Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(bots): routines, voice and messaging platforms for a teammate on another computer
nana2ba4de15521e
diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.tsindex bf7b5bfe54..e3434cf888 100644--- a/apps/desktop/src/main/hook-control/ipc.ts+++ b/apps/desktop/src/main/hook-control/ipc.ts@@ -773,6 +773,34 @@ function registerTrustedHookControlHandler(channel: string, handler: HookControl});}+/** Compare-and-set of the official X account's teammate (IPC and the teammate settings host share it). */+export async function changeXCompanionBinding(botId: string | null, expectedBotId: string | null) {+ requireHookControl();+ const assertAccount = captureChannelAccount();+ const { store: s, manager: m } = ensureInstances();+ if (botId !== null) await requireXCompanion(botId);+ assertAccount();+ if ((s.get().xCompanionBotId ?? null) !== expectedBotId) {+ throwIpcError('PRECONDITION_FAILED', 'X companion assignment changed');+ }+ translateValidation(() => s.setXCompanionBotId(botId));+ const hook = m.snapshot();+ broadcastStatus(hook);+ return hook;+}++/** What a teammate's settings page may show of the official X account: no URLs, accounts or tokens. */+export function readXCompanionSummary(): { available: boolean; enabled: boolean; connected: boolean; companionBotId: string | null } {+ if (!hookControlAvailable()) return { available: false, enabled: false, connected: false, companionBotId: null };+ const x = ensureInstances().manager.snapshot().x;+ return {+ available: x.available,+ enabled: x.enabled,+ connected: x.binding?.state === 'confirmed',+ companionBotId: x.companionBotId ?? null,+ };+}+/** 注册 IPC 并按配置 + 登录态拉起连接。bootstrap 里调用一次。 */export function registerHookControlIpc(): void {registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.GET, () => ({@@ -935,21 +963,13 @@ export function registerHookControlIpc(): void {);registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.SET_X_COMPANION, async (_e, payload) => {- requireHookControl();- const assertAccount = captureChannelAccount();- const { store: s, manager: m } = ensureInstances();const p = requireObject(payload);- const botId = requireNullableString(p.botId, 'botId');- const expectedBotId = requireNullableString(p.expectedBotId, 'expectedBotId');- if (botId !== null) await requireXCompanion(botId);- assertAccount();- if ((s.get().xCompanionBotId ?? null) !== expectedBotId) {- throwIpcError('PRECONDITION_FAILED', 'X companion assignment changed');- }- translateValidation(() => s.setXCompanionBotId(botId));- const hook = m.snapshot();- broadcastStatus(hook);- return { hook };+ return {+ hook: await changeXCompanionBinding(+ requireNullableString(p.botId, 'botId'),+ requireNullableString(p.expectedBotId, 'expectedBotId'),+ ),+ };});// 发起 Slack 账号绑定(SIWS OIDC): 经已连接的 WS 发 bind.start(无参); serverdiff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.tsindex c07f8cd5d9..d202e6217f 100644--- a/apps/desktop/src/main/im/index.ts+++ b/apps/desktop/src/main/im/index.ts@@ -150,6 +150,19 @@ const log = createLogger('main:im');let wired = false;+/** Personal WeChat operations a remote Desktop's teammate settings may drive (set once the IM stack is wired). */+export interface WechatSettingsApi {+ getState(): unknown;+ getChannelSettings(): unknown;+ setCompanion(botId: string | null): Promise<unknown>;+ unbind(): Promise<unknown>;+ cancelAuthorization(): void;+}+let wechatSettingsApi: WechatSettingsApi | null = null;+export function getWechatSettingsApi(): WechatSettingsApi | null {+ return wechatSettingsApi;+}+export interface DesktopCcPrefs {model: string;providerId?: string | null;@@ -389,6 +402,41 @@ export function startImOrchestrators(): void {},});+ const setWechatCompanion = (botId: string | null) =>+ connectionLifecycle.runWhileStarted(async () => {+ const generation = captureImAccountGeneration();+ if (generation === null) throwIpcError('PRECONDITION_FAILED', 'Account unavailable');+ try {+ await setWechatCompanionBinding(botId, (commit) => wechatIm.updateCompanionBinding(() => {+ if (!isImAccountGenerationCurrent(generation)) throw new Error('ACCOUNT_CHANGED');+ commit();+ }));+ } catch (error) {+ const code = error instanceof Error ? error.message : '';+ throwIpcError('PRECONDITION_FAILED',+ ['WECHAT_CONNECTION_BUSY', 'BOT_INACTIVE', 'WECHAT_COMPANION_IN_USE'].includes(code)+ ? code : 'WECHAT_COMPANION_UPDATE_FAILED');+ }+ BrowserWindow.getAllWindows().forEach((window) => {+ if (!window.isDestroyed()) window.webContents.send('wechatBot:channel-settings-changed', readWechatChannelSettings());+ });+ return readWechatChannelSettings();+ });+ const unbindWechat = () =>+ connectionLifecycle.runWhileStarted(async () => {+ await wechatIm.unbind();+ return { ok: true };+ });+ // The teammate settings host (a remote Desktop's pages) uses the same operations; browser+ // authorization and the native directory chooser stay on this window's IPC.+ wechatSettingsApi = {+ getState: () => wechatIm.getState(),+ getChannelSettings: () => readWechatChannelSettings(),+ setCompanion: setWechatCompanion,+ unbind: unbindWechat,+ cancelAuthorization: () => { wechatIm.cancelAuthorization(); },+ };+ipcMain.handle('wechatBot:get-state', (event) => {assertTrustedAppRendererEvent(event);return wechatIm.getState();@@ -404,10 +452,7 @@ export function startImOrchestrators(): void {});ipcMain.handle('wechatBot:unbind', (event) => {assertTrustedAppRendererEvent(event);- return connectionLifecycle.runWhileStarted(async () => {- await wechatIm.unbind();- return { ok: true };- });+ return unbindWechat();});ipcMain.handle('wechatBot:get-channel-settings', (event) => {assertTrustedAppRendererEvent(event);@@ -418,25 +463,7 @@ export function startImOrchestrators(): void {if (botId !== null && (typeof botId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(botId))) {throwIpcError('INVALID_ARGUMENT', 'Invalid teammate');}- return connectionLifecycle.runWhileStarted(async () => {- const generation = captureImAccountGeneration();- if (generation === null) throwIpcError('PRECONDITION_FAILED', 'Account unavailable');- try {- await setWechatCompanionBinding(botId as string | null, (commit) => wechatIm.updateCompanionBinding(() => {- if (!isImAccountGenerationCurrent(generation)) throw new Error('ACCOUNT_CHANGED');- commit();- }));- } catch (error) {- const code = error instanceof Error ? error.message : '';- throwIpcError('PRECONDITION_FAILED',- ['WECHAT_CONNECTION_BUSY', 'BOT_INACTIVE', 'WECHAT_COMPANION_IN_USE'].includes(code)- ? code : 'WECHAT_COMPANION_UPDATE_FAILED');- }- BrowserWindow.getAllWindows().forEach((window) => {- if (!window.isDestroyed()) window.webContents.send('wechatBot:channel-settings-changed', readWechatChannelSettings());- });- return readWechatChannelSettings();- });+ return setWechatCompanion(botId as string | null);});ipcMain.handle('wechatBot:choose-working-directory', async (event) => {assertTrustedAppRendererEvent(event);diff --git a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts b/apps/desktop/src/main/im/shared/botImConnectionRuntime.tsindex fe9c5b19e9..3b780e3fae 100644--- a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts+++ b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts@@ -734,6 +734,12 @@ export function parseBotImConnectionAddInput(payload: unknown): BotImConnectionAreturn { botId, channel: 'discord', token, ownerUserId };}+/** 隐藏任务小节(本机设置页与远程桌面的设置页共用): 群名沿用「群聊」小节同一份已知群。 */+const laneOptions = () => ({ knownGroups: (record: BotImConnectionRecord) => requireDeps().listKnownGroups(record) });+export const listBotImConnectionLanesForSettings = (id: string) => listBotImConnectionLanes(id, laneOptions());+export const resetBotImConnectionLaneForSettings = (id: string, sessionId: string) =>+ resetBotImConnectionLane(id, sessionId, laneOptions());+export function registerBotImConnectionIpc(): void {if (ipcRegistered) return;ipcRegistered = true;@@ -768,12 +774,11 @@ export function registerBotImConnectionIpc(): void {return setBotImConnectionGroupMode(p.id, p.chatId, mode);});// 隐藏任务小节: 群名沿用「群聊」小节同一份已知群(deps.listKnownGroups)。- const laneOptions = { knownGroups: (record: BotImConnectionRecord) => requireDeps().listKnownGroups(record) };ipcMain.handle('botImConnection:list-lanes', (e, payload) => {assertTrustedAppRendererEvent(e);const id = (payload as { id?: unknown } | null)?.id;if (!isBotImConnectionId(id)) throwIpcError('INVALID_PARAMS', 'id is invalid');- return listBotImConnectionLanes(id, laneOptions);+ return listBotImConnectionLanesForSettings(id);});ipcMain.handle('botImConnection:reset-lane', (e, payload) => {assertTrustedAppRendererEvent(e);@@ -782,7 +787,7 @@ export function registerBotImConnectionIpc(): void {if (typeof p.sessionId !== 'string' || !/^[A-Za-z0-9_.:-]{1,200}$/.test(p.sessionId)) {throwIpcError('INVALID_PARAMS', 'sessionId is invalid');}- return resetBotImConnectionLane(p.id, p.sessionId, laneOptions);+ return resetBotImConnectionLaneForSettings(p.id, p.sessionId);});}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSettingsHost.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSettingsHost.test.tsindex 0ce34df048..57375656a9 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSettingsHost.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSettingsHost.test.ts@@ -48,8 +48,25 @@ function setup(overrides: { allowed?: boolean; visible?: boolean; ownerCurrent?:personalSkills: vi.fn(async () => []),autonomy: { get: vi.fn(), set: vi.fn(), reset: vi.fn() },searchHistory: vi.fn(async () => ({ results: [] })),+ channels: {+ im: {+ list: vi.fn(async () => ({ connections: [{ id: 'mine', botId: 'bot-1' }, { id: 'theirs', botId: 'bot-2' }] })),+ remove: vi.fn(async () => ({ connections: [{ id: 'theirs', botId: 'bot-2' }], archivedSessionIds: [] })),+ listGroups: vi.fn(async () => ({ groups: [] })), setGroupActivation: vi.fn(), listLanes: vi.fn(async () => ({ lanes: [] })),+ resetLane: vi.fn(), listAdoptable: vi.fn(async () => ({ bots: [] })), adopt: vi.fn(),+ },+ wechat: vi.fn(async () => ({+ getState: () => ({ phase: 'connected', bound: true }),+ getChannelSettings: vi.fn(() => ({ version: 1, workingDir: '/Users/owner/wechat', workingDirAvailable: true, companionBotId: 'bot-2' })),+ setCompanion: vi.fn(async () => ({ version: 1, workingDir: '/Users/owner/wechat', workingDirAvailable: true, companionBotId: 'bot-1' })),+ unbind: vi.fn(), cancelAuthorization: vi.fn(),+ })),+ x: { summary: vi.fn(() => ({ available: true, enabled: true, connected: true, companionBotId: 'bot-2' })), setCompanion: vi.fn() },+ },+ voice: { models: vi.fn(() => []), voices: vi.fn(async () => ({ voices: [] })), preference: vi.fn(async () => ({ selection: null, customized: false })), setPreference: vi.fn(async () => ({ selection: null, customized: false })) },+ routines: { list: vi.fn(async () => []), sources: vi.fn(async () => []), history: vi.fn(async () => []), save: vi.fn(async () => ({ id: 'r1' })), runNow: vi.fn(), remove: vi.fn() },...overrides.deps,- } as unknown as BotSettingsOpsDeps & { updateProfile: ReturnType<typeof vi.fn>; lifecycle: ReturnType<typeof vi.fn>; memory: Record<string, ReturnType<typeof vi.fn>> };+ } as unknown as BotSettingsOpsDeps & { updateProfile: ReturnType<typeof vi.fn>; lifecycle: ReturnType<typeof vi.fn>; memory: Record<string, ReturnType<typeof vi.fn>>; routines: Record<string, ReturnType<typeof vi.fn>>; voice: Record<string, ReturnType<typeof vi.fn>>; channels: any };const host = createBotRemoteSettingsHost({owner: () => 'owner-1',isOwnerCurrent: overrides.ownerCurrent ? overrides.ownerCurrent : () => true,@@ -134,3 +151,47 @@ it('restricts lifecycle operations to the ones the settings page offers', asyncexpect.any(Function),);});++it('validates a routine before it reaches the shared routine service and reports one generic failure', async () => {+ const { deps, call } = setup();+ const invalid = await call('routines.save', { input: { name: '', prompt: '' } });+ expect(invalid).toMatchObject({ ok: false, code: 'INVALID_PARAMS' });+ expect(deps.routines.save).not.toHaveBeenCalled();+ const saved = await call('routines.save', { id: 'r1', input: { name: 'Digest', prompt: 'Summarise', enabled: true, triggers: [{ id: 't1', kind: 'interval', intervalMs: 3_600_000 }] } });+ expect(saved).toMatchObject({ ok: true, value: { id: 'r1' } });+ expect(deps.routines.save).toHaveBeenCalledWith('bot-1', expect.objectContaining({ name: 'Digest' }), 'r1');+ // Event sources are host-wide: no teammate is required.+ expect(await call('routines.sources', undefined, null)).toMatchObject({ ok: true });+});++it('keeps "not provided" and "reset to default" apart when a voice preference is written', async () => {+ const { deps, call } = setup();+ await call('voice.setPreference', { sentencePlayback: false });+ expect(deps.voice.setPreference).toHaveBeenLastCalledWith('bot-1', undefined, false);+ await call('voice.setPreference', { selection: null, sentencePlayback: null });+ expect(deps.voice.setPreference).toHaveBeenLastCalledWith('bot-1', null, null);+ // The catalog is host-wide; a failing voice service never leaks its message.+ (deps.voice.models as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => { throw new Error('key sk-secret rejected'); });+ expect(await call('voice.models', undefined, null)).toEqual({ ok: false, code: 'PRECONDITION_FAILED', message: 'Voice conversation is unavailable.' });+});++it('limits messaging-platform operations to this teammate and keeps the WeChat folder path home', async () => {+ const { deps, call } = setup();+ // Another teammate's connection can be neither removed nor inspected from this teammate's page.+ expect(await call('channels.im.remove', { id: 'theirs' })).toMatchObject({ ok: false, code: 'NOT_FOUND' });+ expect(await call('channels.im.listGroups', { id: 'theirs' })).toMatchObject({ ok: false, code: 'NOT_FOUND' });+ expect(deps.channels.im.remove).not.toHaveBeenCalled();+ // Results list only this teammate's connections.+ expect(await call('channels.im.remove', { id: 'mine' })).toMatchObject({ ok: true, value: { connections: [] } });+ expect(await call('channels.im.list')).toMatchObject({ ok: true, value: { connections: [{ id: 'mine' }] } });+ // WeChat is assigned to someone else: this page can neither release nor unbind it, and never sees the folder path.+ expect(await call('channels.wechat.setCompanion', { assign: false })).toMatchObject({ ok: false, code: 'PRECONDITION_FAILED' });+ expect(await call('channels.wechat.unbind')).toMatchObject({ ok: false, code: 'PRECONDITION_FAILED' });+ const wechat = await call('channels.wechat.get');+ expect(wechat).toMatchObject({ ok: true, value: { channelSettings: { companionBotId: 'bot-2', workingDir: null } } });+ // The official X account behaves the same way.+ expect(await call('channels.x.setCompanion', { assign: false, expectedBotId: 'bot-2' })).toMatchObject({ ok: false, code: 'PRECONDITION_FAILED' });+ expect(deps.channels.x.setCompanion).not.toHaveBeenCalled();+ // There is no operation that takes credentials.+ expect(await call('channels.im.add', { token: 'x' })).toMatchObject({ ok: false, code: 'INVALID_PARAMS' });+});diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteManagement.ts b/apps/desktop/src/main/localDb/ipc/botRemoteManagement.tsindex f739353dfa..03e372a71b 100644--- a/apps/desktop/src/main/localDb/ipc/botRemoteManagement.ts+++ b/apps/desktop/src/main/localDb/ipc/botRemoteManagement.ts@@ -136,6 +136,19 @@ async function getInvitation(context: RemoteResourceHostContext, botId: string)return { effects: [{ kind: 'refresh-collection', collectionId: 'teammates' }] };});}+/** The routine service is shared with the local routines IPC; load it when a routines page asks. */+const routineTools = async () => (await import('../../routines/service.js')).routineTools;++/** The messaging stack is only needed by a remote Desktop's channels page. */+const imRuntime = () => import('../../im/shared/botImConnectionRuntime.js');++/** Loaded on use: the voice stack is large and only a voice page of a remote Desktop needs it. */+async function settingsVoice() {+ const api = (await import('../../voice-conversation/index.js')).getVoiceSettingsHostApi();+ if (!api) throwIpcError('PRECONDITION_FAILED', 'Voice conversation is unavailable.');+ return api!;+}+/*** 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.@@ -171,6 +184,37 @@ const settingsHost = createBotRemoteSettingsHost({personalSkills: listBotSkillsForBot,autonomy: { get: getBotAutonomySettingsView, set: setBotAutonomySchedulerBotId, reset: resetBotAutonomySchedulerSettings },searchHistory: searchBotHistory,+ routines: {+ list: async (botId) => (await routineTools()).list(botId),+ sources: async () => (await routineTools()).sources(),+ history: async (botId, id) => (await routineTools()).history(botId, id),+ save: async (botId, input, id) => (await routineTools()).save(botId, input, id),+ runNow: async (botId, id) => (await routineTools()).runNow(botId, id),+ remove: async (botId, id) => (await routineTools()).remove(botId, id),+ },+ channels: {+ im: {+ list: async () => (await imRuntime()).buildBotImConnectionListPayload(),+ remove: async (id) => (await imRuntime()).removeBotImConnection(id),+ listGroups: async (id) => (await imRuntime()).listBotImConnectionGroups(id),+ setGroupActivation: async (id, chatId, mode) => (await imRuntime()).setBotImConnectionGroupMode(id, chatId, mode),+ listLanes: async (id) => (await imRuntime()).listBotImConnectionLanesForSettings(id),+ resetLane: async (id, sessionId) => (await imRuntime()).resetBotImConnectionLaneForSettings(id, sessionId),+ listAdoptable: async () => (await import('../../im/shared/botImPersonalAdoption.js')).listAdoptablePersonalBots(),+ adopt: async (input) => (await import('../../im/shared/botImPersonalAdoption.js')).adoptPersonalBot(input),+ },+ wechat: async () => (await import('../../im/index.js')).getWechatSettingsApi(),+ x: {+ summary: async () => (await import('../../hook-control/ipc.js')).readXCompanionSummary(),+ setCompanion: async (botId, expected) => (await import('../../hook-control/ipc.js')).changeXCompanionBinding(botId, expected),+ },+ },+ voice: {+ models: async () => (await settingsVoice()).models(),+ voices: async selection => (await settingsVoice()).voices(selection),+ preference: async botId => (await settingsVoice()).preference(botId),+ setPreference: async (botId, selection, playback) => (await settingsVoice()).setPreference(botId, selection, playback),+ },}),});export const botRemoteManagement = { ...settings, getEditor, getInvitation, settingsHost };diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.ts b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.tsindex 41d88014b7..0d139ab826 100644--- a/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.ts+++ b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.ts@@ -4,10 +4,20 @@ import {type BotSettingsOp,} from '../../../shared/botRemoteSettings.js';import type { BotAutonomySettingsView } from '../../../shared/botAutonomy.js';+import {+ BOT_IM_CHANNELS,+ type BotImAdoptablePersonalBotsPayload,+ type BotImChannel,+ type BotImConnectionAddResult,+ type BotImConnectionGroupsPayload,+ type BotImConnectionLanesPayload,+ type BotImConnectionListPayload,+} from '../../../shared/botImConnection.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 { parseRoutineInput, type Routine, type RoutineRun, type RoutineSource } from '@cindy/maker-scheduler';import { throwIpcError } from '../../utils/ipcValidate.js';import type { BotSettingsCall, BotSettingsOpHandler } from './botRemoteSettingsHost.js';@@ -44,6 +54,49 @@ export interface BotSettingsOpsDeps {reset(): Promise<BotAutonomySettingsView>;};searchHistory(botId: string, query: string, limit: number): Promise<unknown>;+ /**+ * Messaging platforms. Credentials are entered and stored on this computer only: there is no+ * operation that adds a connection from credentials, and no result carries one.+ */+ channels: {+ im: {+ list(): Promise<BotImConnectionListPayload>;+ remove(id: string): Promise<BotImConnectionListPayload>;+ listGroups(id: string): Promise<BotImConnectionGroupsPayload>;+ setGroupActivation(id: string, chatId: string, mode: 'mention' | 'always'): Promise<BotImConnectionGroupsPayload>;+ listLanes(id: string): Promise<BotImConnectionLanesPayload>;+ resetLane(id: string, sessionId: string): Promise<BotImConnectionLanesPayload>;+ listAdoptable(): Promise<BotImAdoptablePersonalBotsPayload>;+ adopt(input: { botId: string; channel: BotImChannel }): Promise<BotImConnectionAddResult>;+ };+ wechat(): Promise<{+ getState(): unknown;+ getChannelSettings(): unknown;+ setCompanion(botId: string | null): Promise<unknown>;+ unbind(): Promise<unknown>;+ cancelAuthorization(): void;+ } | null>;+ x: {+ summary(): Promise<{ available: boolean; enabled: boolean; connected: boolean; companionBotId: string | null }>;+ setCompanion(botId: string | null, expectedBotId: string | null): Promise<unknown>;+ };+ };+ /** Speech catalog and the per-teammate preference (the voice IPC's own services). */+ voice: {+ models(): unknown;+ voices(selection: unknown): Promise<unknown>;+ preference(botId: string): Promise<unknown>;+ setPreference(botId: string, selection: unknown, sentencePlayback: unknown): Promise<unknown>;+ };+ /** The routine service every surface shares (`routineTools`). */+ routines: {+ list(botId: string): Promise<Routine[]>;+ sources(): Promise<RoutineSource[]>;+ history(botId: string, id: string): Promise<RoutineRun[]>;+ save(botId: string, input: ReturnType<typeof parseRoutineInput>, id?: string): Promise<Routine>;+ runNow(botId: string, id: string): Promise<unknown>;+ remove(botId: string, id: string): Promise<void>;+ };}const fail = (message = 'Invalid settings arguments'): never => throwIpcError('INVALID_PARAMS', message);@@ -83,6 +136,41 @@ export function readBotSettingsPatch(value: unknown): Record<string, unknown> {}const ACTIONS = new Set(['resume', 'restart', 'delete']);+const GROUP_CHAT_ID = /^-?\d{1,32}$/;+const LANE_SESSION_ID = /^[A-Za-z0-9_.:-]{1,200}$/;++/** A connection page operation may touch only this teammate's own connections. */+async function ownConnection(deps: BotSettingsOpsDeps, call: BotSettingsCall): Promise<string> {+ const id = text(call.args.id, 'id', 200);+ const own = (await deps.channels.im.list()).connections.some((connection) => connection.id === id && connection.botId === botOf(call));+ return own ? id : throwIpcError('NOT_FOUND', 'Connection unavailable');+}+const onlyThisTeammate = (deps: BotSettingsOpsDeps, payload: BotImConnectionListPayload, call: BotSettingsCall): BotImConnectionListPayload =>+ ({ connections: payload.connections.filter((connection) => connection.botId === botOf(call)) });++/** The path of the WeChat working folder belongs to the teammate's computer. */+const wechatSettings = (settings: unknown) => ({ ...record(settings, 'settings'), workingDir: null });+async function wechatOf(deps: BotSettingsOpsDeps) {+ return (await deps.channels.wechat()) ?? throwIpcError('PRECONDITION_FAILED', 'WeChat is unavailable');+}++/** The local voice IPC answers every failure with one message and logs no arguments; so does the remote page. */+const voiceCall = async <T>(run: () => T | Promise<T>): Promise<T> => {+ try {+ return await run();+ } catch {+ return throwIpcError('PRECONDITION_FAILED', 'Voice conversation is unavailable.');+ }+};++/** The local routine IPC reports every failure with this one message; so does the remote page. */+const routineCall = async <T>(run: () => Promise<T>): Promise<T> => {+ try {+ return await run();+ } catch {+ return throwIpcError('INVALID_PARAMS', 'Routine operation failed; check the teammate and trigger settings');+ }+};const KINDS: readonly Kind[] = ['skill', 'mcp', 'toolset'];export function createBotRemoteSettingsOps(deps: BotSettingsOpsDeps): Partial<Record<BotSettingsOp, BotSettingsOpHandler>> {@@ -139,6 +227,83 @@ export function createBotRemoteSettingsOps(deps: BotSettingsOpsDeps): Partial<Rereturn deps.autonomy.set(value as string | null);},'autonomy.reset': async () => deps.autonomy.reset(),+ 'routines.list': call => routineCall(() => deps.routines.list(botOf(call))),+ 'routines.sources': () => routineCall(() => deps.routines.sources()),+ 'routines.history': call => routineCall(() => deps.routines.history(botOf(call), text(call.args.id, 'id', 128))),+ 'routines.save': call => routineCall(() => {+ const id = call.args.id === undefined ? undefined : text(call.args.id, 'id', 128);+ return deps.routines.save(botOf(call), parseRoutineInput(call.args.input), id);+ }),+ 'routines.runNow': call => routineCall(() => deps.routines.runNow(botOf(call), text(call.args.id, 'id', 128))),+ 'routines.remove': call => routineCall(async () => {+ await deps.routines.remove(botOf(call), text(call.args.id, 'id', 128));+ return null;+ }),+ 'voice.models': () => voiceCall(() => deps.voice.models()),+ 'voice.voices': call => voiceCall(() => deps.voice.voices(call.args.selection)),+ 'voice.preference': call => voiceCall(() => deps.voice.preference(botOf(call))),+ 'voice.setPreference': call => voiceCall(() => deps.voice.setPreference(+ botOf(call),+ 'selection' in call.args ? call.args.selection : undefined,+ 'sentencePlayback' in call.args ? call.args.sentencePlayback : undefined,+ )),+ 'channels.im.list': async call => onlyThisTeammate(deps, await deps.channels.im.list(), call),+ 'channels.im.remove': async call => onlyThisTeammate(deps, await deps.channels.im.remove(await ownConnection(deps, call)), call),+ 'channels.im.listGroups': async call => deps.channels.im.listGroups(await ownConnection(deps, call)),+ 'channels.im.setGroupActivation': async call => {+ const id = await ownConnection(deps, call);+ if (typeof call.args.chatId !== 'string' || !GROUP_CHAT_ID.test(call.args.chatId)) fail('chatId is invalid');+ return deps.channels.im.setGroupActivation(id, call.args.chatId as string, call.args.mode === 'always' ? 'always' : 'mention');+ },+ 'channels.im.listLanes': async call => deps.channels.im.listLanes(await ownConnection(deps, call)),+ 'channels.im.resetLane': async call => {+ const id = await ownConnection(deps, call);+ if (typeof call.args.sessionId !== 'string' || !LANE_SESSION_ID.test(call.args.sessionId)) fail('sessionId is invalid');+ return deps.channels.im.resetLane(id, call.args.sessionId as string);+ },+ 'channels.im.listAdoptable': async () => deps.channels.im.listAdoptable(),+ 'channels.im.adopt': async call => {+ const channel = BOT_IM_CHANNELS.find((item) => item === call.args.channel) ?? fail('channel is invalid');+ const result = await deps.channels.im.adopt({ botId: botOf(call), channel });+ return { ...onlyThisTeammate(deps, result, call), connection: result.connection };+ },+ 'channels.wechat.get': async call => {+ botOf(call);+ const wechat = await wechatOf(deps);+ return { state: wechat.getState(), channelSettings: wechatSettings(wechat.getChannelSettings()) };+ },+ 'channels.wechat.setCompanion': async call => {+ const botId = botOf(call);+ const wechat = await wechatOf(deps);+ // A teammate's page may assign WeChat to itself or release its own assignment, never another's.+ if (call.args.assign !== true && (wechat.getChannelSettings() as { companionBotId?: string | null }).companionBotId !== botId)+ throwIpcError('PRECONDITION_FAILED', 'WeChat is assigned to another teammate');+ return { channelSettings: wechatSettings(await wechat.setCompanion(call.args.assign === true ? botId : null)) };+ },+ 'channels.wechat.unbind': async call => {+ const wechat = await wechatOf(deps);+ if ((wechat.getChannelSettings() as { companionBotId?: string | null }).companionBotId !== botOf(call))+ throwIpcError('PRECONDITION_FAILED', 'WeChat is assigned to another teammate');+ await wechat.unbind();+ return null;+ },+ 'channels.wechat.cancelAuthorization': async call => {+ botOf(call);+ (await wechatOf(deps)).cancelAuthorization();+ return null;+ },+ 'channels.x.get': async call => {+ botOf(call);+ return await deps.channels.x.summary();+ },+ 'channels.x.setCompanion': async call => {+ const botId = botOf(call);+ const summary = await deps.channels.x.summary();+ const expected = call.args.expectedBotId === null ? null : text(call.args.expectedBotId, 'expectedBotId', 128);+ if (call.args.assign !== true && summary.companionBotId !== botId) throwIpcError('PRECONDITION_FAILED', 'The official X account belongs to another teammate');+ await deps.channels.x.setCompanion(call.args.assign === true ? botId : null, expected);+ return deps.channels.x.summary();+ },'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/voice-conversation/index.ts b/apps/desktop/src/main/voice-conversation/index.tsindex f67496bfe7..72c89b8dd8 100644--- a/apps/desktop/src/main/voice-conversation/index.ts+++ b/apps/desktop/src/main/voice-conversation/index.ts@@ -30,13 +30,28 @@ import { classifyVoiceExit } from './semanticExit.js';const log = createLogger('voice-conversation');+/** What a remote Desktop's voice settings page needs; the IPC channels stay local to this window. */+export interface VoiceSettingsHostApi {+ models(): ReturnType<VoiceConversationService['models']>;+ voices(selection: unknown): ReturnType<VoiceConversationService['voices']>;+ preference(botId: unknown): Promise<VoiceConversationPreference>;+ setPreference(botId: unknown, value: unknown, sentencePlayback: unknown): Promise<VoiceConversationPreference>;+}+let settingsApi: VoiceSettingsHostApi | null = null;+export function getVoiceSettingsHostApi(): VoiceSettingsHostApi | null {+ return settingsApi;+}+function boundedString(value: unknown, name: string, limit: number): string {const text = requireString(value, name);if (!text.trim() || text.length > limit) throwIpcError('INVALID_PARAMS', `Invalid ${name}`);return text;}-/** Local top-level renderer only; deliberately absent from device-link and plugin allowlists. */+/**+ * Local top-level renderer only; the IPC channels are deliberately absent from device-link and plugin+ * allowlists. Model catalog and per-teammate preference are also served to the teammate settings host.+ */export function registerVoiceConversationIpc(deps: {createProvider(): Promise<AsrProvider>;createAudioGate(): AudioGate | undefined;@@ -140,10 +155,9 @@ export function registerVoiceConversationIpc(deps: {throw new Error('invalid_companion');return action(botId);};- handle('preference', (_event, raw) =>- preferenceBot(raw, (botId) => companionVoicePreference(deps.getSettings(), botId)),- );- handle('set-preference', (_event, raw, value, sentencePlayback) =>+ const readPreference = (raw: unknown) =>+ preferenceBot(raw, (botId) => companionVoicePreference(deps.getSettings(), botId));+ const writePreference = (raw: unknown, value: unknown, sentencePlayback: unknown) =>preferenceBot(raw, (botId) => {const settings = deps.getSettings();const patch: Partial<VoiceInputSettings> = {};@@ -164,8 +178,23 @@ export function registerVoiceConversationIpc(deps: {);}return companionVoicePreference(deps.updateSettings(patch), botId);- }),+ });+ handle('preference', (_event, raw) => readPreference(raw));+ handle('set-preference', (_event, raw, value, sentencePlayback) =>+ writePreference(raw, value, sentencePlayback),);+ // The settings page of a remote Desktop reads and writes the same preference through the+ // teammate settings host. Calls, previews and audio stay on the IPC channels above.+ settingsApi = {+ models: () => service.models(),+ voices: (raw) => {+ const selection = normalizeSpeechModelSelection(raw);+ if (!selection) throwIpcError('INVALID_PARAMS', 'Invalid speech model');+ return service.voices(selection!);+ },+ preference: readPreference,+ setPreference: writePreference,+ };for (const operation of ['start', 'start-playback'] as const) {handle(operation, async (event, raw) => {if (isAppSessionBoundaryPending()) throw new Error('changing_account');diff --git a/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx b/apps/desktop/src/renderer/components/settings/WechatBotSection.tsxindex 5842dc9b49..ec1e2f6d3c 100644--- a/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx+++ b/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx@@ -45,10 +45,16 @@ export function WechatBotSection({expanded,onToggle,companion,+ host,}: {expanded: boolean;onToggle: () => void;companion?: { id: string; name: string };+ /**+ * Set when the teammate runs on another computer: its WeChat API. Authorizing opens a browser and+ * scanning happens on that computer, so connecting stays there; assignment and release work from here.+ */+ host?: { name: string; api: Window['electronAPI']['wechatBot'] };}) {const { t } = useTranslation();const { confirm } = useConfirmDialog();@@ -65,7 +71,7 @@ export function WechatBotSection({resetWorkingDirectory,setCompanion,isUpdatingCompanion,- } = useWechatBot();+ } = useWechatBot(host?.api);const [routeSummary, setRouteSummary] = useImChannelSettingsSummary('wechat');const assigned = channelSettings?.companionBotId;const otherCompanion = !!companion && !!assigned && assigned !== companion.id;@@ -235,18 +241,20 @@ export function WechatBotSection({</div></div><div className="flex flex-wrap gap-2">- <Button- variant="secondary"- size="lg"- loading={isAuthorizing}- type="button"- onClick={() => void handleAuthorize()}- disabled={isAuthorizing || isUpdatingCompanion || !channelSettings || disabledByPolicy}- className="flex-1"- >- <RotateCw size={13} />- {t('settings.wechatBot.actions.rebind')}- </Button>+ {host ? null : (+ <Button+ variant="secondary"+ size="lg"+ loading={isAuthorizing}+ type="button"+ onClick={() => void handleAuthorize()}+ disabled={isAuthorizing || isUpdatingCompanion || !channelSettings || disabledByPolicy}+ className="flex-1"+ >+ <RotateCw size={13} />+ {t('settings.wechatBot.actions.rebind')}+ </Button>+ )}<Buttonvariant="secondary"size="lg"@@ -274,17 +282,23 @@ export function WechatBotSection({)}</p></div>- <Button- variant="cta"- size="lg"- loading={isAuthorizing}- type="button"- onClick={() => void handleAuthorize()}- disabled={isAuthorizing || isUpdatingCompanion || !channelSettings || disabledByPolicy}- className="w-full"- >- {t('settings.wechatBot.actions.connect')}- </Button>+ {host ? (+ <p className="text-12 leading-[1.6] text-[var(--settings-section-desc)]">+ {t('bots.remoteSettings.finishOnHost', { device: host.name })}+ </p>+ ) : (+ <Button+ variant="cta"+ size="lg"+ loading={isAuthorizing}+ type="button"+ onClick={() => void handleAuthorize()}+ disabled={isAuthorizing || isUpdatingCompanion || !channelSettings || disabledByPolicy}+ className="w-full"+ >+ {t('settings.wechatBot.actions.connect')}+ </Button>+ )}</div>)}</ImChannelSettingsCard>diff --git a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsxindex fcfc97d618..66b4a8f36f 100644--- a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx+++ b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx@@ -75,7 +75,7 @@ export function BotCapabilitySettings({setError(false);const load = async () => {try {- const next = await target.capabilities.load(bot, JSON.parse(modelChainKey));+ const next = await target.capabilities.load(bot, JSON.parse(modelChainKey), isCurrent);if (!isCurrent()) return;setCatalog({ key: catalogKey, entries: next });setError(kinds.some((kind) => !next[kind]));diff --git a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsxindex b94301b685..b2646b3110 100644--- a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx+++ b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx@@ -37,6 +37,8 @@ import type {BotImGroupActivationMode,} from '../../../shared/botImConnection';import { useBotTranslation } from './botPronounContext';+import { useBotSettingsTarget } from './useBotSettingsTarget';+import { RemoteOfficialXCard } from './RemoteOfficialXCard';import type { BotProfile } from './botStore';import {addBotImConnection,@@ -51,6 +53,7 @@ import {resetBotImConnectionLane,setBotImConnectionGroupActivation,useBotImConnections,+ type BotImConnectionApi,} from './botImConnectionClient';const BOT_TOKEN_PATTERN = /^\d+:[A-Za-z0-9_-]{20,}$/;@@ -104,7 +107,10 @@ const STATUS_TEXT: Record<StatusTone, string> = {export function BotChannelsPage({ bot }: { bot: BotProfile }) {const { t } = useBotTranslation();- const { payload, loading, apply } = useBotImConnections();+ // This computer's messaging stack, or the teammate's computer's through the settings target.+ const target = useBotSettingsTarget();+ const { im, wechat, x: remoteX } = target.channels;+ const { payload, loading, apply } = useBotImConnections(im);const { confirm } = useConfirmDialog();const [adding, setAdding] = useState(false);const [wechatExpanded, setWechatExpanded] = useState(false);@@ -137,7 +143,7 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {if (!ok) return;setRemovingId(view.id);try {- apply(await removeBotImConnection(view.id));+ apply(await removeBotImConnection(im, view.id));} catch {await confirm({title: t('bots.channels.removeConfirm.failed'),@@ -151,7 +157,8 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {return (<section className="flex flex-col gap-4 pt-3" aria-label={t('bots.channels.title')}>- {typeof window.electronAPI.hookControl?.setXCompanion === 'function' ? <HookConnectionsSection companion={{ id: bot.id, name: bot.name }} /> : null}+ {remoteX ? <RemoteOfficialXCard bot={bot} api={remoteX} deviceName={target.deviceName ?? ''} /> : null}+ {!remoteX && target.kind === 'local' && typeof window.electronAPI.hookControl?.setXCompanion === 'function' ? <HookConnectionsSection companion={{ id: bot.id, name: bot.name }} /> : null}{loading && !payload ? (<div className="flex justify-center py-6 text-[var(--text-tertiary)]"><Spinner size={16} />@@ -210,11 +217,11 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {{t('bots.channels.remove')}</Button></div>- {view.channel === 'telegram' && view.botContextId && botImConnectionGroupsSupported() ? (- <ConnectionGroups connectionId={view.id} botName={bot.name} />+ {view.channel === 'telegram' && view.botContextId && botImConnectionGroupsSupported(im) ? (+ <ConnectionGroups api={im} connectionId={view.id} botName={bot.name} />) : null}- {view.botContextId && botImConnectionLanesSupported() ? (- <ConnectionLanes connectionId={view.id} botName={bot.name} />+ {view.botContextId && botImConnectionLanesSupported(im) ? (+ <ConnectionLanes api={im} connectionId={view.id} botName={bot.name} />) : null}</li>);@@ -231,7 +238,11 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {{t('bots.channels.add.button')}</Button></div>- {typeof window.electronAPI.wechatBot?.setCompanion === 'function' ? (+ {wechat ? (+ <WechatBotSection companion={{ id: bot.id, name: bot.name }} expanded={wechatExpanded}+ host={{ name: target.deviceName ?? '', api: wechat }}+ onToggle={() => setWechatExpanded((expanded) => !expanded)} />+ ) : target.kind === 'local' && typeof window.electronAPI.wechatBot?.setCompanion === 'function' ? (<WechatBotSection companion={{ id: bot.id, name: bot.name }} expanded={wechatExpanded}onToggle={() => setWechatExpanded((expanded) => !expanded)} />) : null}@@ -242,7 +253,7 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {{t('bots.channels.sharedMemoryNote', { name: bot.name })}</p>{adding ? (- <BotChannelAddDialog bot={bot} onApplied={apply} onOpenChange={setAdding} />+ <BotChannelAddDialog bot={bot} api={im} remoteName={target.channels.canEnterCredentials ? undefined : target.deviceName} onApplied={apply} onOpenChange={setAdding} />) : null}</section>);@@ -252,7 +263,7 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {* 一条 Telegram 连接的「群聊」小节: 机器人进过的群 + 每群参与模式(仅 @ / 全响应)。* 与 设置 → IM 机器人 的同名设置各管各的 bot; 乐观更新, 保存失败回读正本并提示。*/-function ConnectionGroups({ connectionId, botName }: { connectionId: string; botName: string }) {+function ConnectionGroups({ api, connectionId, botName }: { api: BotImConnectionApi | null; connectionId: string; botName: string }) {const { t } = useBotTranslation();const [groups, setGroups] = useState<BotImConnectionGroup[] | null>(null);const [error, setError] = useState<'load' | 'save' | null>(null);@@ -262,7 +273,7 @@ function ConnectionGroups({ connectionId, botName }: { connectionId: string; botuseEffect(() => {let cancelled = false;setError(null);- void listBotImConnectionGroups(connectionId)+ void listBotImConnectionGroups(api, connectionId).then((payload) => {if (!cancelled) setGroups(payload.groups);})@@ -272,7 +283,7 @@ function ConnectionGroups({ connectionId, botName }: { connectionId: string; botreturn () => {cancelled = true;};- }, [connectionId, reloadToken]);+ }, [api, connectionId, reloadToken]);const setMode = useCallback((chatId: string, mode: BotImGroupActivationMode) => {@@ -281,21 +292,21 @@ function ConnectionGroups({ connectionId, botName }: { connectionId: string; botcurrent ? current.map((g) => (g.chatId === chatId ? { ...g, activation: mode } : g)) : current,);setError(null);- void setBotImConnectionGroupActivation(connectionId, chatId, mode)+ void setBotImConnectionGroupActivation(api, connectionId, chatId, mode).then((payload) => {if (revision === latest.current) setGroups(payload.groups);}).catch(() => {if (revision !== latest.current) return;setError('save');- void listBotImConnectionGroups(connectionId)+ void listBotImConnectionGroups(api, connectionId).then((payload) => {if (revision === latest.current) setGroups(payload.groups);}).catch(() => undefined);});},- [connectionId],+ [api, connectionId],);if (groups === null && error !== 'load') return null;@@ -357,7 +368,7 @@ const LANE_KIND_KEY: Record<BotImConnectionLane['kind'], string> = {* 显示状态、最近活动和当前上下文里的消息数; 卡住时可以让某一条重新开始(同一条任务,* 记录保留, 下一条消息换干净的上下文)。隐藏任务没有自己的任务页, 所以这里不提供打开。*/-function ConnectionLanes({ connectionId, botName }: { connectionId: string; botName: string }) {+function ConnectionLanes({ api, connectionId, botName }: { api: BotImConnectionApi | null; connectionId: string; botName: string }) {const { t } = useBotTranslation();const { confirm } = useConfirmDialog();const [lanes, setLanes] = useState<BotImConnectionLane[] | null>(null);@@ -371,7 +382,7 @@ function ConnectionLanes({ connectionId, botName }: { connectionId: string; botNuseEffect(() => {let cancelled = false;const load = () => {- void listBotImConnectionLanes(connectionId)+ void listBotImConnectionLanes(api, connectionId).then((payload) => {if (cancelled) return;setLanes(payload.lanes);@@ -390,7 +401,7 @@ function ConnectionLanes({ connectionId, botName }: { connectionId: string; botNcancelled = true;clearInterval(timer);};- }, [connectionId, reloadToken]);+ }, [api, connectionId, reloadToken]);const laneName = (lane: BotImConnectionLane) =>lane.kind === 'owner-dm' ? t('bots.channels.lanes.ownerName') : lane.name || lane.chatId || '';@@ -414,7 +425,7 @@ function ConnectionLanes({ connectionId, botName }: { connectionId: string; botNsetResettingId(lane.sessionId);setNotice(null);try {- const payload = await resetBotImConnectionLane(connectionId, lane.sessionId);+ const payload = await resetBotImConnectionLane(api, connectionId, lane.sessionId);setLanes(payload.lanes);setNow(Date.now());setNotice({ tone: 'done', text: t('bots.channels.lanes.resetDone', { lane: name }) });@@ -567,10 +578,15 @@ function SourceOption({function BotChannelAddDialog({bot,+ api,+ remoteName,onApplied,onOpenChange,}: {bot: BotProfile;+ api: BotImConnectionApi | null;+ /** Set for a teammate on another computer: credentials are typed and stored on that computer only. */+ remoteName?: string;onApplied: (next: BotImConnectionListPayload) => void;onOpenChange: (open: boolean) => void;}) {@@ -596,13 +612,14 @@ function BotChannelAddDialog({const [adoptable, setAdoptable] = useState<BotImAdoptablePersonalBot[]>([]);const [source, setSource] = useState<'existing' | 'manual'>('existing');const existing = adoptable.find((item) => item.channel === channel) ?? null;- const useExisting = existing !== null && source === 'existing';+ const credentialsHere = remoteName === undefined;+ const useExisting = existing !== null && (source === 'existing' || !credentialsHere);const refreshAdoptable = useCallback(() => {- void listAdoptablePersonalBots()+ void listAdoptablePersonalBots(api).then((next) => setAdoptable(next.bots)).catch(() => setAdoptable([]));- }, []);+ }, [api]);useEffect(refreshAdoptable, [refreshAdoptable]);useEffect(() => {@@ -613,7 +630,9 @@ function BotChannelAddDialog({const filled = (...values: string[]) => values.every((value) => value.trim().length > 0);const canSubmit = useExisting? true- : channel === 'telegram'+ : !credentialsHere+ ? false+ : channel === 'telegram'? filled(token, ownerUserId): channel === 'feishu'? filled(appId, appSecret)@@ -672,7 +691,7 @@ function BotChannelAddDialog({setBusy(true);setError(null);try {- const next = input ? await addBotImConnection(input) : await adoptPersonalBot({ botId: bot.id, channel });+ const next = input ? await addBotImConnection(api, input) : await adoptPersonalBot(api, { botId: bot.id, channel });onApplied(next);onOpenChange(false);} catch (failure) {@@ -770,18 +789,25 @@ function BotChannelAddDialog({detail={adoptableIdentity(existing)}onSelect={() => setSource('existing')}/>- <SourceOption- checked={!useExisting}- disabled={busy}- title={t('bots.channels.add.source.manual')}- onSelect={() => setSource('manual')}- />+ {credentialsHere ? (+ <SourceOption+ checked={!useExisting}+ disabled={busy}+ title={t('bots.channels.add.source.manual')}+ onSelect={() => setSource('manual')}+ />+ ) : null}</div>) : null}{useExisting ? (<p className="px-1 text-12 leading-[1.5] text-[var(--text-secondary)]">{t('bots.channels.add.source.moveNote', { name: bot.name })}</p>+ ) : !credentialsHere ? (+ // Tokens and secrets are typed where they are stored; they never travel to another computer.+ <p className="px-1 text-12 leading-[1.5] text-[var(--text-secondary)]">+ {t('bots.remoteSettings.finishOnHost', { device: remoteName })}+ </p>) : channel === 'telegram' ? (<><FormField label={t('bots.channels.add.telegram.tokenLabel')}>diff --git a/apps/desktop/src/renderer/features/bots/BotRoutines.tsx b/apps/desktop/src/renderer/features/bots/BotRoutines.tsxindex 0847c849e6..adbf7721d9 100644--- a/apps/desktop/src/renderer/features/bots/BotRoutines.tsx+++ b/apps/desktop/src/renderer/features/bots/BotRoutines.tsx@@ -15,6 +15,7 @@ import { Input, Textarea } from '@/components/ui/input';import { Switch } from '@/components/ui/switch';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { Spinner } from '@/components/ui/spinner';+import { useBotSettingsTarget } from './useBotSettingsTarget';import {DropdownMenu,DropdownMenuTrigger,@@ -46,6 +47,7 @@ export function BotRoutines({backRef?: { current: (() => Promise<boolean>) | null };}) {const { confirm } = useConfirmDialog();+ const routinesApi = useBotSettingsTarget().routines;const inFlight = useRef(false);const [loading, setLoading] = useState(true);const [reload, setReload] = useState(0);@@ -60,8 +62,8 @@ export function BotRoutines({const [deletePending, setDeletePending] = useState(false);const refresh = useCallback(async () => {const [items, available] = await Promise.all([- window.electronAPI.routines.list(botId),- window.electronAPI.routines.sources(),+ routinesApi.list(botId),+ routinesApi.sources(),]);setRoutines(items);setSources(available);@@ -72,8 +74,8 @@ export function BotRoutines({const load = () => {const current = ++request;void Promise.all([- window.electronAPI.routines.list(botId),- window.electronAPI.routines.sources(),+ routinesApi.list(botId),+ routinesApi.sources(),]).then(([items, available]) => {if (alive && current === request) {@@ -92,7 +94,7 @@ export function BotRoutines({};setLoading(true);load();- const unsubscribe = window.electronAPI.routines.onChanged(load);+ const unsubscribe = routinesApi.onChanged(load);return () => {alive = false;unsubscribe();@@ -105,7 +107,7 @@ export function BotRoutines({return;}const load = () => {- void window.electronAPI.routines+ void routinesApi.history(botId, selected).then((runs) => {if (alive) setHistory(runs);@@ -115,7 +117,7 @@ export function BotRoutines({});};load();- const unsubscribe = window.electronAPI.routines.onChanged(load);+ const unsubscribe = routinesApi.onChanged(load);return () => {alive = false;unsubscribe();@@ -272,7 +274,7 @@ export function BotRoutines({routine={routine}disabled={busy}onEnabledChange={(enabled) =>- void act(() => window.electronAPI.routines.save(botId, routineInput({ ...routine, enabled }), routine.id))+ void act(() => routinesApi.save(botId, routineInput({ ...routine, enabled }), routine.id))}/>) : (@@ -325,9 +327,9 @@ export function BotRoutines({onClick={() => {if (revealInvalidField()) return;void act(async () => {- const saved = await window.electronAPI.routines.save(botId, draft, selected!);+ const saved = await routinesApi.save(botId, draft, selected!);setDraft(structuredClone(saved));- await window.electronAPI.routines.runNow(botId, saved.id);+ await routinesApi.runNow(botId, saved.id);});}}>@@ -494,7 +496,7 @@ export function BotRoutines({onClick={() => {if (revealInvalidField()) return;void act(async () => {- const saved = await window.electronAPI.routines.save(+ const saved = await routinesApi.save(botId,draft,selected === 'new' ? undefined : selected!,@@ -518,7 +520,7 @@ export function BotRoutines({disabled={busy}onClick={() =>void act(async () => {- await window.electronAPI.routines.remove(botId, selected!);+ await routinesApi.remove(botId, selected!);setDraft(null);setSelected(null);setDeletePending(false);diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsxindex 54d7df8ccf..7d1622469e 100644--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx@@ -750,7 +750,8 @@ export function BotSettings({{page === 'voice' ? (<CompanionVoiceSettings botId={bot.id} sessionId={canonicalBotSessionId(bot) ?? undefined}beforeLeaveRef={voiceLeaveRef}- onOpenProviders={() => {+ // Providers are connected in the settings of the computer the teammate runs on.+ onOpenProviders={isRemote ? undefined : () => {void canLeave().then((allowed) => {if (allowed) navigate('/settings?tab=providers');});diff --git a/apps/desktop/src/renderer/features/bots/RemoteOfficialXCard.tsx b/apps/desktop/src/renderer/features/bots/RemoteOfficialXCard.tsxnew file mode 100644index 0000000000..30f095dd69--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/RemoteOfficialXCard.tsx@@ -0,0 +1,96 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { Spinner } from '@/components/ui/spinner';+import { toast } from '@/lib/toast';+import type { BotSettingsTarget } from './botSettingsTarget';+import type { BotProfile } from './botStore';++type XApi = NonNullable<BotSettingsTarget['channels']['x']>;+type XState = Awaited<ReturnType<XApi['get']>>;++/**+ * The official X account of the teammate's computer, as a teammate on that computer sees it: who it is+ * assigned to, and assigning it to or releasing it from this teammate. Signing in to X opens a browser on+ * that computer, so connecting stays there.+ */+export function RemoteOfficialXCard({ bot, api, deviceName }: { bot: Pick<BotProfile, 'id' | 'name'>; api: XApi; deviceName: string }) {+ const { t } = useTranslation();+ const { confirm } = useConfirmDialog();+ const [state, setState] = useState<XState | null>(null);+ const [failed, setFailed] = useState(false);+ const [pending, setPending] = useState(false);+ const busy = useRef(false);++ const load = useCallback(() => {+ setFailed(false);+ void api.get().then(setState, () => setFailed(true));+ }, [api]);+ useEffect(load, [load]);++ const bound = state?.companionBotId === bot.id;+ const change = async () => {+ if (busy.current || !state) return;+ busy.current = true;+ setPending(true);+ try {+ const ok = await confirm({+ title: t(`bots.channels.officialX.${bound ? 'removeTitle' : 'bindTitle'}`, { name: bot.name }),+ description: t(`bots.channels.officialX.${bound ? 'removeBody' : 'bindBody'}`, { name: bot.name }),+ confirmText: t(`bots.channels.officialX.${bound ? 'remove' : 'bind'}`),+ });+ if (!ok) return;+ const next = await api.setCompanion(!bound, state.companionBotId);+ setState({ ...state, companionBotId: next.companionBotId });+ } catch {+ toast.error(t('settings.remoteControl.hook.toast.actionFailed'));+ load();+ } finally {+ busy.current = false;+ setPending(false);+ }+ };++ if (!state && !failed) {+ return (+ <div className="flex justify-center py-4 text-[var(--text-tertiary)]">+ <Spinner size={16} />+ </div>+ );+ }+ // An older computer, or one without the official X service, simply has nothing to show.+ if (!state || !state.available) return null;+ const ready = state.enabled && state.connected;+ return (+ <section+ className="flex flex-col gap-2 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3"+ aria-label={t('settings.tina.prefs.providerX')}+ >+ <p className="text-14 text-[var(--text-primary)]">{t('settings.tina.prefs.providerX')}</p>+ <p className="text-12 leading-relaxed text-[var(--text-secondary)]">+ {t(+ bound+ ? 'bots.channels.officialX.bound'+ : state.companionBotId+ ? 'bots.channels.officialX.boundElsewhere'+ : 'bots.channels.officialX.unbound',+ { name: bot.name },+ )}+ </p>+ {ready || bound ? (+ <div>+ <Button variant="secondary" size="sm" type="button" loading={pending} disabled={pending} onClick={() => void change()}>+ {t(bound ? 'bots.channels.officialX.remove' : 'bots.channels.officialX.bind')}+ </Button>+ </div>+ ) : (+ // Connecting the account signs in through a browser on the computer that runs it.+ <p className="text-12 leading-relaxed text-[var(--text-secondary)]">+ {t('bots.remoteSettings.finishOnHost', { device: deviceName })}+ </p>+ )}+ </section>+ );+}diff --git a/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsx b/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsxindex fd562eb7cf..85393d9577 100644--- a/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsx@@ -119,6 +119,10 @@ function RemoteSettingsPages({ bot, ops, initialPage: requestedPage = 'home', be() =>window.electronAPI.deviceLink.onRemotePush((push, stamp) => {const payload = parseRemoteResourceChangedPayload(push.payload);+ if (push.deviceId === bot.deviceId && push.channel === REMOTE_RESOURCE_CHANGED_CHANNEL && payload?.collectionId === 'routines' && isDeviceLinkRemotePushCurrent(push, stamp)) {+ handle.changed('routines');+ return;+ }if (push.deviceId !== bot.deviceId ||push.channel !== REMOTE_RESOURCE_CHANGED_CHANNEL ||diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsxindex c47421d037..a505f526ce 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx@@ -24,6 +24,8 @@ vi.mock('@/components/ui/confirm-dialog-provider', () => ({}));import { BotChannelsPage } from '../BotChannelsPage';+import { BotSettingsTargetContext, type BotSettingsTarget } from '../botSettingsTarget';+import { localBotSettingsTarget } from '../localBotSettingsTarget';function profile(id: string, name: string): BotProfile {return {@@ -357,3 +359,69 @@ describe('BotChannelsPage', () => {);});});++describe('BotChannelsPage for a teammate on another computer', () => {+ /** The page talks to the other computer's API only; this window's own API must stay untouched. */+ function renderRemote(api: Record<string, unknown>, channels: Partial<BotSettingsTarget['channels']> = {}) {+ const own = installApi({ connections: [] });+ const target = {+ ...localBotSettingsTarget,+ kind: 'remote',+ deviceId: 'mac',+ deviceName: 'Studio',+ channels: { im: api, canEnterCredentials: false, wechat: null, x: null, ...channels },+ } as unknown as BotSettingsTarget;+ render(+ <BotSettingsTargetContext.Provider value={target}>+ <BotChannelsPage bot={mia} />+ </BotSettingsTargetContext.Provider>,+ );+ return own;+ }+ const remoteApi = (extra: Record<string, unknown> = {}) => ({+ list: vi.fn(async () => ({ connections: [connection()] })),+ add: vi.fn(async () => { throw new Error('credentials never travel'); }),+ remove: vi.fn(async () => ({ connections: [], archivedSessionIds: [] })),+ listAdoptable: vi.fn(async () => ({ bots: [] })),+ adopt: vi.fn(),+ onChanged: vi.fn(() => () => undefined),+ ...extra,+ });++ it('lists and removes connections through the other computer, never this window', async () => {+ const api = remoteApi();+ const own = renderRemote(api);+ expect(await screen.findByText('bots.channels.platform.telegram')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /bots\.channels\.removeAria/ }));+ await waitFor(() => expect(api.remove).toHaveBeenCalledWith({ id: 'a1b2c3d4e5f6' }));+ expect(own.list).not.toHaveBeenCalled();+ expect(own.remove).not.toHaveBeenCalled();+ });++ it('asks for credentials only on the other computer', async () => {+ const api = remoteApi();+ renderRemote(api);+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.add.button' }));+ const dialog = await screen.findByRole('dialog');+ expect(within(dialog).queryByLabelText('bots.channels.add.telegram.tokenLabel')).toBeNull();+ expect(within(dialog).getByText(/bots\.remoteSettings\.finishOnHost:.*Studio/)).toBeTruthy();+ expect((within(dialog).getByRole('button', { name: 'bots.channels.add.confirm' }) as HTMLButtonElement).disabled).toBe(true);+ expect(api.add).not.toHaveBeenCalled();+ });++ it('still moves the personal bot that is already set up there, without any credential', async () => {+ const api = remoteApi({+ listAdoptable: vi.fn(async () => ({ bots: [{ channel: 'telegram', identity: '@mia_bot' }] })),+ adopt: vi.fn(async () => ({ connections: [connection()], connection: connection() })),+ });+ renderRemote(api);+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.add.button' }));+ const dialog = await screen.findByRole('dialog');+ await within(dialog).findByRole('radio', { name: /bots\.channels\.add\.source\.existing/ });+ expect(within(dialog).queryByRole('radio', { name: 'bots.channels.add.source.manual' })).toBeNull();+ fireEvent.click(within(dialog).getByRole('button', { name: 'bots.channels.add.confirm' }));+ await waitFor(() => expect(api.adopt).toHaveBeenCalledWith({ botId: 'bot-1', channel: 'telegram' }));+ expect(api.add).not.toHaveBeenCalled();+ });+});+diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSettingsTarget.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSettingsTarget.test.tsindex f3d0cb64b0..8fba3ce8f8 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSettingsTarget.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSettingsTarget.test.ts@@ -30,7 +30,10 @@ const refused = (code: string, message: string) => ({ result: { ok: false, code,/** 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[];+ 'memory.list', 'memory.read', 'memory.update', 'memory.delete', 'capabilities.catalog', 'autonomy.get', 'autonomy.set', 'autonomy.reset', 'history.search',+ 'routines.list', 'routines.sources', 'routines.history', 'routines.save', 'routines.runNow', 'routines.remove',+ 'voice.models', 'voice.voices', 'voice.preference', 'voice.setPreference',+ 'channels.im.list', 'channels.im.remove', 'channels.wechat.get', 'channels.x.get'] as BotSettingsOp[];function create(ops: BotSettingsOp[] = ALL_OPS) {return createRemoteBotSettingsTarget({ deviceId: 'mac', deviceName: 'Studio', botId: 'bot-1', ops: new Set(ops), online: () => true });@@ -108,7 +111,7 @@ it('builds the capability lists from the host catalog without the fixed baselinetoolset: [{ 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, []);+ const catalog = await target.capabilities.load({ id: 'bot-1' } as never, [], () => true);expect(catalog.skill).toEqual([{ id: 'personal:brief', name: 'Brief', available: false, personal: true },{ id: 'review', name: 'review', description: 'Review', available: true },@@ -124,8 +127,38 @@ it('does not re-read a deleted teammate after the lifecycle action', async () =>expect(host.invoke).toHaveBeenCalledTimes(1);});+it('runs routines on the teammate computer and tells the page when they change there', async () => {+ const { target, changed } = create();+ host.invoke.mockResolvedValue(ok([]));+ await target.routines.save('bot-1', { name: 'Digest' } as never, 'r1');+ expect(sent()).toMatchObject({ resourceRef: { id: 'bot-1' }, input: { op: 'routines.save', args: { id: 'r1', input: { name: 'Digest' } } } });+ await target.routines.sources();+ expect(sent(1)).toMatchObject({ input: { op: 'routines.sources' } });+ expect(sent(1).resourceRef).toBeUndefined();+ const listener = vi.fn();+ const off = target.routines.onChanged(listener);+ changed('routines');+ expect(listener).toHaveBeenCalledTimes(1);+ off();+ changed('routines');+ expect(listener).toHaveBeenCalledTimes(1);+});++it('never takes credentials and leaves browser sign-in and folder choosing to the teammate computer', async () => {+ const { target } = create();+ const im = target.channels.im!;+ expect(target.channels.canEnterCredentials).toBe(false);+ await expect(im.add({ botId: 'bot-1', channel: 'telegram', token: 'secret', ownerUserId: '1' })).rejects.toSatisfy((error) => extractIpcError(error)?.code === 'PRECONDITION_FAILED');+ await expect(target.channels.wechat!.authorize()).rejects.toBeTruthy();+ await expect(target.channels.wechat!.chooseWorkingDirectory()).rejects.toBeTruthy();+ expect(host.invoke).not.toHaveBeenCalled();+ host.invoke.mockResolvedValueOnce(ok({ channelSettings: { version: 1, workingDir: null, workingDirAvailable: true, companionBotId: 'bot-1' } }));+ await expect(target.channels.wechat!.setCompanion('bot-1')).resolves.toMatchObject({ companionBotId: 'bot-1' });+ expect(sent()).toMatchObject({ resourceRef: { id: 'bot-1' }, input: { op: 'channels.wechat.setCompanion', args: { assign: true } } });+});+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(ALL_OPS))].sort()).toEqual(['capabilities', 'channels', 'history', 'memory', 'model', 'personality', 'profile', 'routines', 'voice']);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/botImConnectionClient.ts b/apps/desktop/src/renderer/features/bots/botImConnectionClient.tsindex 49e8bb055f..6bfdfe1ac5 100644--- a/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts+++ b/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts@@ -18,7 +18,7 @@ import type {BotImGroupActivationMode,} from '../../../shared/botImConnection';-type BotImConnectionApi = Window['electronAPI']['botImConnection'];+export type BotImConnectionApi = Window['electronAPI']['botImConnection'];export function botImConnectionApi(): BotImConnectionApi | null {// 副窗口 / 旧 preload 没有这个命名空间时整块功能静默隐藏, 不抛错。@@ -27,18 +27,18 @@ export function botImConnectionApi(): BotImConnectionApi | null {return api && typeof api.list === 'function' ? api : null;}-export function useBotImConnections(): {+export function useBotImConnections(api: BotImConnectionApi | null = botImConnectionApi()): {payload: BotImConnectionListPayload | null;/** 首次读取还在途; 读取失败或没有 IPC 时为 false, payload 保持 null。 */loading: boolean;apply: (next: BotImConnectionListPayload) => void;} {const [payload, setPayload] = useState<BotImConnectionListPayload | null>(null);- const [loading, setLoading] = useState(() => botImConnectionApi() !== null);+ const [loading, setLoading] = useState(() => api !== null);useEffect(() => {- const api = botImConnectionApi();if (!api) return;+ setPayload(null);let cancelled = false;const unsubscribe = api.onChanged((next) => {if (!cancelled) setPayload(next);@@ -59,74 +59,65 @@ export function useBotImConnections(): {cancelled = true;unsubscribe();};- }, []);+ }, [api]);return { payload, loading, apply: setPayload };}-export function addBotImConnection(input: BotImConnectionAddInput): Promise<BotImConnectionAddResult> {- const api = botImConnectionApi();+export function addBotImConnection(api: BotImConnectionApi | null, input: BotImConnectionAddInput): Promise<BotImConnectionAddResult> {if (!api) return Promise.reject(new Error('botImConnection IPC unavailable'));return api.add(input);}-export function removeBotImConnection(id: string): Promise<BotImConnectionRemoveResult> {- const api = botImConnectionApi();+export function removeBotImConnection(api: BotImConnectionApi | null, id: string): Promise<BotImConnectionRemoveResult> {if (!api) return Promise.reject(new Error('botImConnection IPC unavailable'));return api.remove({ id });}/** 旧 preload 没有群聊接口时整个「群聊」小节不显示。 */-export function botImConnectionGroupsSupported(): boolean {- const api = botImConnectionApi();+export function botImConnectionGroupsSupported(api: BotImConnectionApi | null = botImConnectionApi()): boolean {return !!api && typeof api.listGroups === 'function' && typeof api.setGroupActivation === 'function';}-export function listBotImConnectionGroups(id: string): Promise<BotImConnectionGroupsPayload> {- const api = botImConnectionApi();+export function listBotImConnectionGroups(api: BotImConnectionApi | null, id: string): Promise<BotImConnectionGroupsPayload> {if (!api?.listGroups) return Promise.reject(new Error('botImConnection IPC unavailable'));return api.listGroups({ id });}export function setBotImConnectionGroupActivation(+ api: BotImConnectionApi | null,id: string,chatId: string,mode: BotImGroupActivationMode,): Promise<BotImConnectionGroupsPayload> {- const api = botImConnectionApi();if (!api?.setGroupActivation) return Promise.reject(new Error('botImConnection IPC unavailable'));return api.setGroupActivation({ id, chatId, mode });}/** 旧 preload 没有隐藏任务接口时整个小节不显示。 */-export function botImConnectionLanesSupported(): boolean {- const api = botImConnectionApi();+export function botImConnectionLanesSupported(api: BotImConnectionApi | null = botImConnectionApi()): boolean {return !!api && typeof api.listLanes === 'function' && typeof api.resetLane === 'function';}-export function listBotImConnectionLanes(id: string): Promise<BotImConnectionLanesPayload> {- const api = botImConnectionApi();+export function listBotImConnectionLanes(api: BotImConnectionApi | null, id: string): Promise<BotImConnectionLanesPayload> {if (!api?.listLanes) return Promise.reject(new Error('botImConnection IPC unavailable'));return api.listLanes({ id });}/** 让一条隐藏任务重新开始(下一条消息从干净的上下文开始, 记录保留)。 */-export function resetBotImConnectionLane(id: string, sessionId: string): Promise<BotImConnectionLanesPayload> {- const api = botImConnectionApi();+export function resetBotImConnectionLane(api: BotImConnectionApi | null, id: string, sessionId: string): Promise<BotImConnectionLanesPayload> {if (!api?.resetLane) return Promise.reject(new Error('botImConnection IPC unavailable'));return api.resetLane({ id, sessionId });}/** 设置 → IM 机器人 里可以移给伙伴的个人 bot; 旧 preload 没有这个接口时当作没有。 */-export function listAdoptablePersonalBots(): Promise<BotImAdoptablePersonalBotsPayload> {- const api = botImConnectionApi();+export function listAdoptablePersonalBots(api: BotImConnectionApi | null): Promise<BotImAdoptablePersonalBotsPayload> {if (!api?.listAdoptable) return Promise.resolve({ bots: [] });return api.listAdoptable();}/** 把个人 bot 移给伙伴(个人 bot 随之清空)。 */-export function adoptPersonalBot(input: BotImAdoptPersonalBotInput): Promise<BotImConnectionAddResult> {- const api = botImConnectionApi();+export function adoptPersonalBot(api: BotImConnectionApi | null, input: BotImAdoptPersonalBotInput): Promise<BotImConnectionAddResult> {if (!api?.adopt) return Promise.reject(new Error('botImConnection IPC unavailable'));return api.adopt(input);}diff --git a/apps/desktop/src/renderer/features/bots/botSettingsTarget.ts b/apps/desktop/src/renderer/features/bots/botSettingsTarget.tsindex 4c23133fe3..96b6be155b 100644--- a/apps/desktop/src/renderer/features/bots/botSettingsTarget.ts+++ b/apps/desktop/src/renderer/features/bots/botSettingsTarget.ts@@ -18,6 +18,10 @@ export type BotCapabilityEntry = {};type Bots = NonNullable<Window['electronAPI']['localDb']>['bots'];+export type BotRoutinesApi = Window['electronAPI']['routines'];+type VoiceApi = Window['electronAPI']['voiceConversation'];+type ImConnectionApi = Window['electronAPI']['botImConnection'];+type WechatApi = Window['electronAPI']['wechatBot'];/*** The computer a teammate's settings pages read from and write to. The pages are the same components for@@ -49,10 +53,32 @@ export interface BotSettingsTarget {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[]>>>;+ /** `isCurrent` turns false once a newer load superseded this one, so it can stop before its next request. */+ load(bot: BotProfile, modelChain: BotModelRoute[], isCurrent: () => boolean): Promise<Partial<Record<BotCapabilityKind, BotCapabilityEntry[]>>>;/** Calls `refresh` when the catalog may have changed (runtime, MCP or profile changes). */watch(bot: BotProfile, refresh: () => void): () => void;};+ /** Messaging platforms: the connections live on the computer that stores their credentials. */+ channels: {+ im: ImConnectionApi | null;+ /** False for another computer: credentials are never typed into a remote page. */+ canEnterCredentials: boolean;+ /** Personal WeChat of the teammate's computer; null = this window's own API (local only). */+ wechat: WechatApi | null;+ /** The official X account of the teammate's computer (remote only). */+ x: {+ get(): Promise<{ available: boolean; enabled: boolean; connected: boolean; companionBotId: string | null }>;+ setCompanion(assign: boolean, expectedBotId: string | null): Promise<{ companionBotId: string | null }>;+ } | null;+ };+ voice: Pick<VoiceApi, 'models' | 'voices' | 'preference' | 'setPreference'> & {+ /** Refreshes the gateway model list before reading the catalog (a computer refreshes its own on use). */+ refreshCatalog?(): Promise<void>;+ /** Sample playback uses this window's speakers and its own voice service; absent for another computer. */+ previewApi?: VoiceApi;+ };+ /** Routines of the teammate's computer (`onChanged` fires when they change there). */+ routines: BotRoutinesApi;autonomy: {useSettings(): BotAutonomySettingsView | null;setSchedulerBotId(botId: string | null): Promise<void>;diff --git a/apps/desktop/src/renderer/features/bots/localBotSettingsTarget.ts b/apps/desktop/src/renderer/features/bots/localBotSettingsTarget.tsindex e6c4a55ce7..8bc4d364ce 100644--- a/apps/desktop/src/renderer/features/bots/localBotSettingsTarget.ts+++ b/apps/desktop/src/renderer/features/bots/localBotSettingsTarget.ts@@ -21,6 +21,7 @@ import {useBotAutonomySettings,useBotProfiles,} from './botStore';+import { botImConnectionApi } from './botImConnectionClient';import type { BotCapabilityEntry, BotCapabilityKind, BotSettingsTarget } from './botSettingsTarget';const api = () => window.electronAPI.localDb.bots;@@ -36,9 +37,11 @@ const CATALOG_PATCH_KEYS = [async function loadCatalog(bot: { id: string; canonicalSessionId?: string },modelChain: unknown,+ isCurrent: () => boolean,): Promise<Partial<Record<BotCapabilityKind, BotCapabilityEntry[]>>> {if (!bot.canonicalSessionId) throw new Error('Missing canonical task');const session = await sessionService.get(bot.canonicalSessionId);+ if (!isCurrent()) return {};const maker = window.electronAPI.maker;const mcpResult = await maker.listCustomMcpServers({agentKind:@@ -48,6 +51,7 @@ async function loadCatalog(botSessionId: bot.canonicalSessionId,modelChain: modelChain as never,});+ if (!isCurrent()) return {};const agentKind = mcpResult.agentKind;if (!agentKind) throw new Error('Missing next-turn route');const results = await Promise.allSettled([@@ -128,7 +132,7 @@ export const localBotSettingsTarget: BotSettingsTarget = {},history: { search: (body) => api().searchHistory(body) as Promise<ConversationSearchResponse> },capabilities: {- load: (bot, modelChain) => loadCatalog(bot, modelChain),+ load: (bot, modelChain, isCurrent) => loadCatalog(bot, modelChain, isCurrent),watch(bot, refresh) {const changed = (sessionId: string, patch: Partial<Session>) => {if (sessionId === bot.canonicalSessionId && CATALOG_PATCH_KEYS.some((key) => key in patch)) refresh();@@ -145,6 +149,35 @@ export const localBotSettingsTarget: BotSettingsTarget = {};},},+ channels: {+ get im() {+ return botImConnectionApi();+ },+ canEnterCredentials: true,+ wechat: null,+ x: null,+ },+ voice: {+ models: () => window.electronAPI.voiceConversation.models(),+ voices: (...args) => window.electronAPI.voiceConversation.voices(...args),+ preference: (...args) => window.electronAPI.voiceConversation.preference(...args),+ setPreference: (...args) => window.electronAPI.voiceConversation.setPreference(...args),+ refreshCatalog: async () => {+ await window.electronAPI.maker.refreshBuiltinProviderModels('xd');+ },+ get previewApi() {+ return window.electronAPI.voiceConversation;+ },+ },+ routines: {+ list: (...args) => window.electronAPI.routines.list(...args),+ save: (...args) => window.electronAPI.routines.save(...args),+ remove: (...args) => window.electronAPI.routines.remove(...args),+ runNow: (...args) => window.electronAPI.routines.runNow(...args),+ history: (...args) => window.electronAPI.routines.history(...args),+ sources: () => window.electronAPI.routines.sources(),+ onChanged: (listener) => window.electronAPI.routines.onChanged(listener),+ },autonomy: {useSettings: () => useBotAutonomySettings(),setSchedulerBotId: (botId) => setBotSchedulerBotId(botId),diff --git a/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.ts b/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.tsindex f07092503b..2aa85bac24 100644--- a/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.ts+++ b/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.ts@@ -113,6 +113,32 @@ async function toRemoteAvatar(base64: string): Promise<string> {const BASELINE_TOOLSETS = ['memory', 'xdt_helper', 'scheduler', 'lsp'];+/** Connection and account states have no push to a controller; read them while a page is open and visible. */+const CHANNEL_POLL_MS = 5_000;+function pollWhileVisible<T>(read: () => Promise<T>, listener: (value: T) => void): () => void {+ let stopped = false;+ let last: string | undefined;+ const tick = async () => {+ if (stopped || document.hidden) return;+ try {+ const value = await read();+ const key = JSON.stringify(value);+ if (stopped || key === last) return;+ last = key;+ listener(value);+ } catch {+ /* A failed read keeps what the page shows; the next tick tries again. */+ }+ };+ void tick();+ const timer = setInterval(() => void tick(), CHANNEL_POLL_MS);+ return () => {+ stopped = true;+ clearInterval(timer);+ };+}+const hostOnly = () => Promise.reject(createIpcError('PRECONDITION_FAILED', 'This is done on the teammate’s computer'));+/** 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));@@ -125,6 +151,9 @@ export function remoteBotSettingsPages(ops: ReadonlySet<BotSettingsOp>): Set<strif (has('models.default', 'profile.update')) pages.add('model');if (has('capabilities.catalog')) pages.add('capabilities');if (has('history.search')) pages.add('history');+ if (has('voice.models', 'voice.voices', 'voice.preference', 'voice.setPreference')) pages.add('voice');+ if (has('channels.im.list', 'channels.im.remove')) pages.add('channels');+ if (has('routines.list', 'routines.sources', 'routines.history', 'routines.save', 'routines.runNow', 'routines.remove')) pages.add('routines');return pages;}@@ -162,7 +191,50 @@ export function createRemoteBotSettingsTarget(input: RemoteBotSettingsInput) {autonomyListeners.forEach((listener) => listener());};+ const call2 = <T>(op: BotSettingsOp, args?: Record<string, unknown>) => invokeBotSettings<T>(deviceId, op, botId, args);+ const im: BotSettingsTarget['channels']['im'] = {+ list: () => call2('channels.im.list'),+ // Tokens and secrets are typed where they are stored; a remote page never takes or sends them.+ add: hostOnly,+ remove: (payload) => call2('channels.im.remove', { id: payload.id }),+ listGroups: (payload) => call2('channels.im.listGroups', { id: payload.id }),+ setGroupActivation: (payload) => call2('channels.im.setGroupActivation', { ...payload }),+ listLanes: (payload) => call2('channels.im.listLanes', { id: payload.id }),+ resetLane: (payload) => call2('channels.im.resetLane', { ...payload }),+ listAdoptable: () => invokeBotSettings(deviceId, 'channels.im.listAdoptable', null),+ adopt: (payload) => call2('channels.im.adopt', { channel: payload.channel }),+ onChanged: (listener) => pollWhileVisible(() => call2<{ connections: unknown[] }>('channels.im.list'), listener as never),+ };+ let wechatRead: { at: number; value: Promise<{ state: WechatBotState; channelSettings: WechatChannelSettingsState }> } | null = null;+ const readWechat = () => {+ if (!wechatRead || Date.now() - wechatRead.at > 1_000)+ wechatRead = { at: Date.now(), value: call2('channels.wechat.get') };+ return wechatRead.value;+ };+ const wechat: BotSettingsTarget['channels']['wechat'] = {+ getState: async () => (await readWechat()).state,+ getChannelSettings: async () => (await readWechat()).channelSettings,+ // Authorizing opens a browser on the computer that runs WeChat, and the folder chooser is its own.+ authorize: hostOnly,+ chooseWorkingDirectory: hostOnly,+ resetWorkingDirectory: hostOnly,+ async cancelAuthorization() {+ await call2('channels.wechat.cancelAuthorization');+ return { ok: true as const };+ },+ async unbind() {+ await call2('channels.wechat.unbind');+ return { ok: true as const };+ },+ async setCompanion(id) {+ wechatRead = null;+ return (await call2<{ channelSettings: WechatChannelSettingsState }>('channels.wechat.setCompanion', { assign: id !== null })).channelSettings;+ },+ onStateChange: (listener) => pollWhileVisible(async () => (await readWechat()).state, listener),+ onChannelSettingsChange: (listener) => pollWhileVisible(async () => (await readWechat()).channelSettings, listener),+ };const catalogWatchers = new Set<() => void>();+ const routineWatchers = new Set<() => void>();const target: BotSettingsTarget = {kind: 'remote',@@ -251,6 +323,41 @@ export function createRemoteBotSettingsTarget(input: RemoteBotSettingsInput) {return () => void catalogWatchers.delete(refresh);},},+ channels: {+ im: input.ops.has('channels.im.list') ? im : null,+ canEnterCredentials: false,+ wechat: input.ops.has('channels.wechat.get') ? wechat : null,+ x: input.ops.has('channels.x.get')+ ? {+ get: () => call2('channels.x.get'),+ setCompanion: (assign, expectedBotId) => call2('channels.x.setCompanion', { assign, expectedBotId }),+ }+ : null,+ },+ voice: {+ models: () => invokeBotSettings(deviceId, 'voice.models', null),+ voices: (selection) => invokeBotSettings(deviceId, 'voice.voices', null, { selection }),+ preference: (id) => invokeBotSettings(deviceId, 'voice.preference', id),+ setPreference: (id, selection, sentencePlayback) =>+ invokeBotSettings(deviceId, 'voice.setPreference', id, {+ ...(selection !== undefined ? { selection } : {}),+ ...(sentencePlayback !== undefined ? { sentencePlayback } : {}),+ }),+ },+ routines: {+ list: (id) => invokeBotSettings(deviceId, 'routines.list', id),+ save: (id, routine, routineId) => invokeBotSettings(deviceId, 'routines.save', id, { input: routine, ...(routineId ? { id: routineId } : {}) }),+ async remove(id, routineId) {+ await invokeBotSettings(deviceId, 'routines.remove', id, { id: routineId });+ },+ runNow: (id, routineId) => invokeBotSettings(deviceId, 'routines.runNow', id, { id: routineId }),+ history: (id, routineId) => invokeBotSettings(deviceId, 'routines.history', id, { id: routineId }),+ sources: () => invokeBotSettings(deviceId, 'routines.sources', null),+ onChanged(listener) {+ routineWatchers.add(listener);+ return () => void routineWatchers.delete(listener);+ },+ },autonomy: {useSettings() {useEffect(() => {@@ -274,7 +381,12 @@ export function createRemoteBotSettingsTarget(input: RemoteBotSettingsInput) {target,profiles,/** The teammate's computer reported a change: re-read what the open pages show. */- changed() {+ changed(collectionId = 'teammates') {+ // Routines have their own collection on the teammate's computer.+ if (collectionId === 'routines') {+ routineWatchers.forEach((listener) => listener());+ return;+ }void profiles.refresh().catch(() => undefined);if (autonomyListeners.size) void loadAutonomy().catch(() => undefined);if (chainListeners.size) void loadDefaultChain().catch(() => undefined);diff --git a/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsx b/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsxindex c98f35958d..03823ab4fa 100644--- a/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/voice/CompanionVoiceSettings.tsx@@ -31,17 +31,28 @@ import { PcmSpeechPlayer } from './PcmSpeechPlayer';import { VoicePreviewController } from './VoicePreviewController';import { SpeechVoicePicker } from './SpeechVoicePicker';import { resolveVoiceConfiguration } from './voiceConfiguration';+import { useBotSettingsTarget } from '../useBotSettingsTarget';++/** Stands in for the preview service when samples cannot be played from this window. */+const PREVIEW_UNAVAILABLE = {+ preview: () => Promise.reject(new Error('preview_unavailable')),+ readPreview: () => Promise.reject(new Error('preview_unavailable')),+ stopPreview: () => Promise.resolve(),+};type Props = {botId: string;sessionId?: string;beforeLeaveRef?: { current: (() => Promise<boolean>) | null };- onOpenProviders(): void;+ /** Opens this computer's provider settings; absent for a teammate on another computer. */+ onOpenProviders?(): void;};/** Per-companion settings. Opening this page never starts ASR or submits a message. */export function CompanionVoiceSettings(props: Props) {const { t } = useTranslation();+ const target = useBotSettingsTarget();+ const voiceApi = target.voice;const sentencePlaybackId = useId();const session = useSyncExternalStore(useCallback(@@ -95,12 +106,12 @@ export function CompanionVoiceSettings(props: Props) {const preview = useMemo(() =>new VoicePreviewController({- api: window.electronAPI.voiceConversation,+ api: voiceApi.previewApi ?? PREVIEW_UNAVAILABLE,botId: props.botId,sessionId: props.sessionId ?? '',player: () => new PcmSpeechPlayer(() => undefined),}),- [props.botId, props.sessionId],+ [props.botId, props.sessionId, voiceApi],);const refreshVersion = useRef(0);const preferenceVersion = useRef(0);@@ -110,16 +121,15 @@ export function CompanionVoiceSettings(props: Props) {setCatalogError(false);try {// A Gateway refresh failure must not hide usable local BYOK connections.- if (fetchCatalog)- await window.electronAPI.maker.refreshBuiltinProviderModels('xd').catch(() => undefined);- const next = await window.electronAPI.voiceConversation.models();+ if (fetchCatalog) await voiceApi.refreshCatalog?.().catch(() => undefined);+ const next = await voiceApi.models();if (version === refreshVersion.current) setModels(next);} catch {if (version === refreshVersion.current) setCatalogError(true);} finally {if (version === refreshVersion.current) setLoading(false);}- }, []);+ }, [voiceApi]);const loadPreference = useCallback(() => {const version = ++preferenceVersion.current;@@ -134,7 +144,7 @@ export function CompanionVoiceSettings(props: Props) {setSaving(false);dirty.current = false;pendingSave.current = null;- void window.electronAPI.voiceConversation+ void voiceApi.preference(props.botId).then((result) => {if (version !== preferenceVersion.current) return;@@ -146,7 +156,7 @@ export function CompanionVoiceSettings(props: Props) {.catch(() => {if (version === preferenceVersion.current) setPreferenceError(true);});- }, [props.botId]);+ }, [props.botId, voiceApi]);useEffect(() => {void refresh();@@ -193,7 +203,7 @@ export function CompanionVoiceSettings(props: Props) {const version = preferenceVersion.current;setSaving(true);setPreferenceError(false);- const api = window.electronAPI.voiceConversation;+ const api = voiceApi;const operation =playback === undefined? api.setPreference(props.botId, next)@@ -226,7 +236,7 @@ export function CompanionVoiceSettings(props: Props) {pendingSave.current = pending;return pending;},- [props.botId],+ [props.botId, voiceApi],);useEffect(() => {const ref = props.beforeLeaveRef;@@ -310,9 +320,15 @@ export function CompanionVoiceSettings(props: Props) {<p className="text-12 leading-relaxed text-[var(--text-secondary)]">{t('bots.voiceMode.noModelsSetupHint')}</p>- <Button variant="secondary" size="sm" compact onClick={props.onOpenProviders}>- {t('bots.voiceMode.openProviders')}- </Button>+ {props.onOpenProviders ? (+ <Button variant="secondary" size="sm" compact onClick={props.onOpenProviders}>+ {t('bots.voiceMode.openProviders')}+ </Button>+ ) : (+ <p className="text-12 leading-relaxed text-[var(--text-secondary)]">+ {t('bots.remoteSettings.finishOnHost', { device: target.deviceName })}+ </p>+ )}</div>)}</div>@@ -425,7 +441,7 @@ export function CompanionVoiceSettings(props: Props) {voice={selectedVoice}speed={effectiveSpeed}disabled={!ready || saving || blocked}- previewDisabled={!ready || saving || blocked || !props.sessionId}+ previewDisabled={!ready || saving || blocked || !props.sessionId || !voiceApi.previewApi}preview={preview}onChange={(value, save) => {dirty.current = true;@@ -499,7 +515,12 @@ export function CompanionVoiceSettings(props: Props) {{t('bots.voiceMode.incompleteSettings')}</p>) : null}- {!props.sessionId ? (+ {!voiceApi.previewApi ? (+ // Samples play through the speakers of the computer the page runs on.+ <p className="text-12 text-[var(--text-secondary)]">+ {t('bots.remoteSettings.finishOnHost', { device: target.deviceName })}+ </p>+ ) : !props.sessionId ? (<p className="text-12 text-[var(--text-secondary)]">{t('bots.voiceMode.previewNeedsChat')}</p>diff --git a/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx b/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsxindex f75b97e92b..5c0626191d 100644--- a/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx+++ b/apps/desktop/src/renderer/features/bots/voice/SpeechVoicePicker.tsx@@ -18,6 +18,7 @@ import {import type { VoicePreviewController } from './VoicePreviewController';import { readSpeechVoiceLabel, rememberSpeechVoiceLabel } from './speechVoiceLabelCache';import { SpeechVoiceMenu } from './SpeechVoiceMenu';+import { useBotSettingsTarget } from '../useBotSettingsTarget';const MANUAL = 'manual';const LOADING = 'loading';@@ -52,6 +53,7 @@ export function SpeechVoicePicker({onChange,}: Props) {const { t } = useTranslation();+ const voiceApi = useBotSettingsTarget().voice;const [catalogState, setCatalogState] = useState<CatalogState>();const [revision, setRevision] = useState(0);const [manualRouteKey, setManualRouteKey] = useState<string>();@@ -130,7 +132,7 @@ export function SpeechVoicePicker({catalog: protocol && current?.routeKey === routeKey ? current.catalog : undefined,}));if (protocol) {- void window.electronAPI.voiceConversation+ void voiceApi.voices(route).then((result) => {if (version.current === request && isDataOwnerGenerationCurrent(owner))diff --git a/apps/desktop/src/renderer/hooks/useWechatBot.ts b/apps/desktop/src/renderer/hooks/useWechatBot.tsindex 0dd2715bcc..23fcbe88c2 100644--- a/apps/desktop/src/renderer/hooks/useWechatBot.ts+++ b/apps/desktop/src/renderer/hooks/useWechatBot.ts@@ -32,8 +32,15 @@ export interface UseWechatBotReturn {isUpdatingCompanion: boolean;}-export function useWechatBot(): UseWechatBotReturn {+type WechatBotApi = Window['electronAPI']['wechatBot'];++/**+ * `override` serves personal WeChat of another computer (a teammate's settings on a remote Desktop). Its+ * state is that computer's, so it neither reads nor writes the module caches of this window's own.+ */+export function useWechatBot(override?: WechatBotApi): UseWechatBotReturn {const { t } = useTranslation();+ const api = override ?? window.electronAPI.wechatBot;const [owner] = useState(getDataOwnerGeneration);// ProtectedRoute remounts on owner changes; module caches survive that remount.if (cacheOwnerId !== getDataOwnerGeneration().dataOwnerId) {@@ -41,9 +48,9 @@ export function useWechatBot(): UseWechatBotReturn {cachedState = null;cachedChannelSettings = null;}- const [state, setState] = useState<WechatBotState>(() => cachedState ?? EMPTY_STATE);+ const [state, setState] = useState<WechatBotState>(() => (override ? null : cachedState) ?? EMPTY_STATE);const [channelSettings, setChannelSettings] = useState<WechatChannelSettingsState | null>(- () => cachedChannelSettings,+ () => (override ? null : cachedChannelSettings),);const [isAuthorizing, setIsAuthorizing] = useState(false);const [isUnbinding, setIsUnbinding] = useState(false);@@ -55,34 +62,34 @@ export function useWechatBot(): UseWechatBotReturn {useEffect(() => {let cancelled = false;- const unsubscribe = window.electronAPI.wechatBot.onStateChange((next) => {+ const unsubscribe = api.onStateChange((next) => {if (cancelled || !isDataOwnerIdCurrent(owner)) return;pushVersionRef.current += 1;- cachedState = next;+ if (!override) cachedState = next;setState(next);});- const unsubscribeSettings = window.electronAPI.wechatBot.onChannelSettingsChange?.((settings) => {+ const unsubscribeSettings = api.onChannelSettingsChange?.((settings) => {if (cancelled || !isDataOwnerIdCurrent(owner)) return;settingsVersionRef.current += 1;- cachedChannelSettings = settings;+ if (!override) cachedChannelSettings = settings;setChannelSettings(settings);});const initialPushVersion = pushVersionRef.current;const initialSettingsVersion = settingsVersionRef.current;const requestOwner = getDataOwnerGeneration();void Promise.all([- window.electronAPI.wechatBot.getState(),- window.electronAPI.wechatBot.getChannelSettings(),+ api.getState(),+ api.getChannelSettings(),]).then(([nextState, nextChannelSettings]) => {// Same-owner repair keeps this page mounted and these read-only settings valid.if (cancelled || !isDataOwnerIdCurrent(requestOwner)) return;if (pushVersionRef.current === initialPushVersion) {- cachedState = nextState;+ if (!override) cachedState = nextState;setState(nextState);}if (settingsVersionRef.current === initialSettingsVersion) {- cachedChannelSettings = nextChannelSettings;+ if (!override) cachedChannelSettings = nextChannelSettings;setChannelSettings(nextChannelSettings);}})@@ -95,13 +102,13 @@ export function useWechatBot(): UseWechatBotReturn {unsubscribe();unsubscribeSettings?.();};- }, [owner]);+ }, [owner, api, override]);const authorize = useCallback(async (): Promise<boolean> => {if (isAuthorizing) return false;setIsAuthorizing(true);try {- await window.electronAPI.wechatBot.authorize();+ await api.authorize();return true;} catch {log.error('failed to start personal WeChat authorization');@@ -110,22 +117,22 @@ export function useWechatBot(): UseWechatBotReturn {} finally {setIsAuthorizing(false);}- }, [isAuthorizing, t]);+ }, [api, isAuthorizing, t]);const cancelAuthorization = useCallback(async (): Promise<void> => {try {- await window.electronAPI.wechatBot.cancelAuthorization();+ await api.cancelAuthorization();} catch {log.error('failed to cancel personal WeChat authorization');toast.error(t('settings.wechatBot.toasts.cancelFailed'));}- }, [t]);+ }, [api, t]);const unbind = useCallback(async (): Promise<boolean> => {if (isUnbinding) return false;setIsUnbinding(true);try {- await window.electronAPI.wechatBot.unbind();+ await api.unbind();toast.success(t('settings.wechatBot.toasts.unbound'));return true;} catch {@@ -135,16 +142,16 @@ export function useWechatBot(): UseWechatBotReturn {} finally {setIsUnbinding(false);}- }, [isUnbinding, t]);+ }, [api, isUnbinding, t]);const chooseWorkingDirectory = useCallback(async (): Promise<void> => {if (isUpdatingWorkingDir || !isDataOwnerIdCurrent(owner)) return;const requestOwner = getDataOwnerGeneration();setIsUpdatingWorkingDir(true);try {- const result = await window.electronAPI.wechatBot.chooseWorkingDirectory();+ const result = await api.chooseWorkingDirectory();if (!isDataOwnerGenerationCurrent(requestOwner)) return;- cachedChannelSettings = result.state;+ if (!override) cachedChannelSettings = result.state;setChannelSettings(result.state);if (!result.canceled) toast.success(t('settings.wechatBot.toasts.workingDirSaved'));} catch {@@ -153,16 +160,16 @@ export function useWechatBot(): UseWechatBotReturn {} finally {setIsUpdatingWorkingDir(false);}- }, [isUpdatingWorkingDir, owner, t]);+ }, [api, override, isUpdatingWorkingDir, owner, t]);const resetWorkingDirectory = useCallback(async (): Promise<void> => {if (isUpdatingWorkingDir || !isDataOwnerIdCurrent(owner)) return;const requestOwner = getDataOwnerGeneration();setIsUpdatingWorkingDir(true);try {- const next = await window.electronAPI.wechatBot.resetWorkingDirectory();+ const next = await api.resetWorkingDirectory();if (!isDataOwnerGenerationCurrent(requestOwner)) return;- cachedChannelSettings = next;+ if (!override) cachedChannelSettings = next;setChannelSettings(next);toast.success(t('settings.wechatBot.toasts.workingDirReset'));} catch {@@ -171,7 +178,7 @@ export function useWechatBot(): UseWechatBotReturn {} finally {setIsUpdatingWorkingDir(false);}- }, [isUpdatingWorkingDir, owner, t]);+ }, [api, override, isUpdatingWorkingDir, owner, t]);const setCompanion = useCallback(async (botId: string | null): Promise<boolean> => {if (companionBusyRef.current || !channelSettings || !isDataOwnerIdCurrent(owner)) return false;@@ -179,10 +186,10 @@ export function useWechatBot(): UseWechatBotReturn {companionBusyRef.current = true;setIsUpdatingCompanion(true);try {- const next = await window.electronAPI.wechatBot.setCompanion(botId);+ const next = await api.setCompanion(botId);if (!isDataOwnerGenerationCurrent(requestOwner)) return false;settingsVersionRef.current += 1;- cachedChannelSettings = next;+ if (!override) cachedChannelSettings = next;setChannelSettings(next);return true;} catch {@@ -192,7 +199,7 @@ export function useWechatBot(): UseWechatBotReturn {companionBusyRef.current = false;setIsUpdatingCompanion(false);}- }, [channelSettings, owner, t]);+ }, [api, override, channelSettings, owner, t]);return {state,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex e5e321e289..b624cefba6 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9075,7 +9075,8 @@"conflict": "Settings changed on the other device. Reload before saving.","unsupported": "Update Cindy on the other device to edit these settings.","discardDescription": "Reloading will discard these unsaved settings.",- "leaveDescription": "Leaving will discard these unsaved settings."+ "leaveDescription": "Leaving will discard these unsaved settings.",+ "finishOnHost": "Finish this on {{device}}."},"devicePicker": {"local": "This Device",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex c634b6c660..46c10de2d3 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9041,7 +9041,8 @@"conflict": "別のデバイスで設定が変更されました。保存する前に再読み込みしてください。","unsupported": "これらの設定を編集するには、別のデバイスの Cindy を更新してください。","discardDescription": "再読み込みすると、未保存の設定が破棄されます。",- "leaveDescription": "移動すると、未保存の設定が破棄されます。"+ "leaveDescription": "移動すると、未保存の設定が破棄されます。",+ "finishOnHost": "{{device}} で操作してください。"},"devicePicker": {"local": "この端末",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 66f9c9d783..14da68ff49 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9041,7 +9041,8 @@"conflict": "다른 기기에서 설정이 변경되었습니다. 저장하기 전에 다시 불러오세요.","unsupported": "이 설정을 편집하려면 다른 기기의 Cindy를 업데이트하세요.","discardDescription": "다시 불러오면 저장하지 않은 설정이 삭제됩니다.",- "leaveDescription": "나가면 저장하지 않은 설정이 삭제됩니다."+ "leaveDescription": "나가면 저장하지 않은 설정이 삭제됩니다.",+ "finishOnHost": "{{device}}에서 진행하세요."},"devicePicker": {"local": "이 기기",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 0f0fe7389c..8b32e2eb9b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9041,7 +9041,8 @@"conflict": "设置已在另一台设备上更改,请重新读取后再保存。","unsupported": "请更新另一台设备上的 Cindy 以编辑这些设置。","discardDescription": "重新读取将放弃尚未保存的设置。",- "leaveDescription": "离开后会放弃尚未保存的设置。"+ "leaveDescription": "离开后会放弃尚未保存的设置。",+ "finishOnHost": "请在「{{device}}」上完成。"},"devicePicker": {"local": "本机",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex d6cdcbde1a..72f672f49f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9041,7 +9041,8 @@"conflict": "設定已在另一台裝置上變更,請重新讀取後再儲存。","unsupported": "請更新另一台裝置上的 Cindy 以編輯這些設定。","discardDescription": "重新讀取將放棄尚未儲存的設定。",- "leaveDescription": "離開後會放棄尚未儲存的設定。"+ "leaveDescription": "離開後會放棄尚未儲存的設定。",+ "finishOnHost": "請在「{{device}}」上完成。"},"devicePicker": {"local": "本機",diff --git a/apps/desktop/src/shared/botRemoteSettings.ts b/apps/desktop/src/shared/botRemoteSettings.tsindex e8f41f8ba5..1028a69383 100644--- a/apps/desktop/src/shared/botRemoteSettings.ts+++ b/apps/desktop/src/shared/botRemoteSettings.ts@@ -34,6 +34,30 @@ export const BOT_SETTINGS_OPS = ['autonomy.set','autonomy.reset','history.search',+ 'routines.list',+ 'routines.sources',+ 'routines.history',+ 'routines.save',+ 'routines.runNow',+ 'routines.remove',+ 'voice.models',+ 'voice.voices',+ 'voice.preference',+ 'voice.setPreference',+ 'channels.im.list',+ 'channels.im.remove',+ 'channels.im.listGroups',+ 'channels.im.setGroupActivation',+ 'channels.im.listLanes',+ 'channels.im.resetLane',+ 'channels.im.listAdoptable',+ 'channels.im.adopt',+ 'channels.wechat.get',+ 'channels.wechat.setCompanion',+ 'channels.wechat.unbind',+ 'channels.wechat.cancelAuthorization',+ 'channels.x.get',+ 'channels.x.setCompanion',] as const;export type BotSettingsOp = (typeof BOT_SETTINGS_OPS)[number];@@ -44,6 +68,10 @@ export const BOT_SETTINGS_HOST_OPS: readonly BotSettingsOp[] = ['autonomy.get','autonomy.set','autonomy.reset',+ 'routines.sources',+ 'voice.models',+ 'voice.voices',+ 'channels.im.listAdoptable',];export interface BotSettingsCaps {