Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(bots): render the local settings pages for a teammate on another computer
nana7b8c810942f8
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceProviderMemory.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceProviderMemory.test.tsindex 5ee898565c..f7d6e2436b 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceProviderMemory.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceProviderMemory.test.ts@@ -20,6 +20,7 @@ const management = {blocks: [{ id: 'memory', primitive: 'form', fallbackMarkdown: 'Memory', data: { actionId: 'grant', values: { memory: true, userContext: '' } } }] })),getEditor: vi.fn(async (_context: unknown, id: string) => ({ ref: ref(id), revision: 'list', display: { title: 'Saved Memories' }, links: [], blocks: [] })),getInvitation: vi.fn(), invoke: vi.fn(), bindResource: vi.fn(),+ settingsHost: { invoke: vi.fn(async () => ({ effects: [], result: { ok: true, value: 'hosted' } })) },};registerBotRemoteResourceProvider(management as unknown as typeof botRemoteManagement);const context = { controllerDeviceId: 'phone' };@@ -40,3 +41,13 @@ it('forwards the optional query and the declared primitives to the memory page',await remoteResourceRegistry.get(context, { client, ref: ref('settings:bot-1/memory') });expect(management.getEditor).toHaveBeenLastCalledWith(context, 'settings:bot-1/memory', 'zh-CN', { query: undefined, primitives: ['form', 'search'] });});++it('declares the desktop teammate-settings action beside create, and routes it to the settings host only', async () => {+ const manifest = remoteResourceRegistry.manifest(context, { client: { protocolVersion: 1, primitives: [] } });+ const actions = manifest.collections.find(collection => collection.id === 'teammates')?.actions?.map(action => action.id);+ expect(actions).toEqual(expect.arrayContaining(['open-create', 'management:settings']));+ const request = { client: { protocolVersion: 1, primitives: [] }, collectionId: 'teammates', actionId: 'management:settings', resourceRef: ref('bot-1'), input: { v: 1, op: 'caps' } };+ await expect(remoteResourceRegistry.invoke(context, request)).resolves.toMatchObject({ result: { ok: true, value: 'hosted' } });+ expect(management.settingsHost.invoke).toHaveBeenCalledWith(context, expect.objectContaining({ actionId: 'management:settings' }));+ expect(management.invoke).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSettingsHost.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSettingsHost.test.tsnew file mode 100644index 0000000000..0ce34df048--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSettingsHost.test.ts@@ -0,0 +1,136 @@+/**+ * 测试价值+ * - 生产入口与可观察结果:`createBotRemoteSettingsHost(...).invoke` 配合 `createBotRemoteSettingsOps`——远程桌面的伙伴设置页经+ * `management:settings` 发来的每个操作,返回的数据/错误形状,以及调用到的服务。+ * - Bug/规则依据:cindy-bots-runtime.md「远程设置」:凭证与本机路径不出主机、提升权限仍走确认表单、隐藏/归档伙伴只在本机恢复、+ * revision 冲突(BOT_MEMORY_CHANGED)必须让页面看得到(registry 适配层会把普通异常折叠成 INTERNAL)。+ * - 现有覆盖缺口:botRemoteSettingsResource/Editors 测的是通用表单资源,没有覆盖这条与本机页面同形的操作面。+ * - 最小失败输入:permissions 补丁;隐藏伙伴;owner 切换后才返回的结果;memory 冲突。+ * - tier:unit(进程内 fake 服务,无 DB)。+ */+import { expect, it, vi } from 'vitest';+import type { RemoteActionInvokeRequest } from '@cindy/device-link';+import { BOT_MEMORY_CHANGED } from '../../../../shared/botMemory.js';+import { BOT_SETTINGS_ACTION_ID, type BotSettingsResult } from '../../../../shared/botRemoteSettings.js';+import { createIpcError } from '../../../../shared/ipc-errors.js';+import { RemoteResourceRegistryError } from '../../../device-link/remoteResourceRegistry.js';+import { createBotRemoteSettingsHost } from '../botRemoteSettingsHost.js';+import { createBotRemoteSettingsOps, projectBotSettingsProfile, type BotSettingsOpsDeps } from '../botRemoteSettingsOps.js';++const rawProfile = {+ id: 'bot-1',+ name: 'Sora',+ homeDir: '/Users/owner/Library/bots/bot-1',+ lastMessagePreview: 'private',+ lastMessageAt: 1,+ lastMessageRole: 'assistant',+ unreadCount: 3,+ capabilities: { permissions: 'ask', memory: true },+ sessions: [+ { id: 'main', title: 'Main', kind: 'chat', role: 'canonical', updatedAt: 1, status: 'active', runtimeSnapshot: { configured: { workingDir: '/secret' } } },+ { id: 'old', title: 'Old', kind: 'history', role: 'history', updatedAt: 1, status: 'archived' },+ { id: 'lane', title: 'IM lane', kind: 'channel', role: 'channel', updatedAt: 1, status: 'active' },+ { id: 'group', title: 'Group lane', kind: 'group', role: 'group', updatedAt: 1, status: 'active' },+ ],+};++function setup(overrides: { allowed?: boolean; visible?: boolean; ownerCurrent?: () => boolean; deps?: Partial<BotSettingsOpsDeps> } = {}) {+ const deps = {+ readProfile: vi.fn(async () => rawProfile),+ updateProfile: vi.fn(async () => rawProfile),+ setAvatar: vi.fn(async () => rawProfile),+ retryInvitation: vi.fn(async () => undefined),+ lifecycle: vi.fn(async () => ({ botId: 'bot-1', action: 'restart', status: 'active', affected: {} })),+ defaultModelChain: vi.fn(async () => []),+ memory: { list: vi.fn(), read: vi.fn(), update: vi.fn(), delete: vi.fn() },+ canonicalSessionId: vi.fn(async () => 'main'),+ capabilities: vi.fn(async () => []),+ personalSkills: vi.fn(async () => []),+ autonomy: { get: vi.fn(), set: vi.fn(), reset: vi.fn() },+ searchHistory: vi.fn(async () => ({ results: [] })),+ ...overrides.deps,+ } as unknown as BotSettingsOpsDeps & { updateProfile: ReturnType<typeof vi.fn>; lifecycle: ReturnType<typeof vi.fn>; memory: Record<string, ReturnType<typeof vi.fn>> };+ const host = createBotRemoteSettingsHost({+ owner: () => 'owner-1',+ isOwnerCurrent: overrides.ownerCurrent ? overrides.ownerCurrent : () => true,+ controllerAllowed: () => overrides.allowed ?? true,+ botVisible: async () => overrides.visible ?? true,+ ops: createBotRemoteSettingsOps(deps),+ });+ const call = async (op: string, args?: Record<string, unknown>, botId: string | null = 'bot-1') => {+ const request: RemoteActionInvokeRequest = {+ client: { protocolVersion: 1, primitives: [] },+ collectionId: 'teammates',+ actionId: BOT_SETTINGS_ACTION_ID,+ ...(botId ? { resourceRef: { collectionId: 'teammates', kind: 'bot', id: botId } } : {}),+ input: { v: 1, op, ...(args ? { args } : {}) },+ };+ return (await host.invoke({ controllerDeviceId: 'laptop' }, request)).result as BotSettingsResult<any>;+ };+ return { deps, call, host };+}++it('lists the implemented operations and refuses unknown ones', async () => {+ const { call } = setup();+ const caps = await call('caps', undefined, null);+ expect(caps).toMatchObject({ ok: true, value: { version: 1 } });+ expect((caps as any).value.ops).toEqual(expect.arrayContaining(['caps', 'profile.get', 'profile.update', 'memory.update', 'lifecycle.run']));+ expect(await call('shell.exec')).toMatchObject({ ok: false, code: 'INVALID_PARAMS' });+ // A teammate-scoped operation without a teammate never reaches a service.+ const { deps, call: bare } = setup();+ expect(await bare('profile.get', undefined, null)).toMatchObject({ ok: false, code: 'INVALID_PARAMS' });+ expect(deps.readProfile).not.toHaveBeenCalled();+});++it('does not run anything for a controller that lost authorization or for a hidden teammate', async () => {+ const revoked = setup({ allowed: false });+ expect(await revoked.call('profile.update', { patch: { name: 'x' } })).toMatchObject({ ok: false, code: 'PRECONDITION_FAILED' });+ expect(revoked.deps.updateProfile).not.toHaveBeenCalled();+ const hidden = setup({ visible: false });+ expect(await hidden.call('profile.get')).toMatchObject({ ok: false, code: 'NOT_FOUND' });+ expect(hidden.deps.readProfile).not.toHaveBeenCalled();+});++it('never delivers a result produced after the account changed', async () => {+ let current = true;+ const { call } = setup({ ownerCurrent: () => current, deps: { readProfile: vi.fn(async () => { current = false; return rawProfile; }) } });+ await expect(call('profile.get')).rejects.toBeInstanceOf(RemoteResourceRegistryError);+});++it('projects the profile without the Home path, previews, runtime snapshots or hidden lanes', () => {+ const projected = projectBotSettingsProfile(rawProfile) as { sessions: Array<{ id: string }> };+ expect(projected).not.toHaveProperty('homeDir');+ expect(projected).not.toHaveProperty('lastMessagePreview');+ expect(projected).not.toHaveProperty('unreadCount');+ expect(projected.sessions.map((session) => session.id)).toEqual(['main', 'old']);+ expect(JSON.stringify(projected)).not.toContain('/secret');+});++it('writes only the fields the settings pages edit, and never a permission change', async () => {+ const { deps, call } = setup();+ const saved = await call('profile.update', { patch: { description: 'Designer', capabilities: { memory: false, mcpServers: ['a'] } } });+ expect(saved.ok).toBe(true);+ expect(deps.updateProfile).toHaveBeenCalledWith({ id: 'bot-1', description: 'Designer', capabilities: { memory: false, mcpServers: ['a'] } });+ for (const patch of [{ capabilities: { permissions: 'trusted' } }, { hidden: true }, { enabled: false }, {}, 'x']) {+ expect(await call('profile.update', { patch })).toMatchObject({ ok: false, code: 'INVALID_PARAMS' });+ }+ expect(deps.updateProfile).toHaveBeenCalledTimes(1);+});++it('lets the page see a memory revision conflict and hides unexpected failures', async () => {+ const conflict = setup({ deps: { memory: { update: vi.fn(async () => { throw createIpcError('PRECONDITION_FAILED', BOT_MEMORY_CHANGED); }) } as never } });+ expect(await conflict.call('memory.update', { filename: 'user_a.md', title: 't', body: 'b', expectedUpdatedAt: '2026-01-01T00:00:00Z' }))+ .toEqual({ ok: false, code: 'PRECONDITION_FAILED', message: BOT_MEMORY_CHANGED });+ const broken = setup({ deps: { readProfile: vi.fn(async () => { throw new Error('/Users/owner/secret.db is locked'); }) } });+ await expect(broken.call('profile.get')).rejects.toMatchObject({ code: 'INTERNAL', message: 'Settings operation failed' });+});++it('restricts lifecycle operations to the ones the settings page offers', async () => {+ const { deps, call } = setup();+ expect(await call('lifecycle.run', { action: 'pause' })).toMatchObject({ ok: false, code: 'INVALID_PARAMS' });+ expect(await call('lifecycle.run', { action: 'delete', confirmName: 'Sora', keepTaskHistory: true, worktreeDisposition: 'retain' })).toMatchObject({ ok: true });+ expect(deps.lifecycle).toHaveBeenCalledWith(+ { botId: 'bot-1', action: 'delete', confirmName: 'Sora', worktreeDisposition: 'retain', keepTaskHistory: true },+ expect.any(Function),+ );+});diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteManagement.ts b/apps/desktop/src/main/localDb/ipc/botRemoteManagement.tsindex 8bbdf058d9..f739353dfa 100644--- a/apps/desktop/src/main/localDb/ipc/botRemoteManagement.ts+++ b/apps/desktop/src/main/localDb/ipc/botRemoteManagement.ts@@ -1,11 +1,11 @@-import { getBotAutonomySettingsView, setBotAutonomySchedulerBotId } from '../../bot-autonomy/hub.js';+import { getBotAutonomySettingsView, resetBotAutonomySchedulerSettings, setBotAutonomySchedulerBotId } from '../../bot-autonomy/hub.js';import { readEffectiveBotModelChain } from '../../maker-host/bot-model-chain-settings-store.js';import type { RemoteResourceHostContext } from '../../device-link/remoteResourceRegistry.js';import { botRemoteResourceFromSource } from './botRemoteResourceProjection.js';import { resolveAvailableTaskModels } from '../../maker-ipc/appDefaultModelControl.js';import type { BotModelRoute } from '../../../shared/botModelChain.js';import { createBotRemoteSettingsResource } from './botRemoteSettingsResource.js';-import { createBotProfile, createBotCanonicalSession, getBotMemoryService, getBotRemoteResourceSource, getBotRemoteSettingsSource, setBotProfileAvatar, updateBotProfile } from './bots.js';+import { createBotProfile, createBotCanonicalSession, getBotMemoryService, getBotRemoteResourceSource, getBotRemoteSettingsSource, readBotSettingsProfile, searchBotHistory, setBotProfileAvatar, updateBotProfile } from './bots.js';import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../appSessionState.js';import { throwIpcError } from '../../utils/ipcValidate.js';import { listBotSkillsForBot, readBotSkillForBot, saveBotSkillForSession, deleteBotSkillForBot } from '../../maker-ipc/botSkillService.js';@@ -14,6 +14,11 @@ import { createBotRemoteEditors } from './botRemoteEditors.js';import { decodeBotAvatarImage } from './botAvatarSelection.js';import { runRegisteredBotLifecycleAction } from '../../maker-ipc/botLifecycleService.js';import { listBotSettingsCapabilities, validateBotCapabilityAdditions } from '../../maker-host/index.js';+import { isProviderSharePeer, isSharedTaskPeer } from '@cindy/device-link';+import { readDeviceLinkSettings } from '../../device-link/settings-store.js';+import { readRemoteBotSessionAccess } from './botRemoteSessionAccess.js';+import { createBotRemoteSettingsHost } from './botRemoteSettingsHost.js';+import { createBotRemoteSettingsOps } from './botRemoteSettingsOps.js';async function validateModelChain(chain: BotModelRoute[]) {const scope = activeOwnerScopeKey();@@ -131,4 +136,41 @@ async function getInvitation(context: RemoteResourceHostContext, botId: string)return { effects: [{ kind: 'refresh-collection', collectionId: 'teammates' }] };});}-export const botRemoteManagement = { ...settings, getEditor, getInvitation };+/**+ * The teammate settings pages of a remote Desktop (`management:settings`): the same pages, with every read and+ * write executed here by the services the local IPC handlers call.+ */+const settingsHost = createBotRemoteSettingsHost({+ owner: deps.owner,+ isOwnerCurrent: owner => !isAppSessionBoundaryPending() && owner === activeOwnerScopeKey(),+ // Same gate as the Skill / plugin management: a same-account controller the owner still allows.+ controllerAllowed: peer => {+ const current = readDeviceLinkSettings();+ return !isSharedTaskPeer(peer) && !isProviderSharePeer(peer) && current.remoteControlEnabled && !current.revokedControllers.includes(peer);+ },+ botVisible: async botId => (await readRemoteBotSessionAccess(botId, 'bot')) === 'visible',+ ops: createBotRemoteSettingsOps({+ readProfile: readBotSettingsProfile,+ updateProfile: input => updateBotProfile(input, undefined, validateBotCapabilityAdditions),+ async setAvatar(botId, avatarImageBase64) {+ const image = decodeBotAvatarImage(avatarImageBase64);+ if (!image) throwIpcError('INVALID_PARAMS', 'Avatar required');+ return setBotProfileAvatar(botId, image!);+ },+ retryInvitation: botId => updateBotProfile({ id: botId, retryInvitation: true }),+ lifecycle: (request, guard) => runRegisteredBotLifecycleAction(request, guard),+ defaultModelChain: () => readEffectiveBotModelChain({}),+ memory: {+ list: (botId, query) => getBotMemoryService().list(botId, query),+ read: (botId, filename) => getBotMemoryService().read(botId, filename),+ update: input => getBotMemoryService().update(input),+ delete: input => getBotMemoryService().delete(input),+ },+ canonicalSessionId: async botId => (await getBotRemoteSettingsSource(botId)).source.canonicalSessionId ?? null,+ capabilities: (callerSessionId, kind) => listBotSettingsCapabilities({ callerSessionId, kind }),+ personalSkills: listBotSkillsForBot,+ autonomy: { get: getBotAutonomySettingsView, set: setBotAutonomySchedulerBotId, reset: resetBotAutonomySchedulerSettings },+ searchHistory: searchBotHistory,+ }),+});+export const botRemoteManagement = { ...settings, getEditor, getInvitation, settingsHost };diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteResourceProvider.ts b/apps/desktop/src/main/localDb/ipc/botRemoteResourceProvider.tsindex 98c777d710..18c55d076b 100644--- a/apps/desktop/src/main/localDb/ipc/botRemoteResourceProvider.ts+++ b/apps/desktop/src/main/localDb/ipc/botRemoteResourceProvider.ts@@ -14,6 +14,7 @@ import { WORKING_PHASES } from '../../../shared/workingStatus.js';import { resolveSystemLocale } from '../../../shared/locale.js';import type { botRemoteManagement } from './botRemoteManagement.js';import { editorCopy } from './botRemoteEditors.js';+import { BOT_SETTINGS_ACTION_ID } from '../../../shared/botRemoteSettings.js';import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from '../../device-link/broadcast-tap.js';import {getBotRemoteResourceSource,@@ -60,7 +61,8 @@ export function registerBotRemoteResourceProvider(management?: typeof botRemoteMtitle: TEAMMATES_TITLE,placement: 'home-scope',icon: { name: 'users', fallbackText: '••' },- ...(management ? { actions: [{ id: 'open-create', label: editorCopy.create }] } : {}),+ // `management:settings` tells a desktop controller this host runs the teammate settings pages itself.+ ...(management ? { actions: [{ id: 'open-create', label: editorCopy.create }, { id: BOT_SETTINGS_ACTION_ID, label: 'Teammate settings' }] } : {}),},async list(_context, request) {const scope = captureDataOwnerBroadcastScope();@@ -163,6 +165,7 @@ export function registerBotRemoteResourceProvider(management?: typeof botRemoteMreturn {effects:[],todo:result ? botTodoRemoteProjection(result) : null};}+ if (management && request.actionId === BOT_SETTINGS_ACTION_ID) return management.settingsHost.invoke(context, request);if (management && request.actionId === 'open-agent-import' && request.resourceRef?.id === 'create') return {effects: [{ kind: 'navigate', target: { kind: 'resource', ref: { collectionId: 'companion-import', kind: 'import', id: 'sources' } } }],};diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteSettingsHost.ts b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsHost.tsnew file mode 100644index 0000000000..5cbaeb99bf--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsHost.ts@@ -0,0 +1,98 @@+import type { RemoteActionInvokeRequest, RemoteActionInvokeResponse } from '@cindy/device-link';+import {+ BOT_SETTINGS_HOST_OPS,+ BOT_SETTINGS_PROTOCOL_VERSION,+ isBotSettingsOp,+ type BotSettingsCaps,+ type BotSettingsOp,+ type BotSettingsResult,+} from '../../../shared/botRemoteSettings.js';+import { extractIpcError } from '../../../shared/ipcError.js';+import type { RemoteResourceHostContext } from '../../device-link/remoteResourceRegistry.js';+import { RemoteResourceRegistryError } from '../../device-link/remoteResourceRegistry.js';++/** What an operation sees: the validated teammate (null for host-wide operations) and its arguments. */+export interface BotSettingsCall {+ controllerDeviceId: string;+ botId: string | null;+ args: Record<string, unknown>;+ /** Throws once the account, the controller's authorization or the teammate's visibility changed. */+ assertCurrent(): void;+}+export type BotSettingsOpHandler = (call: BotSettingsCall) => Promise<unknown>;++export interface BotSettingsHostDeps {+ ops: Partial<Record<BotSettingsOp, BotSettingsOpHandler>>;+ owner(): string;+ isOwnerCurrent(owner: string): boolean;+ /** Same-account controller that is still authorized to control this computer. */+ controllerAllowed(controllerDeviceId: string): boolean;+ /** Hidden and archived teammates are recoverable on the local Desktop only. */+ botVisible(botId: string): Promise<boolean>;+}++/** Codes whose message is written for the user's page and is safe to hand to the controller. */+const FORWARDED_CODES = new Set(['PRECONDITION_FAILED', 'INVALID_PARAMS', 'NOT_FOUND', 'ALREADY_EXISTS', 'UNSUPPORTED_CAPABILITY']);+const BOT_ID = /^[A-Za-z0-9_-]{1,128}$/;+const MAX_MESSAGE = 300;++const failure = (code: string, message: string): BotSettingsResult => ({ ok: false, code, message: message.slice(0, MAX_MESSAGE) });++/**+ * Executes the teammate settings pages' operations for a remote Desktop. It owns admission only+ * (authorization, visibility, owner currency, error shape); each operation calls the same service+ * the local IPC handler calls, so validation and side effects are not duplicated here.+ */+export function createBotRemoteSettingsHost(deps: BotSettingsHostDeps) {+ const implemented = (): BotSettingsOp[] => (Object.keys(deps.ops) as BotSettingsOp[]).filter(isBotSettingsOp);+ const caps = (): BotSettingsCaps => ({ version: BOT_SETTINGS_PROTOCOL_VERSION, ops: ['caps', ...implemented().filter(op => op !== 'caps')] });++ async function run(context: RemoteResourceHostContext, request: RemoteActionInvokeRequest): Promise<BotSettingsResult> {+ const input = request.input ?? {};+ const op = input.op;+ if (input.v !== BOT_SETTINGS_PROTOCOL_VERSION || !isBotSettingsOp(op)) return failure('INVALID_PARAMS', 'Unknown settings operation');+ const args = input.args === undefined ? {} : input.args;+ if (!args || typeof args !== 'object' || Array.isArray(args)) return failure('INVALID_PARAMS', 'Invalid settings arguments');+ if (!deps.controllerAllowed(context.controllerDeviceId)) return failure('PRECONDITION_FAILED', 'Remote control is unavailable');+ const owner = deps.owner();+ const botScoped = !BOT_SETTINGS_HOST_OPS.includes(op);+ let botId: string | null = null;+ if (botScoped) {+ const ref = request.resourceRef;+ if (ref?.collectionId !== 'teammates' || ref.kind !== 'bot' || !BOT_ID.test(ref.id)) return failure('INVALID_PARAMS', 'Teammate required');+ botId = ref.id;+ }+ const assertCurrent = () => {+ if (!deps.isOwnerCurrent(owner) || !deps.controllerAllowed(context.controllerDeviceId))+ throw new RemoteResourceRegistryError('NOT_FOUND', 'Account changed');+ };+ try {+ if (op === 'caps') return { ok: true, value: caps() };+ const handler = deps.ops[op];+ if (!handler) return failure('UNSUPPORTED_CAPABILITY', 'Update Cindy on the teammate’s computer');+ if (botId && !(await deps.botVisible(botId))) {+ assertCurrent();+ return failure('NOT_FOUND', 'Teammate unavailable');+ }+ assertCurrent();+ const value = await handler({ controllerDeviceId: context.controllerDeviceId, botId, args: args as Record<string, unknown>, assertCurrent });+ // A result produced for another account or after a revoke must never be delivered.+ assertCurrent();+ return { ok: true, value };+ } catch (error) {+ if (error instanceof RemoteResourceRegistryError) throw error;+ const ipc = extractIpcError(error);+ // `message` still carries the `[CODE] ` prefix of the IPC error shape; the controller adds its own.+ if (ipc && FORWARDED_CODES.has(ipc.code)) return failure(ipc.code, ipc.message.replace(/^\[[A-Z0-9_]+\]\s*/, ''));+ throw new RemoteResourceRegistryError('INTERNAL', 'Settings operation failed');+ }+ }++ return {+ caps,+ async invoke(context: RemoteResourceHostContext, request: RemoteActionInvokeRequest): Promise<RemoteActionInvokeResponse> {+ return { effects: [], result: await run(context, request) };+ },+ };+}+export type BotRemoteSettingsHost = ReturnType<typeof createBotRemoteSettingsHost>;diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.ts b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.tsnew file mode 100644index 0000000000..41d88014b7--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.ts@@ -0,0 +1,147 @@+import {+ BOT_SETTINGS_CAPABILITY_FIELDS,+ BOT_SETTINGS_PATCH_FIELDS,+ type BotSettingsOp,+} from '../../../shared/botRemoteSettings.js';+import type { BotAutonomySettingsView } from '../../../shared/botAutonomy.js';+import type { BotModelRoute } from '../../../shared/botModelChain.js';+import type { BotLifecycleActionRequest } from '../../../shared/botLifecycle.js';+import type { BotMemoryDeleteInput, BotMemoryUpdateInput } from '../../../shared/botMemory.js';+import type { BotSkillSummary } from '../../../shared/botSkill.js';+import { throwIpcError } from '../../utils/ipcValidate.js';+import type { BotSettingsCall, BotSettingsOpHandler } from './botRemoteSettingsHost.js';++type Kind = 'skill' | 'mcp' | 'toolset';+export interface BotCapabilityCatalogEntry {+ id: string;+ name: string;+ description: string;+ available: boolean;+ joined: boolean;+}++/** Services the local settings IPC already uses; injected so the operations stay free of main singletons. */+export interface BotSettingsOpsDeps {+ readProfile(botId: string): Promise<unknown>;+ updateProfile(input: Record<string, unknown>): Promise<unknown>;+ setAvatar(botId: string, avatarImageBase64: string): Promise<unknown>;+ retryInvitation(botId: string): Promise<unknown>;+ lifecycle(request: BotLifecycleActionRequest, guard: () => Promise<void>): Promise<unknown>;+ defaultModelChain(): Promise<BotModelRoute[]>;+ memory: {+ list(botId: string, query?: string): Promise<unknown>;+ read(botId: string, filename: string): Promise<unknown>;+ update(input: BotMemoryUpdateInput): Promise<unknown>;+ delete(input: BotMemoryDeleteInput): Promise<void>;+ };+ /** Canonical task of a visible teammate (null while it has none). */+ canonicalSessionId(botId: string): Promise<string | null>;+ capabilities(callerSessionId: string, kind: Kind): Promise<BotCapabilityCatalogEntry[]>;+ personalSkills(botId: string): Promise<BotSkillSummary[]>;+ autonomy: {+ get(): Promise<BotAutonomySettingsView>;+ set(schedulerBotId: string | null): Promise<BotAutonomySettingsView>;+ reset(): Promise<BotAutonomySettingsView>;+ };+ searchHistory(botId: string, query: string, limit: number): Promise<unknown>;+}++const fail = (message = 'Invalid settings arguments'): never => throwIpcError('INVALID_PARAMS', message);+const record = (value: unknown, name: string): Record<string, unknown> =>+ value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : fail(`${name} must be an object`);+const text = (value: unknown, name: string, max: number, allowEmpty = false): string =>+ typeof value === 'string' && value.length <= max && (allowEmpty || value.length > 0) ? value : fail(`${name} is invalid`);+const keysWithin = (value: Record<string, unknown>, allowed: readonly string[], name: string) => {+ if (Object.keys(value).some(key => !allowed.includes(key))) fail(`${name} has an unsupported field`);+};+const botOf = (call: BotSettingsCall): string => call.botId ?? fail('Teammate required');++/** Strips what the controller must not receive: Home path, runtime snapshots, last-message content and hidden lanes. */+export function projectBotSettingsProfile(raw: unknown): Record<string, unknown> {+ const { homeDir: _homeDir, lastMessagePreview: _preview, lastMessageAt: _at, lastMessageRole: _role, unreadCount: _unread, sessions, ...profile } =+ record(raw, 'profile') as Record<string, unknown> & { sessions?: unknown };+ return {+ ...profile,+ sessions: (Array.isArray(sessions) ? sessions : []).flatMap(item => {+ const session = item as Record<string, unknown>;+ // Group and IM lanes are not the teammate's own tasks and their records live in the group / IM.+ if (!session || typeof session.id !== 'string' || session.role === 'group' || session.role === 'channel') return [];+ return [{ id: session.id, title: session.title, kind: session.kind, updatedAt: session.updatedAt, status: session.status, role: session.role,+ ...(session.threadRoot ? { threadRoot: session.threadRoot } : {}) }];+ }),+ };+}++/** Whitelist of what an autosave may write; raising permissions stays in the confirmed generic form. */+export function readBotSettingsPatch(value: unknown): Record<string, unknown> {+ const patch = record(value, 'patch');+ keysWithin(patch, BOT_SETTINGS_PATCH_FIELDS, 'patch');+ if (patch.capabilities !== undefined) keysWithin(record(patch.capabilities, 'capabilities'), BOT_SETTINGS_CAPABILITY_FIELDS, 'capabilities');+ if (patch.capabilityBaseline !== undefined) record(patch.capabilityBaseline, 'capabilityBaseline');+ if (!Object.keys(patch).length) fail('patch is empty');+ return patch;+}++const ACTIONS = new Set(['resume', 'restart', 'delete']);+const KINDS: readonly Kind[] = ['skill', 'mcp', 'toolset'];++export function createBotRemoteSettingsOps(deps: BotSettingsOpsDeps): Partial<Record<BotSettingsOp, BotSettingsOpHandler>> {+ return {+ 'profile.get': async call => ({ profile: projectBotSettingsProfile(await deps.readProfile(botOf(call))) }),+ 'profile.update': async call => {+ const botId = botOf(call);+ const patch = readBotSettingsPatch(call.args.patch);+ return { profile: projectBotSettingsProfile(await deps.updateProfile({ id: botId, ...patch })) };+ },+ 'profile.chooseAvatar': async call => ({+ profile: projectBotSettingsProfile(await deps.setAvatar(botOf(call), text(call.args.avatarImageBase64, 'avatarImageBase64', 80_000))),+ }),+ 'profile.retryInvitation': async call => {+ await deps.retryInvitation(botOf(call));+ return { profile: projectBotSettingsProfile(await deps.readProfile(botOf(call))) };+ },+ 'lifecycle.run': async call => {+ const botId = botOf(call);+ const action = text(call.args.action, 'action', 16);+ if (!ACTIONS.has(action)) fail('Unknown lifecycle action');+ const confirmName = call.args.confirmName === undefined ? undefined : text(call.args.confirmName, 'confirmName', 200);+ const worktreeDisposition = call.args.worktreeDisposition === 'retain' || call.args.worktreeDisposition === 'recycle' ? call.args.worktreeDisposition : undefined;+ return deps.lifecycle({ botId, action: action as BotLifecycleActionRequest['action'], confirmName, worktreeDisposition, keepTaskHistory: call.args.keepTaskHistory === true },+ async () => call.assertCurrent());+ },+ 'models.default': async () => ({ modelChain: await deps.defaultModelChain() }),+ 'memory.list': async call => deps.memory.list(botOf(call), call.args.query === undefined ? '' : text(call.args.query, 'query', 200, true)),+ 'memory.read': async call => deps.memory.read(botOf(call), text(call.args.filename, 'filename', 256)),+ 'memory.update': async call => deps.memory.update({+ botId: botOf(call),+ filename: text(call.args.filename, 'filename', 256),+ title: text(call.args.title, 'title', 1_000, true),+ body: text(call.args.body, 'body', 40_000, true),+ expectedUpdatedAt: text(call.args.expectedUpdatedAt, 'expectedUpdatedAt', 64),+ }),+ 'memory.delete': async call => {+ await deps.memory.delete({ botId: botOf(call), filename: text(call.args.filename, 'filename', 256), expectedUpdatedAt: text(call.args.expectedUpdatedAt, 'expectedUpdatedAt', 64) });+ return null;+ },+ 'capabilities.catalog': async call => {+ const botId = botOf(call);+ const callerSessionId = await deps.canonicalSessionId(botId);+ call.assertCurrent();+ if (!callerSessionId) throwIpcError('PRECONDITION_FAILED', 'Missing canonical task');+ const personal = await deps.personalSkills(botId);+ const entries = await Promise.all(KINDS.map(async kind => [kind, await deps.capabilities(callerSessionId, kind)] as const));+ return { personal, entries: Object.fromEntries(entries) };+ },+ 'autonomy.get': async () => deps.autonomy.get(),+ 'autonomy.set': async call => {+ const value = call.args.schedulerBotId;+ if (value !== null && (typeof value !== 'string' || !value.trim() || value.length > 128)) fail('schedulerBotId must be a teammate id or null');+ return deps.autonomy.set(value as string | null);+ },+ 'autonomy.reset': async () => deps.autonomy.reset(),+ 'history.search': async call => {+ const limit = typeof call.args.limit === 'number' && Number.isFinite(call.args.limit) ? Math.max(1, Math.min(50, Math.floor(call.args.limit))) : 20;+ return deps.searchHistory(botOf(call), text(call.args.query, 'query', 500), limit);+ },+ };+}diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex 3874456b94..a9c129f955 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -1313,6 +1313,11 @@ async function readProfile(};}+/** Full profile read for the teammate settings pages (the remote Desktop projects it before sending). */+export async function readBotSettingsProfile(botId: string) {+ return readProfile(getDbClient(), botId);+}+/*** Device-link only needs enough Bot metadata to render the Mobile directory and* open the canonical task. Keep this projection main-side so profile prompts,@@ -2077,6 +2082,42 @@ async function findExistingCindy(client: ReturnType<typeof getDbClient>) {return existing ? readProfile(client, existing.id) : null;}+/** Teammate history search; the local settings IPC and the remote settings host share it. */+export async function searchBotHistory(botId: string, query: string, limit: number) {+ const db = getDbClient().drizzle;+ const [profile] = await db+ .select({ id: botProfiles.id })+ .from(botProfiles)+ .where(eq(botProfiles.id, botId))+ .limit(1);+ if (!profile) throwIpcError('NOT_FOUND', 'Bot 不存在');+ // Group / IM channel lanes only hold hidden channel turns; the group chat or+ // the IM conversation itself is the user's record.+ const links = await db+ .select({ sessionId: botSessionLinks.sessionId })+ .from(botSessionLinks)+ .where(and(+ eq(botSessionLinks.botId, botId),+ ne(botSessionLinks.role, 'group'),+ ne(botSessionLinks.role, 'channel'),+ ));+ return searchConversations(+ {+ query,+ limit,+ semanticMode: 'hybrid',+ filters: {+ status: 'all',+ sessionIds: links.map((row) => row.sessionId),+ },+ },+ // The Bot-owned Session id set above is authoritative. Passing null here+ // allows migrated IM history to retain its original source while keeping+ // the renderer unable to widen the search scope.+ { sessionSources: null },+ );+}+export function registerBotIpc(): void {ipcMain.handle('local-db:bots:generate-avatar', async (event, token: unknown) => {assertTrustedAppRendererEvent(event);@@ -2222,38 +2263,7 @@ export function registerBotIpc(): void {typeof body.limit === 'number' && Number.isFinite(body.limit)? Math.max(1, Math.min(50, Math.floor(body.limit))): 20;- const db = getDbClient().drizzle;- const [profile] = await db- .select({ id: botProfiles.id })- .from(botProfiles)- .where(eq(botProfiles.id, botId))- .limit(1);- if (!profile) throwIpcError('NOT_FOUND', 'Bot 不存在');- // Group / IM channel lanes only hold hidden channel turns; the group chat or- // the IM conversation itself is the user's record.- const links = await db- .select({ sessionId: botSessionLinks.sessionId })- .from(botSessionLinks)- .where(and(- eq(botSessionLinks.botId, botId),- ne(botSessionLinks.role, 'group'),- ne(botSessionLinks.role, 'channel'),- ));- return searchConversations(- {- query,- limit,- semanticMode: 'hybrid',- filters: {- status: 'all',- sessionIds: links.map((row) => row.sessionId),- },- },- // The Bot-owned Session id set above is authoritative. Passing null here- // allows migrated IM history to retain its original source while keeping- // the renderer unable to widen the search scope.- { sessionSources: null },- );+ return searchBotHistory(botId, query, limit);});ipcMain.handle('local-db:bots:create', async (event, raw: unknown) => {diff --git a/apps/desktop/src/renderer/features/bots/BotAutonomySettings.tsx b/apps/desktop/src/renderer/features/bots/BotAutonomySettings.tsxindex a11d5ca5c3..d431109ea2 100644--- a/apps/desktop/src/renderer/features/bots/BotAutonomySettings.tsx+++ b/apps/desktop/src/renderer/features/bots/BotAutonomySettings.tsx@@ -15,12 +15,7 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { Switch } from '@/components/ui/switch';import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';import { toast } from '@/lib/toast';-import {- resetBotAutonomySettings,- setBotSchedulerBotId,- useBotAutonomySettings,- useBotProfiles,-} from './botStore';+import { useBotSettingsTarget } from './useBotSettingsTarget';const TITLE_CLASS = 'text-13 font-medium leading-5 text-[var(--text-primary)]';const HINT_CLASS = 'mt-1 text-12 leading-5 text-[var(--text-secondary)]';@@ -38,8 +33,9 @@ export function BotAutonomySettings({}) {const { t } = useTranslation();const { confirm } = useConfirmDialog();- const settings = useBotAutonomySettings();- const profiles = useBotProfiles();+ const target = useBotSettingsTarget();+ const settings = target.autonomy.useSettings();+ const profiles = target.useRoster();const [pending, setPending] = useState(false);const saving = useRef(false);const currentBot = useRef(botId); currentBot.current = botId;@@ -75,7 +71,7 @@ export function BotAutonomySettings({cancelText: t('bots.autonomy.invitation.notNow'),})) return;if (!isDataOwnerGenerationCurrent(owner) || currentBot.current !== botId) return;- await setBotSchedulerBotId(next ? botId : null);+ await target.autonomy.setSchedulerBotId(next ? botId : null);if (isDataOwnerGenerationCurrent(owner) && currentBot.current === botId) setMovedFrom(next ? previous : null);});};@@ -103,7 +99,7 @@ export function BotAutonomySettings({tone="quiet"className="-ml-3 mt-1"disabled={pending}- onClick={() => run(resetBotAutonomySettings, () => setMovedFrom(null))}+ onClick={() => run(target.autonomy.reset, () => setMovedFrom(null))}>{t('settings.defaults.restore')}</Button>diff --git a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsxindex fd31ebb56d..fcfc97d618 100644--- a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx+++ b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx@@ -3,25 +3,13 @@ import { Switch } from '@/components/ui/switch';import { Input } from '@/components/ui/input';import { cn } from '@/lib/utils';import { ChevronDown, Search } from 'lucide-react';-import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { useBotTranslation } from './botPronounContext';-import {- getEffectiveBotModelChain,- subscribeBotGlobalModel,- type BotCapabilities,- type BotProfile,-} from './botStore';-import * as sessionService from '@/lib/sessionService';-import { onPatch } from '@/lib/sessionsBus';-import type { Session } from '@/lib/ccAgent.types';-import {- getDataOwnerGeneration,- isDataOwnerGenerationCurrent,- isDataOwnerPushCurrent,-} from '@/contexts/dataOwnerGeneration';+import type { BotCapabilities, BotProfile } from './botStore';+import type { BotCapabilityEntry as Entry, BotCapabilityKind as Kind } from './botSettingsTarget';+import { useBotSettingsTarget } from './useBotSettingsTarget';+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';-type Kind = 'skill' | 'mcp' | 'toolset';-type Entry = { id: string; name: string; description?: string; available: boolean; personal?: boolean };const kinds: Kind[] = ['toolset', 'mcp', 'skill'];/** References are edited per companion; shared installations and connections stay host-owned. */@@ -53,13 +41,11 @@ export function BotCapabilitySettings({const [error, setError] = useState(false);const [query, setQuery] = useState('');const selected = { skill: skills, mcp: capabilities.mcpServers, toolset: capabilities.toolsets };+ const target = useBotSettingsTarget();// Followed defaults can change when providers / available harnesses change, even- // if the local profile still holds the previous modelChain snapshot.- useSyncExternalStore(subscribeBotGlobalModel, () => JSON.stringify(getEffectiveBotModelChain()));- const modelChain =- capabilities.modelChainOverride === null- ? getEffectiveBotModelChain()- : capabilities.modelChain;+ // if the profile still holds the previous modelChain snapshot.+ const defaultChain = target.useDefaultModelChain();+ const modelChain = capabilities.modelChainOverride === null ? defaultChain : capabilities.modelChain;const modelChainKey = JSON.stringify(modelChain);const catalogKey = JSON.stringify([bot.id,@@ -77,37 +63,8 @@ export function BotCapabilitySettings({useEffect(() => {if (!open) return;- const changed = (sessionId: string, patch: Partial<Session>) => {- if (sessionId !== bot.canonicalSessionId) return;- if (- [- 'agentKind',- 'model',- 'providerId',- 'effort',- 'fastMode',- 'runtimeGeneration',- 'runtimeEffective',- 'runtimePending',- 'workingDir',- 'remoteHostId',- ].some((key) => key in patch)- )- refresh();- };- const offLocal = onPatch(changed);- const offPush = window.electronAPI.localDb?.sessionsPush?.onPatched(- ({ sessionId, patch }, stamp) => {- if (isDataOwnerPushCurrent(stamp)) changed(sessionId, patch);- },- );- const offMcp = window.electronAPI.maker.onMcpChanged(refresh);- return () => {- offLocal();- offPush?.();- offMcp();- };- }, [open, bot.canonicalSessionId, refresh]);+ return target.capabilities.watch(bot, refresh);+ }, [open, bot.canonicalSessionId, refresh, target]);useEffect(() => {if (!open) return;@@ -118,70 +75,8 @@ export function BotCapabilitySettings({setError(false);const load = async () => {try {- if (!bot.canonicalSessionId) throw new Error('Missing canonical task');- const session = await sessionService.get(bot.canonicalSessionId);+ const next = await target.capabilities.load(bot, JSON.parse(modelChainKey));if (!isCurrent()) return;- const api = window.electronAPI.maker;- const mcpResult = await api.listCustomMcpServers({- agentKind:- session.runtimePending?.profile.agentKind ??- session.runtimeEffective?.agentKind ??- (session.agentKind === 'codex' || session.agentKind === 'pi'- ? session.agentKind- : 'claude-code'),- botSessionId: bot.canonicalSessionId,- modelChain: JSON.parse(modelChainKey),- });- if (!isCurrent()) return;- const agentKind = mcpResult.agentKind;- if (!agentKind) throw new Error('Missing next-turn route');- const results = await Promise.allSettled([- window.electronAPI.localDb.bots.listSkills(bot.id),- api.listAgentSkills(agentKind, {- forceReload: true,- workingDir: session.workingDir ?? undefined,- remoteHostId: session.remoteHostId ?? undefined,- }),- api.plugins.list(session.workingDir ?? undefined, true, {- botId: bot.id,- agentKind,- remoteHostId: session.remoteHostId,- }),- ]);- if (!isCurrent()) return;- const [personalResult, skillResult, toolsetResult] = results;- const next: Partial<Record<Kind, Entry[]>> = {};- if (skillResult.status === 'fulfilled' && skillResult.value.success) {- // Match resolveBotSkillReferences: the last entry for a name wins.- // Map retains first-seen display order without changing discovery data.- const skillsByName = new Map(- (skillResult.value.skills ?? []).map((item) => [item.name, item]),- );- next.skill = [...skillsByName.values()].map((item) => ({- id: item.name,- name: item.name,- description: item.description,- available: item.enabled !== false && item.runtimeStatus !== 'failed',- }));- }- if (personalResult.status === 'fulfilled') next.skill = [- ...personalResult.value.map(item => ({ id: `personal:${item.slug}`, name: item.name, available: item.enabled !== false, personal: true })),- ...(next.skill ?? []),- ];- next.mcp = mcpResult.servers.map((item) => ({- id: item.id,- name: item.name,- available: item.available === true,- }));- if (toolsetResult.status === 'fulfilled')- next.toolset = toolsetResult.value- .filter((item) => !['memory', 'xdt_helper', 'scheduler', 'lsp'].includes(item.id))- .map((item) => ({- id: item.id,- name: item.name,- description: item.description,- available: item.available === true,- }));setCatalog({ key: catalogKey, entries: next });setError(kinds.some((kind) => !next[kind]));} catch {@@ -194,7 +89,7 @@ export function BotCapabilitySettings({return () => {requestRef.current += 1;};- }, [open, catalogKey, bot.id, bot.canonicalSessionId, modelChainKey]);+ }, [open, catalogKey, bot.id, bot.canonicalSessionId, modelChainKey, target]);return (<detailsdata-testid="bot-capability-editor"diff --git a/apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx b/apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsxindex a50ab792b2..cf8d1fc380 100644--- a/apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx+++ b/apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx@@ -5,7 +5,7 @@ import { X } from 'lucide-react';import { useTranslation } from 'react-i18next';import type { BotProfile } from './botStore';-import { runBotLifecycleAction } from './botStore';+import { useBotSettingsTarget } from './useBotSettingsTarget';/** Shared destructive confirmation for the roster and teammate settings. */export function BotDeleteDialog({@@ -18,6 +18,7 @@ export function BotDeleteDialog({onDeleted: (botId: string) => void;}) {const { t } = useTranslation();+ const target = useBotSettingsTarget();const inFlight = useRef(false);const [busy, setBusy] = useState(false);const [failed, setFailed] = useState(false);@@ -34,7 +35,7 @@ export function BotDeleteDialog({setBusy(true);setFailed(false);try {- await runBotLifecycleAction({+ await target.lifecycle.run({botId: bot.id,action: 'delete',confirmName: bot.name,diff --git a/apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx b/apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsxindex ac79591f54..a72d413891 100644--- a/apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx@@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next';import type { ConversationSearchJump } from '../../../shared/conversationSearchJump';import type { ConversationSearchResponse } from '../../../shared/conversationSearch';import type { BotProfile } from './botStore';-import { runBotLifecycleAction } from './botStore';+import { useBotSettingsTarget } from './useBotSettingsTarget';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { BotDeleteDialog } from './BotDeleteDialog';@@ -30,6 +30,7 @@ export function BotLifecycleSettings({onOpenSession: (sessionId: string, searchJump?: ConversationSearchJump) => void;}) {const { t } = useTranslation();+ const target = useBotSettingsTarget();const [deleting, setDeleting] = useState(false);const [query, setQuery] = useState('');const [searching, setSearching] = useState(false);@@ -55,7 +56,7 @@ export function BotLifecycleSettings({setActionError(false);try {if (beforeAction && !(await beforeAction())) return;- await runBotLifecycleAction({ botId: bot.id, action });+ await target.lifecycle.run({ botId: bot.id, action });setRestarted(action === 'restart');} catch {setActionError(true);@@ -88,7 +89,7 @@ export function BotLifecycleSettings({setSearchError(false);try {setSearchResult(- await window.electronAPI.localDb.bots.searchHistory({+ await target.history.search({botId: bot.id,query: trimmed,limit: 20,diff --git a/apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx b/apps/desktop/src/renderer/features/bots/BotMemorySettings.tsxindex 9cb3f3f805..e3e85f2072 100644--- a/apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx+++ b/apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx@@ -19,6 +19,7 @@ import {type BotMemorySummary,} from '../../../shared/botMemory';import { useBotTranslation } from './botPronounContext';+import { useBotSettingsTarget } from './useBotSettingsTarget';const SEARCH_DEBOUNCE_MS = 200;const SAVE_DEBOUNCE_MS = 800;@@ -27,7 +28,11 @@ type View ={ kind: 'list' } | { kind: 'detail'; filename: string } | { kind: 'edit'; filename: string };type SaveState = 'idle' | 'saving' | 'saved' | 'error' | 'conflict';-const memoryApi = () => window.electronAPI.localDb.bots.memory;+/** The teammate's computer serves the memory; the pages never assume it is this one. */+function useMemoryApi() {+ const target = useBotSettingsTarget();+ return useCallback(() => target.memory, [target]);+}const isConflict = (error: unknown) => {const ipc = extractIpcError(error);return ipc?.code === 'PRECONDITION_FAILED' && ipc.message.includes(BOT_MEMORY_CHANGED);@@ -159,6 +164,7 @@ function MemoryList({onOpen: (filename: string) => void;}) {const { t } = useBotTranslation();+ const memoryApi = useMemoryApi();const { day } = useDateLabels();const [query, setQuery] = useState('');const [entries, setEntries] = useState<BotMemorySummary[] | null>(null);@@ -309,6 +315,7 @@ function MemoryDetail({onMissing: () => void;}) {const { t } = useBotTranslation();+ const memoryApi = useMemoryApi();const { stamp } = useDateLabels();const { confirm } = useConfirmDialog();const [detail, setDetail] = useState<BotMemoryDetail | null>(null);@@ -442,6 +449,7 @@ function MemoryEditor({onDone: () => void;}) {const { t } = useBotTranslation();+ const memoryApi = useMemoryApi();const { confirm } = useConfirmDialog();const [title, setTitle] = useState(initial.title);const [body, setBody] = useState(initial.body);diff --git a/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx b/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsxindex 0ac7c06963..ad9cdcc470 100644--- a/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx+++ b/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx@@ -12,7 +12,7 @@ import { useCompanionCloud } from './companionCloudStore';import { isBotChannelLaneSession } from './botGroupLane';import { BOT_DM_THREAD_PARAM } from './botDmThreadRoute';import { useRemoteBots } from './useRemoteBots';-import { RemoteBotSettings } from './RemoteBotSettings';+import { RemoteTeammateSettings } from './RemoteTeammateSettings';/** Route-owned compact drawer that keeps the current teammate chat mounted below it. */export function BotSettingsDrawer() {@@ -40,7 +40,7 @@ export function BotSettingsDrawer() {const requestedPage = searchParams.get('settingsPage');const initialPage = requestedPage === 'memory' || requestedPage === 'capabilities' ? requestedPage : 'home';- // 「模型」「语音」「消息平台」只有本机伙伴有; 远端伙伴仍只认上面两页。+ // 「模型」「语音」「消息平台」可直接深链;远程伙伴同样,所在电脑不支持的页会回到设置首页。const localInitialPage =requestedPage === 'model' || requestedPage === 'voice' || requestedPage === 'channels'? requestedPage@@ -144,11 +144,12 @@ export function BotSettingsDrawer() {</Dialog.Close></header>{remoteBot ? (- <RemoteBotSettings- key={`${remoteBot.deviceId}:${remoteBot.id}:${open}:${initialPage}`}+ <RemoteTeammateSettings+ key={`${remoteBot.deviceId}:${remoteBot.id}:${open}:${localInitialPage}`}bot={remoteBot}- initialPage={initialPage}+ initialPage={localInitialPage}beforeCloseRef={beforeCloseRef}+ onBack={performClose}onDeleted={() => {allowNavigation.current = true;navigate('/bots', { replace: true });diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsxindex 8d3c841ac8..54d7df8ccf 100644--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx@@ -29,8 +29,6 @@ import { useRegisterContentHeader } from '../feature-context';import {canonicalBotSessionId,hasLoadedBotProfiles,- chooseBotAvatar,- retryBotInvitation,setCanonicalBotSession,updateBotProfile,useBotProfiles,@@ -39,6 +37,7 @@ import {type BotCapabilities,type BotProfile,} from './botStore';+import { useBotSettingsTarget } from './useBotSettingsTarget';import { BotRosterView } from './BotRosterView';import { BotAvatar } from './BotAvatar';import { BotBasicProfileFields } from './BotBasicProfileFields';@@ -50,7 +49,7 @@ import {withBotCanonicalSessionReadTimeout,} from './botNavigation';import { useCompanionCloud } from './companionCloudStore';-import { withoutShadowedBots } from './companionCloudPresentation';+import { cloudCompanionAt, withoutShadowedBots } from './companionCloudPresentation';import { BotHomeComputerSetting } from './BotHomeComputerSetting';import { CindyMergeSetting } from './CindyMergeSetting';import { BotLifecycleSettings } from './BotLifecycleSettings';@@ -110,9 +109,13 @@ export function BotSettings({}) {const { t } = useBotTranslation();const navigate = useNavigate();+ // The computer these pages read from and write to: this one, or the teammate's own computer.+ const target = useBotSettingsTarget();+ const isRemote = target.kind === 'remote';+ const cloud = useCompanionCloud();const [name, setName] = useState(bot.name);const [description, setDescription] = useState(bot.description);- const profiles = useBotProfiles();+ const profiles = target.useRoster();// Same identity rule as creation and the host: NFKC, trimmed, case-insensitive.const nameTaken = !!name.trim() && profiles.some((other) => other.id !== bot.id && other.status !== 'archived'&& normalizeBotName(other.name) === normalizeBotName(name));@@ -124,17 +127,12 @@ export function BotSettings({const [selectedSkills, setSelectedSkills] = useState<string[]>(bot.skills);const [capabilities, setCapabilities] = useState<BotCapabilities>(bot.capabilities);// Live defaults are display state, not form edits: refreshing them must not- // dirty autosave or overwrite a local model override / pending text edits.- useProviders();- const { availableVendors, loaded: availableAgentsLoaded } = useAvailableAgents();- const hiddenVendors = useMemo<MakerVendor[]>(() => {- if (!availableAgentsLoaded) return [];- return (['cc', 'codex', 'pi'] as const).filter((item) => !availableVendors.has(item));- }, [availableAgentsLoaded, availableVendors]);- useSyncExternalStore(subscribeBotGlobalModel, () => JSON.stringify(getEffectiveBotModelChain()));+ // dirty autosave or overwrite a model override / pending text edits.+ const hiddenVendors = target.useHiddenVendors();+ const defaultModelChain = target.useDefaultModelChain();const displayedModelChain =capabilities.modelChainOverride === null- ? getEffectiveBotModelChain()+ ? defaultModelChain: capabilities.modelChain;const [page, setPage] = useState<| 'home'@@ -205,13 +203,13 @@ export function BotSettings({async (payload: BotSettingsPayload) => {savingProfileRef.current = true;try {- await updateBotProfile(bot.id, botSettingsChanges(savedSettingsRef.current, payload, true));+ await target.profile.update(bot.id, botSettingsChanges(savedSettingsRef.current, payload, true));savedSettingsRef.current = payload;} finally {savingProfileRef.current = false;}},- [bot.id],+ [bot.id, target],);const autosave = useBotSettingsAutosave({@@ -376,8 +374,8 @@ export function BotSettings({await autosave.flush();if (autosave.isDirty()) return;const next = portrait- ? await chooseBotAvatar(bot.id, portrait.split(',')[1])- : await chooseBotAvatar(bot.id);+ ? await target.profile.chooseAvatar(bot.id, portrait.split(',')[1])+ : await target.profile.chooseAvatar(bot.id);if (!next) return;setAvatar(next.avatar);setAvatarColor(next.avatarColor);@@ -393,7 +391,8 @@ export function BotSettings({<BotPortraitPickerdisabled={avatarBusy}onChange={portrait => void handleChooseAvatar(portrait)}- onUpload={() => void handleChooseAvatar()}+ // Another computer's file chooser would read that computer's files; the picker reads this one's.+ onUpload={isRemote ? undefined : () => void handleChooseAvatar()}trigger={<buttontype="button"@@ -401,7 +400,7 @@ export function BotSettings({aria-label={t('bots.profile.changeAvatar')}className="relative rounded-full outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50">- <BotAvatar bot={{ name: displayName, avatar, avatarColor }} size="xl" />+ <BotAvatar bot={{ name: displayName, avatar, avatarColor, deviceId: target.deviceId }} size="xl" /><span className="absolute bottom-0 right-0 flex h-6 w-6 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)]"><Camera size={12} aria-hidden="true" /></span>@@ -413,7 +412,7 @@ export function BotSettings({const invitationPending = bot.invitation && bot.invitation.stage !== 'ready'&& !(bot.invitation.stage === 'avatar' && bot.canonicalSessionId);- const settingsRows = [+ const settingsRows = ([['profile', botSettingsIcons.profile, t('bots.profile.title')],['personality', botSettingsIcons.personality, t('bots.profile.personality')],['memory', botSettingsIcons.memory, t('bots.memory.title')],@@ -423,8 +422,9 @@ export function BotSettings({['channels', botSettingsIcons.channels, t('bots.channels.title')],['routines', botSettingsIcons.routines, t('routines.title')],['history', botSettingsIcons.history, t('bots.historySearch.title')],+ // The Home folder is a path on the teammate's own computer.['advanced', botSettingsIcons.advanced, t('bots.homeFolder.title')],- ] as const;+ ] as const).filter(([id]) => target.pages.has(id));return (<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pb-8"><div className="mx-auto w-full max-w-xl">@@ -434,7 +434,7 @@ export function BotSettings({onRetry={async () => {// A retry must use the confirmed selection, never race an autosave.if (!await canLeave()) throw new Error('Bot settings have not been saved');- await retryBotInvitation(bot.id);+ await target.profile.retryInvitation(bot.id);}} />) : null}<div className="flex min-h-12 flex-wrap items-center justify-between gap-3">@@ -523,8 +523,20 @@ export function BotSettings({</button>))}</div>- <BotHomeComputerSetting bot={bot} />- <CindyMergeSetting bot={bot} />+ {!isRemote ? (+ <>+ <BotHomeComputerSetting bot={bot} />+ <CindyMergeSetting bot={bot} />+ </>+ ) : cloudCompanionAt(cloud, target.deviceId!, bot.id) ? (+ // The main computer can be changed from any computer (it is asked to hand the companion over).+ <>+ <BotHomeComputerSetting bot={{ id: bot.id, name: bot.name }} />+ <CindyMergeSetting bot={{ id: bot.id, name: bot.name }} />+ </>+ ) : (+ <p className="mt-4 truncate text-12 text-[var(--text-tertiary)]">{target.deviceName}</p>+ )}<div className="mt-6"><BotLifecycleSettingsbot={bot}@@ -560,7 +572,7 @@ export function BotSettings({type="button"onClick={() => {setPortraitRetryFailed(false);- void retryBotInvitation(bot.id).catch(() => setPortraitRetryFailed(true));+ void target.profile.retryInvitation(bot.id).catch(() => setPortraitRetryFailed(true));}}disabled={bot.invitation.stage === 'avatar'}className="ml-2 text-[var(--text-primary)] underline underline-offset-2 disabled:opacity-50"@@ -603,8 +615,9 @@ export function BotSettings({<BotModelChainEditorlabel={t('bots.model.primary')}hiddenVendors={hiddenVendors}+ deviceId={target.deviceId}onRestoreDefault={() => {- const modelChain = getEffectiveBotModelChain();+ const modelChain = defaultModelChain;const primary = modelChain[0];setCapabilities((current) => ({...current,@@ -636,7 +649,7 @@ export function BotSettings({/></div><BotTaskModelEditor value={capabilities.taskModelOverride ?? null}- inheritedRoute={displayedModelChain[0]} hiddenVendors={hiddenVendors}+ inheritedRoute={displayedModelChain[0]} hiddenVendors={hiddenVendors} deviceId={target.deviceId}onChange={taskModelOverride => {setCapabilities(current => ({ ...current, taskModelOverride }));autosave.onEdit('instant');@@ -646,7 +659,8 @@ export function BotSettings({{page === 'capabilities' && (<div><BotCapabilitySettings- onConfigure={(kind, id) => {+ // These open the settings of the computer this window runs on, not the teammate's.+ onConfigure={isRemote ? undefined : (kind, id) => {void canLeave().then(ok => {if (!ok) return;const toolSettings: Record<string, string> = {diff --git a/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsx b/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsxnew file mode 100644index 0000000000..fd562eb7cf--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsx@@ -0,0 +1,181 @@+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type MutableRefObject } from 'react';+import { useNavigate } from 'react-router-dom';+import { useTranslation } from 'react-i18next';+import { REMOTE_RESOURCE_CHANGED_CHANNEL, parseRemoteResourceChangedPayload } from '@cindy/device-link';++import { Button } from '@/components/ui/button';+import { Spinner } from '@/components/ui/spinner';+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';+import { extractIpcError } from '@/utils/ipcError';+import type { BotSettingsOp } from '../../../shared/botRemoteSettings';+import { BotPronounProvider } from './botPronounContext';+import { BotSettings } from './BotsHomeView';+import { BotSettingsTargetContext } from './botSettingsTarget';+import { RemoteBotSettings } from './RemoteBotSettings';+import { createRemoteBotSettingsTarget, type RemoteBotSettingsHandle } from './remoteBotSettingsTarget';+import { hostDeclaresBotSettings, readBotSettingsCaps } from './remoteBotSettingsClient';+import type { RemoteBot } from './remoteBotRoster';+import type { ConversationSearchJump } from '../../../shared/conversationSearchJump';+import type { BotProfile } from './botStore';++interface Props {+ bot: RemoteBot;+ initialPage?: 'home' | 'memory' | 'capabilities' | 'model' | 'voice' | 'channels';+ beforeCloseRef: MutableRefObject<(() => Promise<boolean>) | null>;+ onBack: () => void;+ onDeleted: () => void;+}++type Support =+ | { state: 'checking' }+ | { state: 'unsupported' }+ | { state: 'failed' }+ | { state: 'ready'; ops: ReadonlySet<BotSettingsOp> };++/** Re-read trailing edge: a chat full of replies changes the teammate row constantly. */+const REFRESH_DELAY_MS = 400;++/**+ * Teammate settings for a teammate on another computer. The pages are the local ones (`BotSettings`);+ * their reads and writes run on the teammate's computer. A computer that predates the settings host+ * keeps the generic form page.+ */+export function RemoteTeammateSettings(props: Props) {+ const owner = getDataOwnerGeneration();+ return <RemoteTeammateSettingsContent key={`${owner.dataOwnerId}:${owner.generation}:${props.bot.deviceId}:${props.bot.id}`} {...props} />;+}++function RemoteTeammateSettingsContent(props: Props) {+ const { bot } = props;+ const { t } = useTranslation();+ const [support, setSupport] = useState<Support>({ state: 'checking' });+ const [attempt, setAttempt] = useState(0);+ // Probe while the computer is reachable; going offline keeps what was already learned.+ useEffect(() => {+ if (!bot.online) return;+ let cancelled = false;+ void (async () => {+ try {+ if (!(await hostDeclaresBotSettings(bot.deviceId))) return !cancelled && setSupport({ state: 'unsupported' });+ const caps = await readBotSettingsCaps(bot.deviceId);+ if (!cancelled) setSupport({ state: 'ready', ops: new Set(caps.ops) });+ } catch (error) {+ // An older host rejects the unknown action; anything else is a failed read the person can retry.+ if (!cancelled) setSupport(extractIpcError(error)?.code === 'UNSUPPORTED_CAPABILITY' ? { state: 'unsupported' } : { state: 'failed' });+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [bot.deviceId, bot.online, attempt]);++ if (support.state === 'unsupported')+ return <RemoteBotSettings bot={bot} initialPage={props.initialPage === 'memory' || props.initialPage === 'capabilities' ? props.initialPage : undefined} beforeCloseRef={props.beforeCloseRef} onDeleted={props.onDeleted} />;+ if (support.state === 'ready') return <RemoteSettingsPages {...props} ops={support.ops} />;+ return (+ <div className="min-h-0 flex-1 overflow-y-auto p-5 text-13 text-[var(--text-primary)]">+ {!bot.online ? (+ <p role="status">{t('bots.remote.offlineDescription', { name: bot.name, device: bot.deviceName })}</p>+ ) : support.state === 'failed' ? (+ <div role="alert" className="space-y-2">+ <p>{t('bots.remoteSettings.loadFailed')}</p>+ <Button variant="secondary" compact onClick={() => { setSupport({ state: 'checking' }); setAttempt((value) => value + 1); }}>{t('bots.retry')}</Button>+ </div>+ ) : (+ <Spinner size={18} />+ )}+ </div>+ );+}++function RemoteSettingsPages({ bot, ops, initialPage: requestedPage = 'home', beforeCloseRef, onBack }: Props & { ops: ReadonlySet<BotSettingsOp> }) {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const online = useRef(bot.online);+ online.current = bot.online;+ const handle = useMemo<RemoteBotSettingsHandle>(+ () => createRemoteBotSettingsTarget({ deviceId: bot.deviceId, deviceName: bot.deviceName, botId: bot.id, ops, online: () => online.current }),+ [bot.deviceId, bot.deviceName, bot.id, ops],+ );+ const profile = useSyncExternalStore(handle.profiles.subscribe, handle.profiles.get);+ // A page this computer cannot serve falls back to the settings home.+ const initialPage = requestedPage === 'home' || handle.target.pages.has(requestedPage) ? requestedPage : 'home';+ const [status, setStatus] = useState<'loading' | 'ready' | 'failed' | 'gone'>('loading');+ const load = useCallback(() => {+ setStatus('loading');+ void handle.profiles.load().then(+ () => setStatus('ready'),+ (error) => setStatus(extractIpcError(error)?.code === 'NOT_FOUND' ? 'gone' : 'failed'),+ );+ }, [handle]);+ useEffect(() => {+ if (bot.online) load();+ // Reload on (re)connect; a profile that was already read stays on screen while offline.+ }, [handle, bot.online, load]);++ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ useEffect(+ () =>+ window.electronAPI.deviceLink.onRemotePush((push, stamp) => {+ const payload = parseRemoteResourceChangedPayload(push.payload);+ if (+ push.deviceId !== bot.deviceId ||+ push.channel !== REMOTE_RESOURCE_CHANGED_CHANNEL ||+ payload?.collectionId !== 'teammates' ||+ (payload.resourceRefs?.length && !payload.resourceRefs.some((ref) => ref.kind === 'bot' && ref.id === bot.id)) ||+ !isDeviceLinkRemotePushCurrent(push, stamp)+ )+ return;+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(() => handle.changed(), REFRESH_DELAY_MS);+ }),+ [bot.deviceId, bot.id, handle],+ );+ useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []);++ const onOpenSession = useCallback(+ (sessionId: string, searchJump?: ConversationSearchJump) => {+ const projection = profile?.sessions.find((item) => item.id === sessionId);+ const base = `/bots/remote/${encodeURIComponent(bot.deviceId)}/${encodeURIComponent(bot.id)}`;+ if (projection?.kind === 'history') navigate(`${base}/history/${encodeURIComponent(sessionId)}`, { state: searchJump ? { searchJump } : undefined });+ else if (projection?.role === 'canonical') navigate(base, { state: searchJump ? { searchJump } : undefined });+ },+ [bot.deviceId, bot.id, navigate, profile],+ );++ if (!profile) {+ return (+ <div className="min-h-0 flex-1 overflow-y-auto p-5 text-13 text-[var(--text-primary)]">+ {!bot.online ? (+ <p role="status">{t('bots.remote.offlineDescription', { name: bot.name, device: bot.deviceName })}</p>+ ) : status === 'failed' || status === 'gone' ? (+ <div role="alert" className="space-y-2">+ <p>{t('bots.remoteSettings.loadFailed')}</p>+ <Button variant="secondary" compact onClick={load}>{t('bots.retry')}</Button>+ </div>+ ) : (+ <Spinner size={18} />+ )}+ </div>+ );+ }+ return (+ <BotSettingsTargetContext.Provider value={handle.target}>+ <BotPronounProvider bot={profile as BotProfile}>+ {/* The status line keeps its height whether or not it has text, so the pages never jump. */}+ <p role="status" className="shrink-0 truncate px-5 pt-2 text-12 leading-5 text-[var(--text-secondary)] min-h-7">+ {!bot.online ? t('bots.remote.offlineDescription', { name: bot.name, device: bot.deviceName }) : ''}+ </p>+ <BotSettings+ key={`${bot.deviceId}:${bot.id}:${initialPage}`}+ initialPage={initialPage}+ beforeCloseRef={beforeCloseRef}+ bot={profile}+ onBack={onBack}+ onOpenSession={onOpenSession}+ />+ </BotPronounProvider>+ </BotSettingsTargetContext.Provider>+ );+}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSettingsDrawer.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSettingsDrawer.test.tsxindex 39ab275d64..b3c2b69463 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botSettingsDrawer.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSettingsDrawer.test.tsx@@ -32,7 +32,7 @@ vi.mock('../botPronounContext', () => ({BotPronounProvider: ({ children }: { children: ReactNode }) => children,}));vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => [{ id: 'remote-bot', deviceId: 'other-mac', name: 'Remote' }] }));-vi.mock('../RemoteBotSettings', () => ({ RemoteBotSettings: ({ bot, initialPage }: { bot: { deviceId: string }; initialPage?: string }) => <div data-testid="remote-settings" data-initial-page={initialPage}>{bot.deviceId}</div> }));+vi.mock('../RemoteTeammateSettings', () => ({ RemoteTeammateSettings: ({ bot, initialPage }: { bot: { deviceId: string }; initialPage?: string }) => <div data-testid="remote-settings" data-initial-page={initialPage}>{bot.deviceId}</div> }));vi.mock('../botStore', () => ({useBotProfiles: () => [{ id: 'bot-1', name: 'Filo', status: 'active', sessions: [], capabilities: {}, skills: [] },@@ -145,7 +145,7 @@ describe('BotSettingsDrawer', () => {},);- it('deep-links local teammates to the messaging platforms page but not remote ones', () => {+ it('deep-links local and remote teammates to the messaging platforms page', () => {const local = render(<RouterProviderrouter={createMemoryRouter([{ path: '*', element: <BotSettingsDrawer /> }], {@@ -164,7 +164,8 @@ describe('BotSettingsDrawer', () => {})}/>,);- expect(screen.getByTestId('remote-settings').getAttribute('data-initial-page')).toBe('home');+ // The remote host serves the same pages; one that cannot serve a page falls back to the home itself.+ expect(screen.getByTestId('remote-settings').getAttribute('data-initial-page')).toBe('channels');});it('allows wheel events in portaled model lists while blocking background scrolling', async () => {diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSettingsTarget.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSettingsTarget.test.tsnew file mode 100644index 0000000000..f3d0cb64b0--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSettingsTarget.test.ts@@ -0,0 +1,132 @@+/**+ * 测试价值+ * - 生产入口与可观察结果:`createRemoteBotSettingsTarget`——远程伙伴设置页调用的 profile/memory/capabilities/lifecycle 接口,+ * 以及它们经 `management:settings` 发给伙伴所在电脑的请求与页面看到的结果/错误。+ * - Bug/规则依据:cindy-bots-runtime.md「远程设置」:本机页与远程页同一套组件,自动保存的乐观写入/回滚语义一致;记忆 revision+ * 冲突必须以本机同样的错误形状到达页面;旧主机缺的操作不得出现对应页面。+ * - 现有覆盖缺口:remoteBotSettings.test.tsx 测通用表单页;没有覆盖这条与本机页同形的目标实现。+ * - 最小失败输入:主机拒绝写入;写入在途时的旧读取;超长文本补丁;memory 冲突;只有 profile 操作的旧主机。+ * - tier:unit(假的 deviceLink.invoke,无 DOM)。+ */+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { BOT_MEMORY_CHANGED } from '../../../../shared/botMemory';+import type { BotSettingsOp } from '../../../../shared/botRemoteSettings';+import { extractIpcError } from '../../../utils/ipcError';++const host = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => [] }));+vi.mock('@/hooks/useAvailableAgents', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/hooks/useAvailableAgents')>()), useAvailableAgents: () => ({ availableVendors: new Set(), loaded: false }) }));++import { createRemoteBotSettingsTarget, remoteBotSettingsPages } from '../remoteBotSettingsTarget';++const profile = (patch: Record<string, unknown> = {}) => ({+ id: 'bot-1', name: 'Sora', description: '', identitySource: 'old soul', userContextSource: '', avatar: '🙂', avatarColor: 'teal',+ status: 'active', skills: [], currentVersion: 1, createdAt: 1, sessions: [],+ capabilities: { harness: 'pi', model: 'm', modelChain: [{ harness: 'pi', model: 'm', providerId: null, effort: '', fastMode: false }], memory: true, permissions: 'ask' },+ ...patch,+});+const ok = (value: unknown) => ({ result: { ok: true, value }, effects: [] });+const refused = (code: string, message: string) => ({ result: { ok: false, code, message }, effects: [] });+/** The request a page produced, as the host receives it. */+const sent = (call = 0) => host.invoke.mock.calls[call][2][0] as { input: { op: BotSettingsOp; args?: Record<string, unknown> }; resourceRef?: { id: string } };+const ALL_OPS = ['caps', 'profile.get', 'profile.update', 'profile.chooseAvatar', 'profile.retryInvitation', 'lifecycle.run', 'models.default',+ 'memory.list', 'memory.read', 'memory.update', 'memory.delete', 'capabilities.catalog', 'autonomy.get', 'autonomy.set', 'autonomy.reset', 'history.search'] as BotSettingsOp[];++function create(ops: BotSettingsOp[] = ALL_OPS) {+ return createRemoteBotSettingsTarget({ deviceId: 'mac', deviceName: 'Studio', botId: 'bot-1', ops: new Set(ops), online: () => true });+}++beforeEach(() => {+ host.invoke.mockReset();+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: host.invoke } } });+});+afterEach(() => vi.unstubAllGlobals());++it('applies the host profile after an autosave and sends only what changed', async () => {+ const { target, profiles } = create();+ host.invoke.mockResolvedValueOnce(ok({ profile: profile() }));+ await profiles.load();+ host.invoke.mockResolvedValueOnce(ok({ profile: profile({ description: 'Designer', avatar: '🙂' }) }));+ const next = await target.profile.update('bot-1', { description: 'Designer', capabilities: { memory: false } });+ expect(sent(1)).toMatchObject({ resourceRef: { id: 'bot-1' }, input: { op: 'profile.update', args: { patch: { description: 'Designer', capabilities: { memory: false } } } } });+ expect(next.description).toBe('Designer');+ expect(profiles.get()?.description).toBe('Designer');+});++it('rolls an optimistic write back and rejects with the host error when the host refuses it', async () => {+ const { target, profiles } = create();+ host.invoke.mockResolvedValueOnce(ok({ profile: profile() }));+ await profiles.load();+ host.invoke.mockResolvedValueOnce(refused('INVALID_PARAMS', 'Model route unavailable'));+ const write = target.profile.update('bot-1', { name: 'Renamed' });+ expect(profiles.get()?.name).toBe('Renamed');+ await expect(write).rejects.toSatisfy((error) => extractIpcError(error)?.code === 'INVALID_PARAMS');+ expect(profiles.get()?.name).toBe('Sora');+});++it('ignores a read that was overtaken by a write', async () => {+ const { target, profiles } = create();+ host.invoke.mockResolvedValueOnce(ok({ profile: profile() }));+ await profiles.load();+ let release!: (value: unknown) => void;+ host.invoke.mockReturnValueOnce(new Promise((resolve) => { release = resolve; }));+ const stale = profiles.refresh();+ host.invoke.mockResolvedValueOnce(ok({ profile: profile({ name: 'Renamed' }) }));+ await target.profile.update('bot-1', { name: 'Renamed' });+ release(ok({ profile: profile() }));+ await stale;+ expect(profiles.get()?.name).toBe('Renamed');+});++it('sends long personality and user text as separate requests so none exceeds the invoke input limit', async () => {+ const { target, profiles } = create();+ host.invoke.mockResolvedValueOnce(ok({ profile: profile() }));+ await profiles.load();+ host.invoke.mockResolvedValue(ok({ profile: profile() }));+ const long = '字'.repeat(12_000); // 36 KB in UTF-8+ await target.profile.update('bot-1', { identitySource: long, userContextSource: long, avatarColor: 'blue' });+ const patches = host.invoke.mock.calls.slice(1).map((call) => Object.keys((call[2][0] as { input: { args: { patch: object } } }).input.args.patch));+ expect(patches).toEqual([['avatarColor'], ['identitySource'], ['userContextSource']]);+});++it('hands the memory page the same conflict error the local call raises', async () => {+ const { target } = create();+ host.invoke.mockResolvedValueOnce(refused('PRECONDITION_FAILED', BOT_MEMORY_CHANGED));+ const error = await target.memory.update({ botId: 'bot-1', filename: 'user_a.md', title: 't', body: 'b', expectedUpdatedAt: 'x' }).catch((e) => e);+ expect(extractIpcError(error)).toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(extractIpcError(error)?.message).toContain(BOT_MEMORY_CHANGED);+ expect(sent()).toMatchObject({ resourceRef: { id: 'bot-1' }, input: { op: 'memory.update', args: { filename: 'user_a.md', expectedUpdatedAt: 'x' } } });+});++it('builds the capability lists from the host catalog without the fixed baseline toolsets', async () => {+ const { target } = create();+ host.invoke.mockResolvedValueOnce(ok({+ personal: [{ slug: 'brief', name: 'Brief', description: '', updatedAt: '', enabled: false }],+ entries: {+ skill: [{ id: 'review', name: 'review', description: 'Review', available: true, joined: true }],+ mcp: [{ id: 'm1', name: 'Docs', description: 'http', available: false, joined: false }],+ toolset: [{ id: 'memory', name: 'Memory', description: '', available: true, joined: true }, { id: 'browser', name: 'Browser', description: '', available: true, joined: false }],+ },+ }));+ const catalog = await target.capabilities.load({ id: 'bot-1' } as never, []);+ expect(catalog.skill).toEqual([+ { id: 'personal:brief', name: 'Brief', available: false, personal: true },+ { id: 'review', name: 'review', description: 'Review', available: true },+ ]);+ expect(catalog.mcp).toEqual([{ id: 'm1', name: 'Docs', description: 'http', available: false }]);+ expect(catalog.toolset?.map((item) => item.id)).toEqual(['browser']);+});++it('does not re-read a deleted teammate after the lifecycle action', async () => {+ const { target } = create();+ host.invoke.mockResolvedValueOnce(ok({ botId: 'bot-1', action: 'delete', status: 'deleted', affected: {} }));+ await target.lifecycle.run({ botId: 'bot-1', action: 'delete', confirmName: 'Sora' });+ expect(host.invoke).toHaveBeenCalledTimes(1);+});++it('offers only the pages whose operations the host implements', () => {+ expect([...remoteBotSettingsPages(new Set(ALL_OPS))].sort()).toEqual(['capabilities', 'history', 'memory', 'model', 'personality', 'profile']);+ expect([...remoteBotSettingsPages(new Set<BotSettingsOp>(['caps', 'profile.get', 'profile.update']))].sort()).toEqual(['personality', 'profile']);+ // The Home folder is a path on the teammate's computer: no remote host ever offers it.+ expect(remoteBotSettingsPages(new Set(ALL_OPS)).has('advanced')).toBe(false);+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteTeammateSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteTeammateSettings.test.tsxnew file mode 100644index 0000000000..43d56f13c4--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteTeammateSettings.test.tsx@@ -0,0 +1,114 @@+// @vitest-environment jsdom+/**+ * 测试价值+ * - 生产入口与可观察结果:`RemoteTeammateSettings`——远程控制伙伴时设置抽屉里实际渲染什么:同一套本机页面(带远程目标)、+ * 旧版主机回退到通用表单页、对方离线时的状态、主机推送后的重读。+ * - Bug/规则依据:cindy-bots-runtime.md「远程设置」;AGENTS.md 协议兼容:新桌面控制旧主机不得破坏现有通用表单页。+ * - 现有覆盖缺口:botSettingsDrawer.test 只验证抽屉对该组件的挂载;remoteBotSettings.test 只测通用表单页。+ * - 最小失败输入:主机未声明 management:settings;caps 被旧主机拒绝;离线且从未探测;同一伙伴/其它伙伴的推送。+ * - tier:unit(jsdom + 假的主机客户端)。+ */+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { REMOTE_RESOURCE_CHANGED_CHANNEL } from '@cindy/device-link';+import { MemoryRouter } from 'react-router-dom';+import { createIpcError } from '../../../../shared/ipc-errors';++const h = vi.hoisted(() => ({+ declares: vi.fn(),+ caps: vi.fn(),+ call: vi.fn(),+ push: null as null | ((push: unknown, stamp: unknown) => void),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));+vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ isDeviceLinkRemotePushCurrent: () => true }));+vi.mock('../remoteBotSettingsClient', () => ({+ hostDeclaresBotSettings: h.declares,+ readBotSettingsCaps: h.caps,+ invokeBotSettings: h.call,+ splitProfilePatch: (patch: object) => [patch],+}));+vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => [] }));+vi.mock('@/hooks/useAvailableAgents', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/hooks/useAvailableAgents')>()), useAvailableAgents: () => ({ availableVendors: new Set(), loaded: false }) }));+vi.mock('../RemoteBotSettings', () => ({ RemoteBotSettings: ({ bot }: { bot: { deviceId: string } }) => <div data-testid="generic-form">{bot.deviceId}</div> }));+vi.mock('../BotsHomeView', async () => {+ const { useOptionalBotSettingsTarget } = await import('../botSettingsTarget');+ return {+ BotSettings: ({ bot, initialPage }: { bot: { name: string }; initialPage: string }) => {+ const target = useOptionalBotSettingsTarget();+ return <div data-testid="pages" data-page={initialPage} data-target={`${target?.kind}:${target?.deviceId}`}>{bot.name}</div>;+ },+ };+});++import { RemoteTeammateSettings } from '../RemoteTeammateSettings';++const bot = { id: 'bot-1', deviceId: 'mac', deviceName: 'Studio', name: 'Sora', avatar: '', avatarColor: '', description: '', preview: '', activityAt: 0, sessionId: 's', online: true };+const profile = (name: string) => ({ profile: { id: 'bot-1', name, description: '', avatar: '🙂', avatarColor: 'teal', status: 'active', skills: [], currentVersion: 1, createdAt: 1, sessions: [], capabilities: { harness: 'pi', model: 'm', modelChain: [], memory: true, permissions: 'ask' } } });+const renderSettings = (ui: React.ReactElement) => render(<MemoryRouter>{ui}</MemoryRouter>);+const props = { beforeCloseRef: { current: null }, onBack: vi.fn(), onDeleted: vi.fn() };++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ h.declares.mockReset().mockResolvedValue(true);+ h.caps.mockReset().mockResolvedValue({ version: 1, ops: ['caps', 'profile.get', 'profile.update', 'memory.list', 'memory.read', 'memory.update', 'memory.delete'] });+ h.call.mockReset().mockResolvedValue(profile('Sora'));+ h.push = null;+ vi.stubGlobal('window', Object.assign(window, { electronAPI: { deviceLink: { onRemotePush: (listener: (push: unknown, stamp: unknown) => void) => { h.push = listener; return () => { h.push = null; }; } } } }));+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++const pushFor = (id: string) => act(() => h.push?.({ deviceId: 'mac', channel: REMOTE_RESOURCE_CHANGED_CHANNEL,+ payload: { collectionId: 'teammates', resourceRefs: [{ collectionId: 'teammates', kind: 'bot', id }] } }, {}));++it('renders the local pages against the teammate computer, opening the requested page it can serve', async () => {+ renderSettings(<RemoteTeammateSettings bot={bot} initialPage="memory" {...props} />);+ const pages = await screen.findByTestId('pages');+ expect(pages.getAttribute('data-target')).toBe('remote:mac');+ expect(pages.getAttribute('data-page')).toBe('memory');+ expect(pages.textContent).toBe('Sora');+ expect(screen.queryByTestId('generic-form')).toBeNull();+});++it('falls back to the home page when the host cannot serve the requested page', async () => {+ renderSettings(<RemoteTeammateSettings bot={bot} initialPage="channels" {...props} />);+ expect((await screen.findByTestId('pages')).getAttribute('data-page')).toBe('home');+});++it('keeps the generic form page for a host that predates teammate settings', async () => {+ h.declares.mockResolvedValue(false);+ renderSettings(<RemoteTeammateSettings bot={bot} {...props} />);+ expect(await screen.findByTestId('generic-form')).toBeTruthy();+ h.declares.mockResolvedValue(true);+ cleanup();+ // An older host that lists the action but rejects the operation set is treated the same way.+ h.caps.mockRejectedValue(createIpcError('UNSUPPORTED_CAPABILITY', 'old'));+ renderSettings(<RemoteTeammateSettings bot={bot} {...props} />);+ expect(await screen.findByTestId('generic-form')).toBeTruthy();+ expect(screen.queryByTestId('pages')).toBeNull();+});++it('asks nothing of an unreachable computer and says so', () => {+ renderSettings(<RemoteTeammateSettings bot={{ ...bot, online: false }} {...props} />);+ expect(screen.getByRole('status').textContent).toBe('bots.remote.offlineDescription');+ expect(h.declares).not.toHaveBeenCalled();+});++it('re-reads the profile once after the host reports a change for this teammate, and ignores others', async () => {+ renderSettings(<RemoteTeammateSettings bot={bot} {...props} />);+ await screen.findByTestId('pages');+ const reads = () => h.call.mock.calls.filter((call) => call[1] === 'profile.get').length;+ expect(reads()).toBe(1);+ h.call.mockResolvedValue(profile('Renamed on the other computer'));+ pushFor('someone-else');+ await act(async () => { await vi.advanceTimersByTimeAsync(600); });+ expect(reads()).toBe(1);+ pushFor('bot-1');+ pushFor('bot-1');+ await act(async () => { await vi.advanceTimersByTimeAsync(600); });+ await waitFor(() => expect(screen.getByTestId('pages').textContent).toBe('Renamed on the other computer'));+ expect(reads()).toBe(2);+});diff --git a/apps/desktop/src/renderer/features/bots/botSettingsTarget.ts b/apps/desktop/src/renderer/features/bots/botSettingsTarget.tsnew file mode 100644index 0000000000..4c23133fe3--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/botSettingsTarget.ts@@ -0,0 +1,67 @@+import { createContext, useContext } from 'react';++import type { MakerVendor } from '@/lib/ccAgent.types';+import type { BotAutonomySettingsView } from '../../../shared/botAutonomy';+import type { BotLifecycleActionRequest, BotLifecycleActionResult } from '../../../shared/botLifecycle';+import type { BotModelRoute } from '../../../shared/botModelChain';+import type { ConversationSearchResponse } from '../../../shared/conversationSearch';+import type { BotSkillSummary } from '../../../shared/botSkill';+import type { BotProfile, BotProfileUpdatePatch } from './botStore';++export type BotCapabilityKind = 'skill' | 'mcp' | 'toolset';+export type BotCapabilityEntry = {+ id: string;+ name: string;+ description?: string;+ available: boolean;+ personal?: boolean;+};++type Bots = NonNullable<Window['electronAPI']['localDb']>['bots'];++/**+ * The computer a teammate's settings pages read from and write to. The pages are the same components for+ * every teammate; a target supplies the calls they make. The local target wraps this computer's IPC; the+ * remote one reaches the teammate's own computer through `management:settings`+ * (`shared/botRemoteSettings.ts`), where the same services run.+ */+export interface BotSettingsTarget {+ kind: 'local' | 'remote';+ /** Device-link id of the teammate's computer (remote only). */+ deviceId?: string;+ deviceName?: string;+ /** False while the computer cannot be reached: pages keep their content and writes are refused. */+ online: boolean;+ /** Pages whose host operations exist; the local target supports all of them. */+ pages: ReadonlySet<string>;+ profile: {+ update(botId: string, patch: BotProfileUpdatePatch): Promise<BotProfile>;+ /** Gallery / uploaded image bytes; omitted bytes open the native chooser (local only). */+ chooseAvatar(botId: string, avatarImageBase64?: string): Promise<BotProfile | null>;+ retryInvitation(botId: string): Promise<void>;+ };+ lifecycle: { run(request: BotLifecycleActionRequest): Promise<BotLifecycleActionResult> };+ /** Model defaults and engines are those of the teammate's computer. */+ useDefaultModelChain(): BotModelRoute[];+ useHiddenVendors(): MakerVendor[];+ /** Teammates on the same computer: name uniqueness and the follow-up holder's name. */+ useRoster(): ReadonlyArray<{ id: string; name: string; status?: string }>;+ memory: Bots['memory'];+ history: { search(body: { botId: string; query: string; limit: number }): Promise<ConversationSearchResponse> };+ capabilities: {+ load(bot: BotProfile, modelChain: BotModelRoute[]): Promise<Partial<Record<BotCapabilityKind, BotCapabilityEntry[]>>>;+ /** Calls `refresh` when the catalog may have changed (runtime, MCP or profile changes). */+ watch(bot: BotProfile, refresh: () => void): () => void;+ };+ autonomy: {+ useSettings(): BotAutonomySettingsView | null;+ setSchedulerBotId(botId: string | null): Promise<void>;+ reset(): Promise<void>;+ };+}++export const BotSettingsTargetContext = createContext<BotSettingsTarget | null>(null);+/** `null` = this computer; consumers fall back to `localBotSettingsTarget`. */+export const useOptionalBotSettingsTarget = () => useContext(BotSettingsTargetContext);++export type { BotSkillSummary };diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.tsindex 3ff09db6cd..503117d7a1 100644--- a/apps/desktop/src/renderer/features/bots/botStore.ts+++ b/apps/desktop/src/renderer/features/bots/botStore.ts@@ -559,7 +559,7 @@ function botsApi(): NonNullable<typeof window.electronAPI.localDb>['bots'] | nulreturn window.electronAPI?.localDb?.bots ?? null;}-function normalizeDbProfile(value: unknown): BotProfile | null {+export function normalizeDbProfile(value: unknown): BotProfile | null {if (!value || typeof value !== 'object') return null;const item = value as Partial<BotProfile>;if (typeof item.id !== 'string' || typeof item.name !== 'string') return null;diff --git a/apps/desktop/src/renderer/features/bots/localBotSettingsTarget.ts b/apps/desktop/src/renderer/features/bots/localBotSettingsTarget.tsnew file mode 100644index 0000000000..e6c4a55ce7--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/localBotSettingsTarget.ts@@ -0,0 +1,153 @@+import { useMemo, useSyncExternalStore } from 'react';++import type { ConversationSearchResponse } from '../../../shared/conversationSearch';++import { useAvailableAgents } from '@/hooks/useAvailableAgents';+import { useProviders } from '@/hooks/useProviders';+import type { MakerVendor } from '@/lib/ccAgent.types';+import type { Session } from '@/lib/ccAgent.types';+import * as sessionService from '@/lib/sessionService';+import { onPatch } from '@/lib/sessionsBus';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';+import {+ chooseBotAvatar,+ getEffectiveBotModelChain,+ retryBotInvitation,+ runBotLifecycleAction,+ setBotSchedulerBotId,+ resetBotAutonomySettings,+ subscribeBotGlobalModel,+ updateBotProfile,+ useBotAutonomySettings,+ useBotProfiles,+} from './botStore';+import type { BotCapabilityEntry, BotCapabilityKind, BotSettingsTarget } from './botSettingsTarget';++const api = () => window.electronAPI.localDb.bots;+const ALL_PAGES = ['profile', 'personality', 'memory', 'model', 'voice', 'capabilities', 'channels', 'routines', 'history', 'advanced'] as const;++/** Runtime / MCP facts that change which references a teammate can use. */+const CATALOG_PATCH_KEYS = [+ 'agentKind', 'model', 'providerId', 'effort', 'fastMode', 'runtimeGeneration',+ 'runtimeEffective', 'runtimePending', 'workingDir', 'remoteHostId',+];++/** The catalog the capability page lists, read from this computer's runtime. */+async function loadCatalog(+ bot: { id: string; canonicalSessionId?: string },+ modelChain: unknown,+): Promise<Partial<Record<BotCapabilityKind, BotCapabilityEntry[]>>> {+ if (!bot.canonicalSessionId) throw new Error('Missing canonical task');+ const session = await sessionService.get(bot.canonicalSessionId);+ const maker = window.electronAPI.maker;+ const mcpResult = await maker.listCustomMcpServers({+ agentKind:+ session.runtimePending?.profile.agentKind ??+ session.runtimeEffective?.agentKind ??+ (session.agentKind === 'codex' || session.agentKind === 'pi' ? session.agentKind : 'claude-code'),+ botSessionId: bot.canonicalSessionId,+ modelChain: modelChain as never,+ });+ const agentKind = mcpResult.agentKind;+ if (!agentKind) throw new Error('Missing next-turn route');+ const results = await Promise.allSettled([+ api().listSkills(bot.id),+ maker.listAgentSkills(agentKind, {+ forceReload: true,+ workingDir: session.workingDir ?? undefined,+ remoteHostId: session.remoteHostId ?? undefined,+ }),+ maker.plugins.list(session.workingDir ?? undefined, true, {+ botId: bot.id,+ agentKind,+ remoteHostId: session.remoteHostId,+ }),+ ]);+ const [personalResult, skillResult, toolsetResult] = results;+ const next: Partial<Record<BotCapabilityKind, BotCapabilityEntry[]>> = {};+ if (skillResult.status === 'fulfilled' && skillResult.value.success) {+ // Match resolveBotSkillReferences: the last entry for a name wins.+ // Map retains first-seen display order without changing discovery data.+ const skillsByName = new Map((skillResult.value.skills ?? []).map((item) => [item.name, item]));+ next.skill = [...skillsByName.values()].map((item) => ({+ id: item.name,+ name: item.name,+ description: item.description,+ available: item.enabled !== false && item.runtimeStatus !== 'failed',+ }));+ }+ if (personalResult.status === 'fulfilled')+ next.skill = [+ ...personalResult.value.map((item) => ({ id: `personal:${item.slug}`, name: item.name, available: item.enabled !== false, personal: true })),+ ...(next.skill ?? []),+ ];+ next.mcp = mcpResult.servers.map((item) => ({ id: item.id, name: item.name, available: item.available === true }));+ if (toolsetResult.status === 'fulfilled')+ next.toolset = toolsetResult.value+ .filter((item) => !['memory', 'xdt_helper', 'scheduler', 'lsp'].includes(item.id))+ .map((item) => ({ id: item.id, name: item.name, description: item.description, available: item.available === true }));+ return next;+}++function useDefaultModelChain() {+ // Followed defaults change with providers / available harnesses, not with the profile.+ useSyncExternalStore(subscribeBotGlobalModel, () => JSON.stringify(getEffectiveBotModelChain()));+ return getEffectiveBotModelChain();+}++function useHiddenVendors(): MakerVendor[] {+ // Live provider defaults are display state; load them so the chain editor reflects them.+ useProviders();+ const { availableVendors, loaded } = useAvailableAgents();+ return useMemo<MakerVendor[]>(() => {+ if (!loaded) return [];+ return (['cc', 'codex', 'pi'] as const).filter((item) => !availableVendors.has(item));+ }, [loaded, availableVendors]);+}++/** This computer: the settings pages as they always were, behind the target interface. */+export const localBotSettingsTarget: BotSettingsTarget = {+ kind: 'local',+ online: true,+ pages: new Set<string>(ALL_PAGES),+ // Store functions are read on use, so a module that never opens these pages never needs them.+ profile: {+ update: (...args) => updateBotProfile(...args),+ chooseAvatar: (...args) => chooseBotAvatar(...args),+ retryInvitation: (...args) => retryBotInvitation(...args),+ },+ lifecycle: { run: (request) => runBotLifecycleAction(request) },+ useDefaultModelChain,+ useHiddenVendors,+ useRoster: () => useBotProfiles(),+ memory: {+ list: (...args) => api().memory.list(...args),+ read: (...args) => api().memory.read(...args),+ update: (...args) => api().memory.update(...args),+ delete: (...args) => api().memory.delete(...args),+ },+ history: { search: (body) => api().searchHistory(body) as Promise<ConversationSearchResponse> },+ capabilities: {+ load: (bot, modelChain) => loadCatalog(bot, modelChain),+ watch(bot, refresh) {+ const changed = (sessionId: string, patch: Partial<Session>) => {+ if (sessionId === bot.canonicalSessionId && CATALOG_PATCH_KEYS.some((key) => key in patch)) refresh();+ };+ const offLocal = onPatch(changed);+ const offPush = window.electronAPI.localDb?.sessionsPush?.onPatched(({ sessionId, patch }, stamp) => {+ if (isDataOwnerPushCurrent(stamp)) changed(sessionId, patch);+ });+ const offMcp = window.electronAPI.maker.onMcpChanged(refresh);+ return () => {+ offLocal();+ offPush?.();+ offMcp();+ };+ },+ },+ autonomy: {+ useSettings: () => useBotAutonomySettings(),+ setSchedulerBotId: (botId) => setBotSchedulerBotId(botId),+ reset: () => resetBotAutonomySettings(),+ },+};diff --git a/apps/desktop/src/renderer/features/bots/remoteBotSettingsClient.ts b/apps/desktop/src/renderer/features/bots/remoteBotSettingsClient.tsnew file mode 100644index 0000000000..592101f670--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/remoteBotSettingsClient.ts@@ -0,0 +1,74 @@+import {+ REMOTE_RESOURCE_INVOKE_CHANNEL,+ REMOTE_RESOURCE_MANIFEST_CHANNEL,+ REMOTE_RESOURCE_PROTOCOL_VERSION,+} from '@cindy/device-link';++import { boundedPluginResponse } from '@/features/plugin/remotePluginManagementClient';+import {+ BOT_SETTINGS_ACTION_ID,+ BOT_SETTINGS_PROTOCOL_VERSION,+ type BotSettingsCaps,+ type BotSettingsOp,+ type BotSettingsResult,+} from '../../../shared/botRemoteSettings';+import { createIpcError, isIpcErrorCode } from '../../../shared/ipc-errors';++const client = { protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION, primitives: [] };+/** The invoke channel rejects inputs above 64 KiB; keep a margin for the envelope. */+const MAX_INPUT_BYTES = 56 * 1024;+const encoder = new TextEncoder();+const byteLength = (value: unknown) => encoder.encode(JSON.stringify(value)).length;++/** Does the host declare the teammate settings action? (Older hosts only have the generic form.) */+export async function hostDeclaresBotSettings(deviceId: string): Promise<boolean> {+ const manifest = await window.electronAPI.deviceLink.invoke(deviceId, REMOTE_RESOURCE_MANIFEST_CHANNEL, [{ client }]);+ if (!boundedPluginResponse(manifest)) return false;+ return !!(manifest as { collections?: Array<{ id: string; actions?: Array<{ id: string }> }> }).collections?.some(+ (collection) => collection.id === 'teammates' && collection.actions?.some((action) => action.id === BOT_SETTINGS_ACTION_ID),+ );+}++/** One operation on the teammate's computer. A refused operation rejects with the same IPC error shape the local call has. */+export async function invokeBotSettings<T = unknown>(+ deviceId: string,+ op: BotSettingsOp,+ botId: string | null,+ args?: Record<string, unknown>,+): Promise<T> {+ const input = { v: BOT_SETTINGS_PROTOCOL_VERSION, op, ...(args ? { args } : {}) };+ if (byteLength(input) > MAX_INPUT_BYTES) throw createIpcError('INVALID_PARAMS', 'Request is too large');+ const response = (await window.electronAPI.deviceLink.invoke(deviceId, REMOTE_RESOURCE_INVOKE_CHANNEL, [+ {+ client,+ collectionId: 'teammates',+ actionId: BOT_SETTINGS_ACTION_ID,+ ...(botId ? { resourceRef: { collectionId: 'teammates', kind: 'bot', id: botId } } : {}),+ input,+ },+ ])) as { result?: BotSettingsResult<T> } | null;+ const result = response?.result;+ if (!boundedPluginResponse(result) || !result || typeof result.ok !== 'boolean') throw createIpcError('INTERNAL', 'Invalid settings response');+ if (result.ok) return result.value;+ throw createIpcError(isIpcErrorCode(result.code) ? result.code : 'INTERNAL', String(result.message ?? ''));+}++export async function readBotSettingsCaps(deviceId: string): Promise<BotSettingsCaps> {+ const caps = await invokeBotSettings<BotSettingsCaps>(deviceId, 'caps', null);+ if (!caps || !Array.isArray(caps.ops) || typeof caps.version !== 'number') throw createIpcError('INTERNAL', 'Invalid settings capabilities');+ return caps;+}++const TEXT_FIELDS = ['name', 'description', 'identitySource', 'userContextSource'] as const;+/**+ * An autosave patch is a handful of fields. Long personality + user text can exceed the invoke input+ * limit together, so the free text goes in its own requests (each still has to fit by itself).+ */+export function splitProfilePatch(patch: Record<string, unknown>): Array<Record<string, unknown>> {+ if (byteLength({ patch }) <= MAX_INPUT_BYTES) return [patch];+ const rest = Object.fromEntries(Object.entries(patch).filter(([key]) => !(TEXT_FIELDS as readonly string[]).includes(key)));+ return [+ ...(Object.keys(rest).length ? [rest] : []),+ ...TEXT_FIELDS.filter((key) => key in patch).map((key) => ({ [key]: patch[key] })),+ ];+}diff --git a/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.ts b/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.tsnew file mode 100644index 0000000000..f07092503b--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.ts@@ -0,0 +1,285 @@+import { useEffect, useMemo, useSyncExternalStore } from 'react';++import { useAvailableAgents } from '@/hooks/useAvailableAgents';+import type { MakerVendor } from '@/lib/ccAgent.types';+import type { BotAutonomySettingsView } from '../../../shared/botAutonomy';+import type { BotMemoryDeleteInput, BotMemoryUpdateInput } from '../../../shared/botMemory';+import type { BotModelRoute } from '../../../shared/botModelChain';+import type { ConversationSearchResponse } from '../../../shared/conversationSearch';+import type { BotSkillSummary } from '../../../shared/botSkill';+import type { BotSettingsOp } from '../../../shared/botRemoteSettings';+import { createIpcError } from '../../../shared/ipc-errors';+import { normalizeDbProfile, type BotProfile, type BotProfileUpdatePatch } from './botStore';+import type { BotCapabilityEntry, BotCapabilityKind, BotSettingsTarget } from './botSettingsTarget';+import { invokeBotSettings, splitProfilePatch } from './remoteBotSettingsClient';+import { useRemoteBots } from './useRemoteBots';++export interface RemoteBotSettingsInput {+ deviceId: string;+ deviceName: string;+ botId: string;+ /** Operations the teammate's computer implements (`caps`). */+ ops: ReadonlySet<BotSettingsOp>;+ online(): boolean;+}++/** One teammate's profile as read from its computer; writes mirror the local store's optimistic rules. */+export function createRemoteProfileStore(deviceId: string, botId: string) {+ let profile: BotProfile | null = null;+ const listeners = new Set<() => void>();+ let writeGeneration = 0;+ let readGeneration = 0;+ let writing = 0;+ const emit = () => listeners.forEach((listener) => listener());+ const adopt = (raw: unknown): BotProfile => {+ const next = normalizeDbProfile((raw as { profile?: unknown } | null)?.profile);+ if (!next) throw createIpcError('INTERNAL', 'Invalid teammate profile');+ // Re-reads that change nothing keep the same object so the pages do not reconcile for nothing.+ if (profile && JSON.stringify(profile) === JSON.stringify(next)) return profile;+ profile = next;+ emit();+ return next;+ };+ return {+ get: () => profile,+ subscribe(listener: () => void) {+ listeners.add(listener);+ return () => void listeners.delete(listener);+ },+ async refresh() {+ const generation = ++readGeneration;+ const writes = writeGeneration;+ const raw = await invokeBotSettings(deviceId, 'profile.get', botId);+ // A write that started or finished meanwhile carries newer state than this read.+ if (generation !== readGeneration || writing > 0 || writes !== writeGeneration) return;+ adopt(raw);+ },+ async load() {+ const raw = await invokeBotSettings(deviceId, 'profile.get', botId);+ return adopt(raw);+ },+ async update(patch: BotProfileUpdatePatch): Promise<BotProfile> {+ const before = profile;+ if (!before) throw new Error('Bot not found');+ const { avatarUploadToken: _token, capabilityBaseline, ...profilePatch } = patch;+ const generation = ++writeGeneration;+ writing += 1;+ profile = { ...before, ...profilePatch, capabilities: { ...before.capabilities, ...profilePatch.capabilities } };+ emit();+ const body: Record<string, unknown> = {+ ...profilePatch,+ ...(capabilityBaseline ? { capabilityBaseline } : {}),+ ...(profilePatch.avatar !== undefined ? { expectedAvatar: before.avatar } : {}),+ };+ try {+ let raw: unknown;+ for (const part of splitProfilePatch(body)) raw = await invokeBotSettings(deviceId, 'profile.update', botId, { patch: part });+ const next = normalizeDbProfile((raw as { profile?: unknown } | null)?.profile);+ if (!next) throw createIpcError('INTERNAL', 'Invalid teammate profile');+ // A newer write on this profile is closer to what the person wants now.+ if (generation === writeGeneration) {+ profile = next;+ emit();+ }+ return next;+ } catch (error) {+ if (generation === writeGeneration) {+ profile = before;+ emit();+ }+ throw error;+ } finally {+ writing -= 1;+ }+ },+ /** Result of a host-side change (avatar, retry, lifecycle) that returns the new profile. */+ adopt,+ };+}+export type RemoteProfileStore = ReturnType<typeof createRemoteProfileStore>;++/** Gallery or uploaded art, normalised to a small JPEG so it fits the invoke input limit. */+async function toRemoteAvatar(base64: string): Promise<string> {+ const image = new Image();+ image.src = `data:image/png;base64,${base64}`;+ await image.decode();+ const canvas = document.createElement('canvas');+ canvas.width = canvas.height = 128;+ const context = canvas.getContext('2d');+ if (!context) throw new Error('Image unavailable');+ context.drawImage(image, 0, 0, 128, 128);+ return canvas.toDataURL('image/jpeg', 0.85).split(',')[1];+}++const BASELINE_TOOLSETS = ['memory', 'xdt_helper', 'scheduler', 'lsp'];++/** Pages the host can serve, from the operations it implements. */+export function remoteBotSettingsPages(ops: ReadonlySet<BotSettingsOp>): Set<string> {+ const has = (...needed: BotSettingsOp[]) => needed.every((op) => ops.has(op));+ const pages = new Set<string>();+ if (has('profile.get', 'profile.update')) {+ pages.add('profile');+ pages.add('personality');+ }+ if (has('memory.list', 'memory.read', 'memory.update', 'memory.delete')) pages.add('memory');+ if (has('models.default', 'profile.update')) pages.add('model');+ if (has('capabilities.catalog')) pages.add('capabilities');+ if (has('history.search')) pages.add('history');+ return pages;+}++/**+ * The settings pages for a teammate on another computer. Reads and writes go to that computer through+ * `management:settings`; the pages themselves are the local components.+ */+export function createRemoteBotSettingsTarget(input: RemoteBotSettingsInput) {+ const { deviceId, botId } = input;+ const profiles = createRemoteProfileStore(deviceId, botId);+ const call = <T>(op: BotSettingsOp, args?: Record<string, unknown>) => invokeBotSettings<T>(deviceId, op, botId, args);++ let defaultChain: BotModelRoute[] = [];+ const chainListeners = new Set<() => void>();+ let chainKey = '[]';+ const loadDefaultChain = async () => {+ if (!input.ops.has('models.default')) return;+ const { modelChain } = await invokeBotSettings<{ modelChain: BotModelRoute[] }>(deviceId, 'models.default', null);+ const key = JSON.stringify(modelChain);+ if (key === chainKey) return;+ chainKey = key;+ defaultChain = modelChain;+ chainListeners.forEach((listener) => listener());+ };++ let autonomy: BotAutonomySettingsView | null = null;+ const autonomyListeners = new Set<() => void>();+ const loadAutonomy = async () => {+ const view = await invokeBotSettings<BotAutonomySettingsView>(deviceId, 'autonomy.get', null);+ autonomy = view;+ autonomyListeners.forEach((listener) => listener());+ };+ const applyAutonomy = (view: BotAutonomySettingsView) => {+ autonomy = view;+ autonomyListeners.forEach((listener) => listener());+ };++ const catalogWatchers = new Set<() => void>();++ const target: BotSettingsTarget = {+ kind: 'remote',+ deviceId,+ deviceName: input.deviceName,+ get online() {+ return input.online();+ },+ pages: remoteBotSettingsPages(input.ops),+ profile: {+ update: (_id, patch) => profiles.update(patch),+ async chooseAvatar(_id, avatarImageBase64) {+ // The native chooser reads files of the computer it runs on; here the picker hands over bytes.+ if (avatarImageBase64 === undefined) return null;+ const raw = await call('profile.chooseAvatar', { avatarImageBase64: await toRemoteAvatar(avatarImageBase64) });+ return profiles.adopt(raw);+ },+ async retryInvitation() {+ profiles.adopt(await call('profile.retryInvitation'));+ },+ },+ lifecycle: {+ async run(request) {+ const result = await call<Awaited<ReturnType<BotSettingsTarget['lifecycle']['run']>>>('lifecycle.run', {+ action: request.action,+ confirmName: request.confirmName,+ worktreeDisposition: request.worktreeDisposition,+ keepTaskHistory: request.keepTaskHistory,+ });+ if (result.status !== 'deleted') await profiles.refresh();+ return result;+ },+ },+ useDefaultModelChain() {+ useEffect(() => {+ void loadDefaultChain().catch(() => undefined);+ }, []);+ return useSyncExternalStore(+ (listener) => (chainListeners.add(listener), () => void chainListeners.delete(listener)),+ () => defaultChain,+ );+ },+ useHiddenVendors() {+ const { availableVendors, loaded } = useAvailableAgents(deviceId);+ return useMemo<MakerVendor[]>(+ () => (loaded ? (['cc', 'codex', 'pi'] as const).filter((item) => !availableVendors.has(item)) : []),+ [loaded, availableVendors],+ );+ },+ useRoster() {+ const bots = useRemoteBots();+ return useMemo(() => bots.filter((bot) => bot.deviceId === deviceId).map((bot) => ({ id: bot.id, name: bot.name })), [bots]);+ },+ memory: {+ list: (id, query) => invokeBotSettings(deviceId, 'memory.list', id, { query }),+ read: (id, filename) => invokeBotSettings(deviceId, 'memory.read', id, { filename }),+ update: (body) => {+ const { botId: id, ...rest } = body as BotMemoryUpdateInput;+ return invokeBotSettings(deviceId, 'memory.update', id, rest);+ },+ async delete(body) {+ const { botId: id, ...rest } = body as BotMemoryDeleteInput;+ await invokeBotSettings(deviceId, 'memory.delete', id, rest);+ },+ },+ history: { search: ({ botId: id, query, limit }) => invokeBotSettings<ConversationSearchResponse>(deviceId, 'history.search', id, { query, limit }) },+ capabilities: {+ async load(bot) {+ const result = await invokeBotSettings<{+ personal: BotSkillSummary[];+ entries: Partial<Record<BotCapabilityKind, Array<{ id: string; name: string; description?: string; available: boolean }>>>;+ }>(deviceId, 'capabilities.catalog', bot.id);+ const entries = (kind: BotCapabilityKind): BotCapabilityEntry[] =>+ (result.entries[kind] ?? []).map(({ id, name, description, available }) => ({ id, name, description, available }));+ return {+ skill: [+ ...result.personal.map((item) => ({ id: `personal:${item.slug}`, name: item.name, available: item.enabled !== false, personal: true })),+ ...entries('skill'),+ ],+ mcp: entries('mcp'),+ toolset: entries('toolset').filter((item) => !BASELINE_TOOLSETS.includes(item.id)),+ };+ },+ watch(_bot, refresh) {+ catalogWatchers.add(refresh);+ return () => void catalogWatchers.delete(refresh);+ },+ },+ autonomy: {+ useSettings() {+ useEffect(() => {+ void loadAutonomy().catch(() => undefined);+ }, []);+ return useSyncExternalStore(+ (listener) => (autonomyListeners.add(listener), () => void autonomyListeners.delete(listener)),+ () => autonomy,+ );+ },+ async setSchedulerBotId(id) {+ applyAutonomy(await invokeBotSettings<BotAutonomySettingsView>(deviceId, 'autonomy.set', null, { schedulerBotId: id }));+ },+ async reset() {+ applyAutonomy(await invokeBotSettings<BotAutonomySettingsView>(deviceId, 'autonomy.reset', null));+ },+ },+ };++ return {+ target,+ profiles,+ /** The teammate's computer reported a change: re-read what the open pages show. */+ changed() {+ void profiles.refresh().catch(() => undefined);+ if (autonomyListeners.size) void loadAutonomy().catch(() => undefined);+ if (chainListeners.size) void loadDefaultChain().catch(() => undefined);+ catalogWatchers.forEach((refresh) => refresh());+ },+ };+}+export type RemoteBotSettingsHandle = ReturnType<typeof createRemoteBotSettingsTarget>;diff --git a/apps/desktop/src/renderer/features/bots/useBotSettingsTarget.ts b/apps/desktop/src/renderer/features/bots/useBotSettingsTarget.tsnew file mode 100644index 0000000000..79630d5630--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/useBotSettingsTarget.ts@@ -0,0 +1,7 @@+import { localBotSettingsTarget } from './localBotSettingsTarget';+import { useOptionalBotSettingsTarget, type BotSettingsTarget } from './botSettingsTarget';++/** The target of the surrounding settings page; this computer when there is none. */+export function useBotSettingsTarget(): BotSettingsTarget {+ return useOptionalBotSettingsTarget() ?? localBotSettingsTarget;+}diff --git a/apps/desktop/src/shared/botRemoteSettings.ts b/apps/desktop/src/shared/botRemoteSettings.tsnew file mode 100644index 0000000000..e8f41f8ba5--- /dev/null+++ b/apps/desktop/src/shared/botRemoteSettings.ts@@ -0,0 +1,135 @@+/**+ * Wire contract of the desktop teammate-settings target (`docs/product-rules/cindy-bots-runtime.md`+ * 「远程设置」).+ *+ * The controller renders the same settings pages as the local Desktop; every read and write is+ * executed by the teammate's computer. It rides the existing `maker:remote-resources:invoke`+ * channel on the `teammates` collection (no new device-link channel, no allowlist change): one+ * collection action, `management:settings`, whose `input.op` selects a fixed operation. The host+ * answers with `{ effects: [], result: BotSettingsResult }`.+ *+ * Hosts declare the action in the collection manifest; the `caps` operation then lists the+ * operations they implement so a controller can fall back (per page) when the host is older.+ * Credentials, filesystem paths and runtime objects never appear in a result.+ */++/** Collection action id declared by hosts that implement this contract. */+export const BOT_SETTINGS_ACTION_ID = 'management:settings';+export const BOT_SETTINGS_PROTOCOL_VERSION = 1;++export const BOT_SETTINGS_OPS = [+ 'caps',+ 'profile.get',+ 'profile.update',+ 'profile.chooseAvatar',+ 'profile.retryInvitation',+ 'lifecycle.run',+ 'models.default',+ 'memory.list',+ 'memory.read',+ 'memory.update',+ 'memory.delete',+ 'capabilities.catalog',+ 'autonomy.get',+ 'autonomy.set',+ 'autonomy.reset',+ 'history.search',+] as const;+export type BotSettingsOp = (typeof BOT_SETTINGS_OPS)[number];++/** Operations without a teammate (`resourceRef`) in the request. */+export const BOT_SETTINGS_HOST_OPS: readonly BotSettingsOp[] = [+ 'caps',+ 'models.default',+ 'autonomy.get',+ 'autonomy.set',+ 'autonomy.reset',+];++export interface BotSettingsCaps {+ version: number;+ ops: BotSettingsOp[];+}++/**+ * A failed operation is returned as data rather than thrown: the registry adapter collapses every+ * non-registry error into a generic INTERNAL, which would hide revision conflicts (`PRECONDITION_FAILED`)+ * from the page that has to react to them.+ */+export type BotSettingsResult<T = unknown> =+ | { ok: true; value: T }+ | { ok: false; code: string; message: string };++const OP_SET: ReadonlySet<string> = new Set(BOT_SETTINGS_OPS);+export const isBotSettingsOp = (value: unknown): value is BotSettingsOp =>+ typeof value === 'string' && OP_SET.has(value);++/** Pages of the settings home, in display order. A page is shown for a host only if its ops exist. */+export type BotSettingsPageId =+ | 'profile'+ | 'personality'+ | 'memory'+ | 'model'+ | 'voice'+ | 'capabilities'+ | 'channels'+ | 'routines'+ | 'history'+ | 'advanced';++/** Operations a host must implement for the full page set rendered by the local components. */+export const BOT_SETTINGS_CORE_OPS: readonly BotSettingsOp[] = [+ 'profile.get',+ 'profile.update',+ 'profile.chooseAvatar',+ 'profile.retryInvitation',+ 'lifecycle.run',+ 'models.default',+ 'memory.list',+ 'memory.read',+ 'memory.update',+ 'memory.delete',+ 'capabilities.catalog',+ 'autonomy.get',+ 'autonomy.set',+ 'autonomy.reset',+ 'history.search',+];++/** Profile fields a remote autosave may write; anything else is rejected by the host. */+export const BOT_SETTINGS_PATCH_FIELDS = [+ 'name',+ 'description',+ 'identitySource',+ 'userContextSource',+ 'avatar',+ 'avatarColor',+ 'expectedAvatar',+ 'skills',+ 'capabilityBaseline',+ 'capabilities',+] as const;++/**+ * Capability keys writable through the settings pages. `permissions` is deliberately absent:+ * raising the permission level keeps its confirmation in the generic remote form.+ */+export const BOT_SETTINGS_CAPABILITY_FIELDS = [+ 'model',+ 'modelOverride',+ 'providerId',+ 'effort',+ 'fastMode',+ 'harness',+ 'modelChain',+ 'modelChainOverride',+ 'taskModelOverride',+ 'skillMode',+ 'toolsetMode',+ 'toolsets',+ 'mcpMode',+ 'mcpServers',+ 'memory',+ 'inputHandoff',+ 'allowSchedulerFollow',+] as const;