Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): reconcile live capabilities and runtime availability
zqchrisf17a3da67184
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex c203245d22..3362289287 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -55,6 +55,7 @@ const h = await vi.hoisted(async () => {searchConversations: vi.fn(),requestRuntimeRefresh: vi.fn(),seedTemplateSkills: vi.fn(async () => ({ completedNow: true, skills: [] })),+ toolsetsAvailable: false,ownerScopeKey: 'owner-a:1',ownerBoundaryPending: false,});@@ -98,7 +99,11 @@ vi.mock('../../../maker-host/custom-mcp-store.js', () => ({}));vi.mock('../../../maker-host/index.js', () => ({getMaker: () => ({ getSession: h.getSession, listAgentSkills: async () => ({ skills: [{ name: 'release-check', description: 'Release checklist', enabled: true }] }) }),- getPluginRegistry: () => ({ getPlugins: () => [], getEnableState: async () => ({ effectiveEnabled: true }) }),+ getPluginRegistry: () => ({+ getPlugins: () => ['contacts', 'lsp'].map((id) => ({ id, name: id, description: id })),+ getEnableState: async () => ({ effectiveEnabled: true }),+ }),+ isBotToolsetAvailable: () => h.toolsetsAvailable,getMakerIfReady: () => ({isSessionAlive: h.isSessionAlive,closeSession: h.closeSession,@@ -394,6 +399,7 @@ async function invoke(channel: string, body: unknown): Promise<any> {return handler({}, body);}beforeEach(async () => {+ h.toolsetsAvailable = false;vi.clearAllMocks();h.handlers.clear();h.nextSession = 0;@@ -1608,6 +1614,19 @@ describe('Bot canonical Session lifecycle', () => {await expect(findBotCapabilities({ callerSessionId, kind: 'skill' })).resolves.toMatchObject({ capabilities: [{ id: 'release-check', joined: true }] });});+ it.each(['contacts', 'lsp'])('rejects gated %s despite registry enablement and keeps joined references removable', async (id) => {+ const created = await invoke('local-db:bots:create-canonical-session', { botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1 });+ const input = { callerSessionId: created.session.id, kind: 'toolset' as const, id };+ await expect(findBotCapabilities(input)).resolves.toMatchObject({+ ok: true, capabilities: expect.arrayContaining([{ id, name: id, description: id, available: false, joined: false }]),+ });+ await expect(selectBotCapability({ ...input, joined: true })).resolves.toMatchObject({ ok: false, errorCode: 'CAPABILITY_UNAVAILABLE' });+ h.toolsetsAvailable = true;+ await expect(selectBotCapability({ ...input, joined: true })).resolves.toMatchObject({ ok: true });+ h.toolsetsAvailable = false;+ await expect(selectBotCapability({ ...input, joined: false })).resolves.toMatchObject({ ok: true, joined: false });+ });+it('refuses absent capabilities and callers without an active canonical Bot', async () => {const created = await invoke('local-db:bots:create-canonical-session', { botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1 });await expect(selectBotCapability({ callerSessionId: created.session.id, kind: 'mcp', id: 'missing', joined: true })).resolves.toMatchObject({ ok: false, errorCode: 'CAPABILITY_UNAVAILABLE' });diff --git a/apps/desktop/src/main/maker-host/__tests__/botToolsetAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/botToolsetAvailability.test.tsnew file mode 100644index 0000000000..a8497fc799--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/botToolsetAvailability.test.ts@@ -0,0 +1,64 @@+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';+import { createLiziMcpProviders } from '@cindy/mcps';+import { isBotToolsetProviderAvailable } from '../botToolsetAvailability';++const root = mkdtempSync(join(tmpdir(), 'cindy-bot-toolsets-'));+const tsDir = join(root, 'typescript');+const plainDir = join(root, 'plain');+mkdirSync(tsDir);+mkdirSync(plainDir);+writeFileSync(join(tsDir, 'tsconfig.json'), '{}');+afterAll(() => rmSync(root, { recursive: true, force: true }));+afterEach(() => vi.unstubAllEnvs());++describe('Bot toolset provider availability', () => {+ it('follows the real Contacts and LSP gates rather than registry enablement', () => {+ let contactsEnabled = false;+ let lspEnabled = false;+ const providers = createLiziMcpProviders({+ enabled: ['cindy_contacts', 'cindy_lsp', 'cindy_memory'],+ contacts: { getManager: vi.fn(), isEnabled: () => contactsEnabled },+ lsp: { pool: {} as never, isUserEnabled: () => lspEnabled },+ memory: { getManager: () => ({ isEnabled: () => false }) as never },+ });+ const available = (toolsetId: string, workingDir = tsDir) =>+ isBotToolsetProviderAvailable(providers, { botId: 'bot-1', agentKind: 'claude-code', workingDir, toolsetId });+ expect(available('contacts')).toBe(false);+ contactsEnabled = true;+ expect(available('contacts')).toBe(true);+ contactsEnabled = false;+ expect(available('contacts')).toBe(false);+ expect(available('lsp')).toBe(false);+ lspEnabled = true;+ expect(available('lsp', plainDir)).toBe(false);+ expect(available('lsp')).toBe(true);+ for (const agentKind of ['codex', 'pi'] as const) {+ expect(isBotToolsetProviderAvailable(providers, {+ botId: 'bot-1', agentKind, workingDir: tsDir, toolsetId: 'lsp',+ })).toBe(false); // The real provider rejects the shared bridge's empty workdir.+ expect(isBotToolsetProviderAvailable(providers, {+ botId: 'bot-1', agentKind, workingDir: tsDir, toolsetId: 'memory',+ })).toBe(true);+ }+ vi.stubEnv('LIZI_LSP_DISABLED', '1');+ expect(available('lsp')).toBe(false);+ expect(available('memory')).toBe(true); // Bot Memory is independent of global Memory.+ expect(available('missing')).toBe(false);+ });++ it('keeps target restrictions and never uses custom MCP collisions to bypass a builtin gate', () => {+ const providers = [+ { name: 'cindy_contacts', isEnabled: () => false },+ { name: 'cindy_contacts', isEnabled: () => true },+ { name: 'cindy_docs', isEnabled: () => true },+ ];+ const input = { botId: 'bot-1', agentKind: 'claude-code' as const, workingDir: plainDir };+ expect(isBotToolsetProviderAvailable(providers, { ...input, toolsetId: 'contacts' })).toBe(false);+ expect(isBotToolsetProviderAvailable(providers, { ...input, toolsetId: 'docs' })).toBe(true);+ expect(isBotToolsetProviderAvailable(providers, { ...input, toolsetId: 'docs', remoteHostId: 'ssh' })).toBe(false);+ expect(isBotToolsetProviderAvailable(providers, { ...input, agentKind: 'pi', toolsetId: 'docs', remoteHostId: 'ssh' })).toBe(true);+ });+});diff --git a/apps/desktop/src/main/maker-host/botToolsetAvailability.ts b/apps/desktop/src/main/maker-host/botToolsetAvailability.tsnew file mode 100644index 0000000000..aaecd0f866--- /dev/null+++ b/apps/desktop/src/main/maker-host/botToolsetAvailability.ts@@ -0,0 +1,26 @@+import { buildBotMemoryScopeKey, type McpProvider } from '@cindy/maker-core';+import { isBotToolsetAvailableOnTarget, type BotToolsetContext } from '../../shared/botRemoteCapabilities.js';+import { pluginIdForKnownProviderName } from './plugins/builtin-plugins.js';++/** Query the mounted provider gates without creating servers or changing global settings. */+export function isBotToolsetProviderAvailable(+ providers: readonly McpProvider[],+ input: BotToolsetContext & { toolsetId: string },+): boolean {+ if (!isBotToolsetAvailableOnTarget(input)) return false;+ // Do not use the current runtime's frozen allowlist: discovery must also+ // include capabilities this Bot can join for its next turn.+ const context = {+ agentKind: input.agentKind,+ workingDir: input.workingDir,+ remoteHostId: input.remoteHostId ?? undefined,+ memoryScopeKey: buildBotMemoryScopeKey(input.botId),+ };+ const provider = providers.find((entry) =>+ pluginIdForKnownProviderName(entry.name) === input.toolsetId);+ if (!provider || provider.isEnabled?.(context) === false) return false;+ // Codex/Pi register factories on a shared bridge before a workdir exists.+ // A provider rejected there cannot be mounted even if its per-Bot gate passes.+ return input.agentKind === 'claude-code'+ || (provider.isEnabled?.({ agentKind: input.agentKind, workingDir: '' }) ?? true);+}diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 1a627dc88d..f1d157d956 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -243,7 +243,8 @@ import {} from '../mcp-integrations/codexEnvironment.js';import type { CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.js';import { setRemoteMcpBridgeTokenRotatedHook } from '../mcp-integrations/remoteMcpBridgeToken.js';-import { isBotToolsetAvailableOnTarget } from '../../shared/botRemoteCapabilities.js';+import type { BotToolsetContext } from '../../shared/botRemoteCapabilities.js';+import { isBotToolsetProviderAvailable } from './botToolsetAvailability.js';import {ensureRemoteMcpForward,setRemoteMcpForwardRearmedHook,@@ -716,6 +717,11 @@ function getLspPool(): LspServerPool {return lspPool;}+/** Same Desktop provider instances used by the runtimes, evaluated for this Bot. */+export function isBotToolsetAvailable(input: BotToolsetContext & { toolsetId: string }): boolean {+ return isBotToolsetProviderAvailable(_codexMcpProviders ?? [], input);+}+/** Get the plugin registry singleton (delegates to plugins/index.ts module-level cache). */export function getPluginRegistry() {return createPluginRegistry();@@ -2314,7 +2320,7 @@ export function getMaker(): Maker {]),).values()];},- listToolsets: async ({ agentKind, workingDir, remoteHostId }) => {+ listToolsets: async ({ botId, agentKind, workingDir, remoteHostId }) => {const registry = getPluginRegistry();return Promise.all(registry.getPlugins().map(async (plugin) => {@@ -2325,7 +2331,9 @@ export function getMaker(): Maker {essential: ESSENTIAL_PLUGIN_IDS.has(plugin.id),available:state.effectiveEnabled &&- isBotToolsetAvailableOnTarget({+ isBotToolsetAvailable({+ botId,+ workingDir,agentKind,remoteHostId,toolsetId: plugin.id,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginListHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginListHandler.test.tsnew file mode 100644index 0000000000..99abc336f2--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginListHandler.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest';+import { registerPluginListHandler } from '../pluginListHandler';+import { MAKER_INVOKE } from '../channels';+import { IpcHarness } from './helpers/ipcHarness';++function setup() {+ const items = ['contacts', 'lsp', 'docs'].map((id) => ({+ id, name: id, description: id, source: 'builtin' as const,+ essential: id === 'lsp', effectiveEnabled: true, productDefaultEnabled: true,+ }));+ const listPlugins = vi.fn(async () => items);+ const isBotToolsetAvailable = vi.fn(({ toolsetId }: { toolsetId: string }) => toolsetId === 'docs');+ const assertBotQuery = vi.fn();+ const ipc = new IpcHarness();+ registerPluginListHandler(ipc, { getPluginRegistry: () => ({ listPlugins }), isBotToolsetAvailable, assertBotQuery });+ return { ipc, items, listPlugins, isBotToolsetAvailable, assertBotQuery };+}++describe('Bot-aware plugin catalog IPC', () => {+ it('adds provider availability without changing existing registry fields or legacy queries', async () => {+ const h = setup();+ await expect(h.ipc.invoke(MAKER_INVOKE.PLUGINS_LIST, '/workspace', true)).resolves.toEqual(h.items);+ expect(h.isBotToolsetAvailable).not.toHaveBeenCalled();+ const context = { botId: 'bot-1', agentKind: 'pi', remoteHostId: 'ssh-1' };+ await expect(h.ipc.invoke(MAKER_INVOKE.PLUGINS_LIST, '/workspace', true, context)).resolves.toEqual(+ h.items.map((item) => ({ ...item, available: item.id === 'docs' })),+ );+ expect(h.assertBotQuery).toHaveBeenCalledTimes(1);+ expect(h.isBotToolsetAvailable).toHaveBeenCalledWith({ ...context, workingDir: '/workspace', toolsetId: 'lsp' });+ h.items[2].effectiveEnabled = false;+ await expect(h.ipc.invoke(MAKER_INVOKE.PLUGINS_LIST, '/workspace', true, context)).resolves.toEqual(+ h.items.map((item) => ({ ...item, available: false })),+ );+ });++ it('rejects invalid context and untrusted requests before running provider predicates', async () => {+ const h = setup();+ await expect(h.ipc.invoke(MAKER_INVOKE.PLUGINS_LIST, '', true, { botId: 'bot-1', agentKind: 'unknown' })).rejects.toThrow('INVALID_PARAMS');+ h.assertBotQuery.mockImplementation(() => { throw new Error('untrusted'); });+ await expect(h.ipc.invoke(MAKER_INVOKE.PLUGINS_LIST, '', true, { botId: 'bot-1', agentKind: 'pi' })).rejects.toThrow('untrusted');+ expect(h.isBotToolsetAvailable).not.toHaveBeenCalled();+ expect(h.listPlugins).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.tsindex 31cfa8b24c..fb277b074c 100644--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts@@ -4,7 +4,6 @@ import { getDbClient } from '../localDb/client/current.js';import { updateBotProfile } from '../localDb/ipc/bots.js';import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';import { listCustomMcpServers } from '../maker-host/custom-mcp-store.js';-import { isBotToolsetAvailableOnTarget } from '../../shared/botRemoteCapabilities.js';type Kind = 'skill' | 'mcp' | 'toolset';type Input = { callerSessionId: string; kind: Kind };@@ -75,7 +74,7 @@ async function context(callerSessionId: string) {async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>): Promise<Entry[]> {const joined = new Set(strings(ctx.config[fields[input.kind].list]));- const { getMaker, getPluginRegistry } = await import('../maker-host/index.js');+ const { getMaker, getPluginRegistry, isBotToolsetAvailable } = await import('../maker-host/index.js');const agentKind =getMaker().getSession(input.callerSessionId)?.agentKind ??(ctx.agentKind === 'cc' ? 'claude-code' : ctx.agentKind === 'pi' ? 'pi' : 'codex');@@ -112,7 +111,9 @@ async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>):description: plugin.description,available:(await registry.getEnableState(plugin.id, workingDir)).effectiveEnabled &&- isBotToolsetAvailableOnTarget({+ isBotToolsetAvailable({+ botId: ctx.botId,+ workingDir,agentKind,remoteHostId: ctx.remoteHostId,toolsetId: plugin.id,diff --git a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts b/apps/desktop/src/main/maker-ipc/botProfileRuntime.tsindex 21cf17e436..04edcc6dc1 100644--- a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts+++ b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts@@ -100,6 +100,7 @@ export interface BotProfileRuntimeDeps {remoteHostId?: string;}) => Promise<BotMcpCatalogItem[]>;listToolsets?: (input: {+ botId: string;agentKind: MakerSessionCreateOpts['agentKind'];workingDir: string;remoteHostId?: string;@@ -759,6 +760,7 @@ export async function hydrateBotProfileRuntime(runtimeToolsetMode = 'allowlist';try {toolsetCatalog = await deps.listToolsets({+ botId: row.botId,agentKind: opts.agentKind,workingDir: opts.workingDir,remoteHostId: opts.remoteHostId,diff --git a/apps/desktop/src/main/maker-ipc/pluginListHandler.ts b/apps/desktop/src/main/maker-ipc/pluginListHandler.tsnew file mode 100644index 0000000000..a769c3c394--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/pluginListHandler.ts@@ -0,0 +1,34 @@+import { z } from 'zod';+import type { BotToolsetContext } from '../../shared/botRemoteCapabilities.js';+import type { PluginRegistry } from '../maker-host/plugins/plugin-registry.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { MAKER_INVOKE } from './channels.js';+import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';++const botContextSchema = z.object({+ botId: z.string().min(1),+ agentKind: z.enum(['claude-code', 'codex', 'pi']),+ remoteHostId: z.string().nullish(),+});++/** Preserve the settings catalog, adding actual mount availability only for Bot queries. */+export function registerPluginListHandler(registry: IpcHandlerRegistry, deps: {+ getPluginRegistry: () => Pick<PluginRegistry, 'listPlugins'>;+ isBotToolsetAvailable: (input: BotToolsetContext & { toolsetId: string }) => boolean;+ assertBotQuery: (event: unknown) => void;+}): void {+ registry.handle(MAKER_INVOKE.PLUGINS_LIST, async (event, workingDir, includeHidden, botContext) => {+ const wd = typeof workingDir === 'string' ? workingDir : undefined;+ if (botContext === undefined) return deps.getPluginRegistry().listPlugins(wd, includeHidden === true);+ deps.assertBotQuery(event);+ const parsed = botContextSchema.safeParse(botContext);+ if (!parsed.success) throwIpcError('INVALID_PARAMS', 'Invalid Bot toolset context');+ const items = await deps.getPluginRegistry().listPlugins(wd, includeHidden === true);+ return items.map((item) => ({+ ...item,+ available: item.effectiveEnabled && deps.isBotToolsetAvailable({+ ...parsed.data, workingDir: wd ?? '', toolsetId: item.id,+ }),+ }));+ });+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex e3bdf2c9bd..e8e4c37f99 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,3 +1,4 @@+import { registerPluginListHandler } from './pluginListHandler.js';import { projectRemoteBotDelegations } from './remoteBotDelegations.js';/*** registerMakerIpc — 把 Maker Core 的能力暴露为 maker:* IPC channel。@@ -409,6 +410,7 @@ import {getMaker,getMakerIfReady,getPluginRegistry,+ isBotToolsetAvailable,preflightBotRuntimeResources,prepareCodexForAuthModeChange,prepareCodexForCustomProviderHostChange,@@ -16834,9 +16836,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});// ── Plugin system (Phase 1) ──────────────────────────────────────────────- ipcMain.handle(MAKER_INVOKE.PLUGINS_LIST, async (_e, workingDir: unknown, includeHidden: unknown) => {- const wd = typeof workingDir === 'string' ? workingDir : undefined;- return getPluginRegistry().listPlugins(wd, includeHidden === true);+ registerPluginListHandler(createElectronIpcHandlerRegistry(), {+ getPluginRegistry,+ isBotToolsetAvailable,+ assertBotQuery: (event) => {+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);+ },});// Read one plugin's enable state by id. Unlike PLUGINS_LIST this does NOT skipdiff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex b847ce48df..96d7970ff0 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1,3 +1,4 @@+import type { BotToolsetContext } from '../shared/botRemoteCapabilities';import { contextBridge, ipcRenderer, webUtils } from 'electron';import { DEVICE_LINK_PUSH } from '../shared/deviceLinkIpc';import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';@@ -820,6 +821,8 @@ interface CrossAgentMigrationItem {}interface PluginListItem {+ /** Present only when queried for a Bot runtime context. */+ available?: boolean;id: string;name: string;description: string;@@ -7189,8 +7192,8 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── Plugin system (Phase 1) ──────────────────────────────────────────plugins: {- list: (workingDir?: string, includeHidden?: boolean): Promise<PluginListItem[]> =>- ipcRenderer.invoke('maker:plugins:list', workingDir, includeHidden),+ list: (workingDir?: string, includeHidden?: boolean, botContext?: Omit<BotToolsetContext, 'workingDir'>): Promise<PluginListItem[]> =>+ ipcRenderer.invoke('maker:plugins:list', workingDir, includeHidden, botContext),getState: (id: string,workingDir?: string,diff --git a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsxindex 24b02203fe..4a157bb87a 100644--- a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx+++ b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx@@ -2,7 +2,6 @@ import { useState } from 'react';import { useBotTranslation } from './botPronounContext';import type { BotCapabilities, BotProfile } from './botStore';import * as sessionService from '@/lib/sessionService';-import { isBotToolsetAvailableOnTarget } from '../../../shared/botRemoteCapabilities';import {getDataOwnerGeneration,isDataOwnerGenerationCurrent,@@ -47,7 +46,9 @@ export function BotCapabilitySettings({remoteHostId: session.remoteHostId ?? undefined,}),api.listCustomMcpServers(),- api.plugins.list(session.workingDir ?? undefined, true),+ api.plugins.list(session.workingDir ?? undefined, true, {+ botId: bot.id, agentKind, remoteHostId: session.remoteHostId,+ }),]);if (!isDataOwnerGenerationCurrent(owner)) return;const [skillResult, mcpResult, toolsetResult] = results;@@ -70,9 +71,7 @@ export function BotCapabilitySettings({.map((item) => ({id: item.id,name: item.name,- available: item.effectiveEnabled && isBotToolsetAvailableOnTarget({- agentKind, remoteHostId: session.remoteHostId, toolsetId: item.id,- }),+ available: item.available === true,}));setEntries(next);setError(kinds.some((kind) => !next[kind]));diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsxindex 95635399c2..fb791ec958 100644--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx@@ -32,7 +32,7 @@ import { BotLifecycleSettings } from './BotLifecycleSettings';import { BotInvitationWelcome } from './BotInvitationWelcome';import { BotModelChainEditor } from './BotModelChainEditor';import { BotCapabilitySettings } from './BotCapabilitySettings';-import { botSettingsChanges, normalizeBotSettingsPayload, type BotSettingsPayload } from './botSettingsAutosave';+import { botSettingsChanges, normalizeBotSettingsPayload, reconcileBotSettingsDraft, type BotSettingsPayload } from './botSettingsAutosave';import { useBotSettingsAutosave } from './useBotSettingsAutosave';const DAY_MS = 24 * 60 * 60 * 1_000;@@ -86,31 +86,19 @@ export function BotSettings({if (!availableAgentsLoaded) return [];return (['cc', 'codex', 'pi'] as const).filter((item) => !availableVendors.has(item));}, [availableAgentsLoaded, availableVendors]);- // 只在切到另一个 Bot 时重灌表单。自动保存下 `bot` 每次落库(以及失败回滚)都会- // 换一个新对象,若仍按对象身份重灌,用户在提交在途期间敲的字会被服务端快照盖掉,- // 失败回滚时更会把刚改的内容整批还原 —— 那是比「忘记点保存」更严重的丢字。- // 页面挂载期间本地 state 才是编辑权威;`bot.channels` / `bot.sessions` 等非表单- // 字段仍直接读 prop,保持实时。const botIdentityRef = useRef(bot.id);- useEffect(() => {- if (botIdentityRef.current === bot.id) return;- botIdentityRef.current = bot.id;- setName(bot.name);- setDescription(bot.description);- setIdentitySource(bot.identitySource ?? '');- setUserContextSource(bot.userContextSource ?? '');- setAvatar(bot.avatar);- setAvatarColor(bot.avatarColor);- setSelectedSkills(bot.skills);- setCapabilities(bot.capabilities);- savedSettingsRef.current = normalizeBotSettingsPayload({ name: bot.name, description: bot.description, identitySource: bot.identitySource ?? '', userContextSource: bot.userContextSource ?? '', avatar: bot.avatar, avatarColor: bot.avatarColor, capabilities: bot.capabilities, skills: bot.skills }, bot.name);- }, [bot]);-+ const reconciledBotRef = useRef(bot);+ const savingProfileRef = useRef(false);const savedSettingsRef = useRef(normalizeBotSettingsPayload({ name, description, identitySource, userContextSource, avatar, avatarColor, capabilities, skills: selectedSkills }, bot.name));const commitProfile = useCallback(async (payload: BotSettingsPayload) => {- await updateBotProfile(bot.id, botSettingsChanges(savedSettingsRef.current, payload));- savedSettingsRef.current = payload;+ savingProfileRef.current = true;+ try {+ await updateBotProfile(bot.id, botSettingsChanges(savedSettingsRef.current, payload));+ savedSettingsRef.current = payload;+ } finally {+ savingProfileRef.current = false;+ }},[bot.id],);@@ -129,9 +117,34 @@ export function BotSettings({fallbackName: bot.name,// 归档 bot 的设置页是只读的(不渲染任何表单字段),自动保存不得为它引入写入。enabled: bot.status !== 'archived',+ baseline: savedSettingsRef,commit: commitProfile,});+ useEffect(() => {+ // Store props include optimistic writes and rollback. Reconcile only after+ // our save settles, retaining edits typed while that request was in flight.+ if (savingProfileRef.current || reconciledBotRef.current === bot) return;+ const incoming = normalizeBotSettingsPayload({ ...bot, identitySource: bot.identitySource ?? '', userContextSource: bot.userContextSource ?? '' }, bot.name);+ const next = botIdentityRef.current === bot.id+ ? reconcileBotSettingsDraft(savedSettingsRef.current, {+ name, description, identitySource, userContextSource, avatar, avatarColor,+ capabilities, skills: selectedSkills,+ }, incoming)+ : incoming;+ botIdentityRef.current = bot.id;+ reconciledBotRef.current = bot;+ savedSettingsRef.current = incoming;+ setName(next.name);+ setDescription(next.description);+ setIdentitySource(next.identitySource);+ setUserContextSource(next.userContextSource);+ setAvatar(next.avatar);+ setAvatarColor(next.avatarColor);+ setSelectedSkills(next.skills);+ setCapabilities(next.capabilities);+ }, [bot, autosave.status]);+const updateCapability = <K extends keyof BotCapabilities>(key: K, value: BotCapabilities[K]) => {setCapabilities((current) => ({...current,@@ -323,8 +336,8 @@ export function BotSettings({<BotCapabilitySettingsbot={bot}- capabilities={{ ...bot.capabilities, ...botSettingsChanges(savedSettingsRef.current, { ...savedSettingsRef.current, capabilities }).capabilities }}- skills={JSON.stringify(selectedSkills) === JSON.stringify(savedSettingsRef.current.skills) ? bot.skills : selectedSkills}+ capabilities={capabilities}+ skills={selectedSkills}onChange={(kind, values) => {if (kind === 'skill') setSelectedSkills(values);setCapabilities((current) => ({diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsxindex 137eff5335..df597fdcf4 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx@@ -74,6 +74,8 @@ vi.mock('@/state/newMakerDraft', () => ({}),}));+vi.mock('@/lib/sessionService', () => ({ get: async () => ({ workingDir: '/bot/workspace' }) }));+import { BotSettings } from '../BotsHomeView';function capabilities(overrides: Partial<BotCapabilities> = {}): BotCapabilities {@@ -151,7 +153,18 @@ beforeEach(() => {mocks.openPath.mockReset();mocks.openPath.mockResolvedValue({ success: true });mocks.initialSearch = '';- (window as unknown as { electronAPI: unknown }).electronAPI = { openPath: mocks.openPath };+ (window as unknown as { electronAPI: unknown }).electronAPI = {+ openPath: mocks.openPath,+ maker: {+ listAgentSkills: async () => ({ success: true, skills: [{ name: 'release-check' }] }),+ listCustomMcpServers: async () => ({ servers: [{ id: 'shared-docs', name: 'Shared Docs', transport: 'http' }] }),+ plugins: { list: async () => [+ { id: 'docs', name: 'Documents', effectiveEnabled: true, available: true },+ { id: 'scheduler', name: 'Scheduler', effectiveEnabled: true, available: true },+ { id: 'contacts', name: 'Contacts', effectiveEnabled: true, available: false },+ ] },+ },+ };});afterEach(() => {@@ -264,3 +277,101 @@ describe('Bot settings unified autosave', () => {});});});+++describe('same-Bot capability updates while editing settings', () => {+ async function openCapabilities() {+ const details = screen.getByText('bots.capabilities.title').parentElement as HTMLDetailsElement;+ await act(async () => {+ details.open = true;+ fireEvent(details, new Event('toggle'));+ });+ }+ const cases = [+ { name: 'release-check', selected: { skills: ['release-check'], capabilities: capabilities({ skillMode: 'allowlist' }) }, empty: { skills: [], capabilities: capabilities({ skillMode: 'allowlist' }) }, patch: { skills: [] }, addPatch: { skills: ['release-check'] } },+ { name: 'Shared Docs', selected: { capabilities: capabilities({ mcpMode: 'allowlist', mcpServers: ['shared-docs'] }) }, empty: { capabilities: capabilities({ mcpMode: 'allowlist' }) }, patch: { capabilities: { mcpServers: [] } }, addPatch: { capabilities: { mcpServers: ['shared-docs'] } } },+ { name: 'Documents', selected: { capabilities: capabilities({ toolsetMode: 'allowlist', toolsets: ['docs'] }) }, empty: { capabilities: capabilities({ toolsetMode: 'allowlist' }) }, patch: { capabilities: { toolsets: [] } }, addPatch: { capabilities: { toolsets: ['docs'] } } },+ ];++ it.each(cases)('can remove externally joined $name and add it back after external removal', async ({ name, selected, empty, patch, addPatch }) => {+ vi.useFakeTimers();+ const view = renderSettings(empty);+ await openCapabilities();+ const rerender = (profile: Partial<BotProfile>) => view.rerender(+ <BotSettings bot={bot(profile)} onBack={view.onBack} onOpenSession={view.onOpenSession} />,+ );+ rerender({ ...selected, currentVersion: 2 });+ expect((screen.getByRole('checkbox', { name }) as HTMLInputElement).checked).toBe(true);+ expect(mocks.updateBotProfile).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('checkbox', { name }));+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', patch);+ // Restore externally, then remove externally: re-adding must also be dirty.+ rerender({ ...selected, currentVersion: 3 });+ rerender({ ...empty, currentVersion: 4 });+ expect((screen.getByRole('checkbox', { name }) as HTMLInputElement).checked).toBe(false);+ fireEvent.click(screen.getByRole('checkbox', { name }));+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(mocks.updateBotProfile).toHaveBeenCalledTimes(2);+ expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', addPatch);+ expect((screen.getByRole('checkbox', { name }) as HTMLInputElement).checked).toBe(true);+ });++ it('preserves pending text and per-item choices while incorporating external additions', async () => {+ vi.useFakeTimers();+ const view = renderSettings({ capabilities: capabilities({ toolsetMode: 'allowlist' }) });+ await openCapabilities();+ fireEvent.change(screen.getByLabelText('bots.nameLabel'), { target: { value: 'Local name' } });+ fireEvent.click(screen.getByRole('checkbox', { name: 'Scheduler' }));+ view.rerender(<BotSettings bot={bot({ currentVersion: 2, capabilities: capabilities({ toolsetMode: 'allowlist', toolsets: ['docs'] }) })} onBack={view.onBack} onOpenSession={view.onOpenSession} />);+ expect((screen.getByLabelText('bots.nameLabel') as HTMLInputElement).value).toBe('Local name');+ expect((screen.getByRole('checkbox', { name: 'Documents' }) as HTMLInputElement).checked).toBe(true);+ expect((screen.getByRole('checkbox', { name: 'Scheduler' }) as HTMLInputElement).checked).toBe(true);+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { name: 'Local name', capabilities: { toolsets: ['docs', 'scheduler'] } });+ });++ it('keeps edits made during a successful save and adopts concurrent capability updates', async () => {+ vi.useFakeTimers();+ let finishSave!: (value: { id: string; currentVersion: number; name: string }) => void;+ mocks.updateBotProfile.mockImplementationOnce(() => new Promise((resolve) => { finishSave = resolve; }));+ const view = renderSettings();+ fireEvent.change(screen.getByLabelText('bots.nameLabel'), { target: { value: 'First name' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ view.rerender(<BotSettings bot={bot({ name: 'First name' })} onBack={view.onBack} onOpenSession={view.onOpenSession} />);+ fireEvent.change(screen.getByLabelText('bots.nameLabel'), { target: { value: 'Second name' } });+ view.rerender(<BotSettings bot={bot({ name: 'First name', currentVersion: 3, skills: ['release-check'] })} onBack={view.onBack} onOpenSession={view.onOpenSession} />);+ await act(async () => { finishSave({ id: 'bot-1', currentVersion: 2, name: 'First name' }); });+ expect((screen.getByLabelText('bots.nameLabel') as HTMLInputElement).value).toBe('Second name');+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { name: 'Second name' });+ expect((screen.getByRole('checkbox', { name: /release-check/ }) as HTMLInputElement).checked).toBe(true);+ });++ it('keeps a failed optimistic edit dirty and retries it after a profile rollback', async () => {+ vi.useFakeTimers();+ let rejectSave!: (error: Error) => void;+ mocks.updateBotProfile.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectSave = reject; }));+ const view = renderSettings();+ fireEvent.change(screen.getByLabelText('bots.nameLabel'), { target: { value: 'Local name' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ view.rerender(<BotSettings bot={bot({ name: 'Local name' })} onBack={view.onBack} onOpenSession={view.onOpenSession} />);+ fireEvent.change(screen.getByLabelText('bots.nameLabel'), { target: { value: 'Newer local name' } });+ view.rerender(<BotSettings bot={bot({ currentVersion: 2, skills: ['release-check'] })} onBack={view.onBack} onOpenSession={view.onOpenSession} />);+ await act(async () => { rejectSave(new Error('save failed')); });+ expect((screen.getByLabelText('bots.nameLabel') as HTMLInputElement).value).toBe('Newer local name');+ fireEvent.click(screen.getByRole('button', { name: 'bots.autosave.retry' }));+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { name: 'Newer local name' });+ });++ it('uses host availability and still allows removing a joined unavailable toolset', async () => {+ const view = renderSettings();+ await openCapabilities();+ expect((screen.getByRole('checkbox', { name: /Contacts/ }) as HTMLInputElement).disabled).toBe(true);+ view.rerender(<BotSettings bot={bot({ currentVersion: 2, capabilities: capabilities({ toolsetMode: 'allowlist', toolsets: ['contacts'] }) })} onBack={view.onBack} onOpenSession={view.onOpenSession} />);+ expect((screen.getByRole('checkbox', { name: /Contacts/ }) as HTMLInputElement).disabled).toBe(false);+ fireEvent.click(screen.getByRole('checkbox', { name: /Contacts/ }));+ await waitFor(() => expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { capabilities: { toolsets: [] } }));+ });+});diff --git a/apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts b/apps/desktop/src/renderer/features/bots/botSettingsAutosave.tsindex 107204e385..736971614a 100644--- a/apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts+++ b/apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts@@ -140,6 +140,33 @@ export function botSettingsChanges(previous: BotSettingsPayload, next: BotSettinreturn { ...changed, ...(Object.keys(capabilityChanges).length ? { capabilities: capabilityChanges } : {}) };}+/** Advance untouched fields to a live profile without discarding pending local edits. */+export function reconcileBotSettingsDraft(+ baseline: BotSettingsPayload,+ draft: BotSettingsDraft,+ incoming: BotSettingsPayload,+): BotSettingsDraft {+ const normalized = normalizeBotSettingsPayload(draft, baseline.name);+ const changes = botSettingsChanges(baseline, normalized);+ const reconcileList = (previous: string[], local: string[], remote: string[]) => [+ ...remote.filter((id) => !previous.includes(id) || local.includes(id)),+ ...local.filter((id) => !previous.includes(id) && !remote.includes(id)),+ ];+ return {+ ...incoming,+ ...Object.fromEntries(Object.keys(changes)+ .filter((key) => key !== 'capabilities')+ .map((key) => [key, draft[key as keyof BotSettingsDraft]])),+ skills: reconcileList(baseline.skills, draft.skills, incoming.skills),+ capabilities: {+ ...incoming.capabilities,+ ...changes.capabilities,+ mcpServers: reconcileList(baseline.capabilities.mcpServers, draft.capabilities.mcpServers, incoming.capabilities.mcpServers),+ toolsets: reconcileList(baseline.capabilities.toolsets, draft.capabilities.toolsets, incoming.capabilities.toolsets),+ },+ };+}+/** 自动保存对用户可见的状态。`saved` 由 UI 侧短暂显示后淡出,不常驻。 */export type BotAutosaveStatus = 'idle' | 'saving' | 'saved' | 'error';diff --git a/apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts b/apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.tsindex cebe8f8237..9c5c2a23f0 100644--- a/apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts+++ b/apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts@@ -33,7 +33,9 @@ export interface UseBotSettingsAutosaveOptions {fallbackName: string;/** 是否允许写入。归档 bot 等只读场景传 false,连脏检查都不做。 */enabled: boolean;- /** 真正提交。成功 resolve;失败 reject。基线由本 hook 在成功后推进。 */+ /** Shared with profile reconciliation and patch generation; only confirmed saves advance it. */+ baseline: { current: BotSettingsPayload };+ /** 真正提交。成功 resolve 并推进基线;失败 reject。 */commit: (payload: BotSettingsPayload) => Promise<void>;textDelayMs?: number;instantDelayMs?: number;@@ -64,7 +66,7 @@ export function useBotSettingsAutosave(// 基线 = 上次成功落库的快照。用与当前值同一个归一化函数产生,否则挂载瞬间就会// 因为 trim 差异被判成脏。- const baselineRef = useRef(payload);+ const baselineRef = options.baseline;const commitRef = useRef(commit);commitRef.current = commit;const enabledRef = useRef(enabled);@@ -98,8 +100,6 @@ export function useBotSettingsAutosave(commit: async (next) => {if (!enabledRef.current) return;await commitRef.current(next);- // 只有落库成功才推进基线;失败后基线不动,脏仍然是脏,重试才有意义。- baselineRef.current = next;},onStatusChange: handleStatus,});diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex c70d32bbca..fc5f87002c 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -12,6 +12,7 @@ interface ImportMeta {readonly env: ImportMetaEnv;}+type BotToolsetContext = import('../shared/botRemoteCapabilities').BotToolsetContext;type AgentProxyPrefPayload = import('../shared/agentProxyConfig').SshHostAgentProxyPref;type AgentProxyTunnelStatePayload = import('../shared/agentProxyConfig').AgentProxyTunnelState;type ModelAccessStatusPayload = import('../shared/modelAccess').ModelAccessStatus;@@ -989,6 +990,8 @@ interface CrossAgentStepEvent {}interface PluginListItem {+ /** Present only when queried for a Bot runtime context. */+ available?: boolean;id: string;name: string;description: string;@@ -6511,7 +6514,7 @@ interface ElectronAPI {};plugins: {- list: (workingDir?: string, includeHidden?: boolean) => Promise<PluginListItem[]>;+ list: (workingDir?: string, includeHidden?: boolean, botContext?: Omit<BotToolsetContext, 'workingDir'>) => Promise<PluginListItem[]>;getState: (id: string,workingDir?: string,diff --git a/apps/desktop/src/shared/botRemoteCapabilities.ts b/apps/desktop/src/shared/botRemoteCapabilities.tsindex 3d8506d8e3..5afb3725e1 100644--- a/apps/desktop/src/shared/botRemoteCapabilities.ts+++ b/apps/desktop/src/shared/botRemoteCapabilities.ts@@ -1,5 +1,13 @@import type { AgentKind } from '@cindy/maker-core';+/** Read-only context for evaluating a companion's next-turn toolset catalog. */+export interface BotToolsetContext {+ botId: string;+ agentKind: AgentKind;+ workingDir: string;+ remoteHostId?: string | null;+}+/*** SSH Claude/Codex only receive the narrowly scoped host bridge declared in* codexHttpBridge.ts. Pi has a per-session SSH tunnel for the complete MCP