Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): revalidate capability additions before settings save
zqchrise0038b2036cd
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 61f0a612a3..342f60edc6 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -9,7 +9,7 @@ import { BOT_TEMPLATE_PRESET_IDENTITIES } from '../../../../shared/botTemplatePrimport { createBotModelRouteReconciler } from '../../../maker-ipc/botModelRouteReconciler';import type { BotModelRoute } from '../../../../shared/botModelChain';import type { AgentKind } from '@cindy/maker-core';-import { createBotCapabilityService } from '../../../maker-ipc/botCapabilityService';+import { createBotCapabilityService, type BotCapabilityUpdate } from '../../../maker-ipc/botCapabilityService';import { buildBotMcpCatalog } from '../../../maker-host/botMcpCatalog';import { CustomMcpProvider } from '../../../mcp-integrations/custom-mcp-provider';import type { McpProvider } from '@cindy/maker-core';@@ -65,6 +65,7 @@ const h = await vi.hoisted(async () => {ensureDialogue: vi.fn((sessionId: string) => join(userDataDir, sessionId)),searchConversations: vi.fn(),requestRuntimeRefresh: vi.fn(),+ validateCapabilityAdditions: vi.fn(async (_update: BotCapabilityUpdate) => {}),seedTemplateSkills: vi.fn(async () => ({ completedNow: true, skills: [] })),toolsetsAvailable: false,customMcpConfigs: [] as CustomMcpConfig[],@@ -112,6 +113,7 @@ vi.mock('../../../maker-host/custom-mcp-store.js', async (importOriginal) => ({listCustomMcpServers: async () => h.customMcpConfigs,}));vi.mock('../../../maker-host/index.js', () => ({+ validateBotCapabilityAdditions: h.validateCapabilityAdditions,getMaker: () => ({ getSession: h.getSession, listAgentSkills: async () => ({ skills: [{ name: 'release-check', description: 'Release checklist', enabled: true }] }) }),getPluginRegistry: () => ({getPlugins: () => ['memory', 'xdt_helper', 'contacts', 'lsp'].map((id) => ({ id, name: id, description: id })),@@ -424,6 +426,7 @@ const { list: findBotCapabilities, select: selectBotCapability } = createBotCapabeforeEach(async () => {h.toolsetsAvailable = false;+ h.validateCapabilityAdditions.mockReset().mockResolvedValue(undefined);h.customMcpConfigs = [{ id: 'shared-docs', name: 'Shared Docs', transport: 'http', url: 'https://example.invalid/private', headers: { Authorization: 'FAKE_SECRET' } }];h.mcpProviders = [{ name: 'cindy_helper', toClaudeSdkConfig: () => ({ type: 'sdk' }) },@@ -1657,6 +1660,95 @@ describe('Bot canonical Session lifecycle', () => {await expect(findBotCapabilities({ callerSessionId, kind: 'skill' })).resolves.toMatchObject({ capabilities: [{ id: 'release-check', joined: true }] });});+ it.each(['skill', 'toolset-global', 'toolset-provider', 'mcp'] as const)(+ 'revalidates newly added %s at the settings save boundary without blocking old references', async (scenario) => {+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ let available = true;+ const kind = scenario.startsWith('toolset') ? 'toolset' as const : scenario as 'skill' | 'mcp';+ const id = kind === 'skill' ? 'release-check' : kind === 'toolset' ? 'contacts' : 'shared-docs';+ const field = kind === 'skill' ? 'skills' : kind === 'toolset' ? 'toolsets' : 'mcpServers';+ const patch = (ids: string[]) => kind === 'skill' ? { skills: ids } : { capabilities: { [field]: ids } };+ const listAgentSkills = vi.fn(async (_agentKind: AgentKind, opts: { forceReload?: boolean }) => ({+ skills: available || !opts.forceReload+ ? [{ kind: 'agent-skill' as const, source: 'user' as const, name: 'release-check', enabled: true }] : [],+ }));+ const resolveBotAgentKind = vi.fn(capabilityDeps.resolveBotAgentKind);+ const service = createBotCapabilityService({+ ...capabilityDeps, resolveBotAgentKind,+ getMaker: () => ({ listAgentSkills }),+ getPluginRegistry: () => ({+ getPlugins: getPluginRegistry().getPlugins,+ getEnableState: async (id, workingDir) => ({+ ...await getPluginRegistry().getEnableState(id, workingDir),+ effectiveEnabled: scenario !== 'toolset-global' || available,+ }),+ }),+ isBotToolsetAvailable: () => scenario !== 'toolset-provider' || available,+ listMcpServers: async (input) => available ? capabilityDeps.listMcpServers(input) : [],+ });+ h.validateCapabilityAdditions.mockImplementation(service.validateAdditions);+ await expect(service.list({ callerSessionId: created.session.id, kind })).resolves.toMatchObject({+ capabilities: expect.arrayContaining([expect.objectContaining({ id, available: true })]),+ });+ available = false;+ await expect(service.select({ callerSessionId: created.session.id, kind, id, joined: true }))+ .resolves.toMatchObject({ ok: false, errorCode: 'CAPABILITY_UNAVAILABLE' });+ await expect(invoke('local-db:bots:update', { id: 'bot-1', name: 'Unsaved name', ...patch([id]) }))+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(h.sqlite!.prepare('SELECT current_version, display_name FROM bot_profiles WHERE id = ?').get('bot-1'))+ .toEqual({ current_version: 1, display_name: 'Release Bot' });+ if (kind === 'skill') expect(listAgentSkills).toHaveBeenLastCalledWith('pi', expect.objectContaining({ forceReload: true }));+ available = true;+ await expect(invoke('local-db:bots:update', { id: 'bot-1', ...patch([id]) })).resolves.toMatchObject({ currentVersion: 2 });+ available = false;+ resolveBotAgentKind.mockClear();+ // Retaining a now-unavailable reference must not prevent an unrelated edit or removal.+ await expect(invoke('local-db:bots:update', { id: 'bot-1', name: 'Saved name', ...patch([id]) })).resolves.toMatchObject({ name: 'Saved name' });+ await expect(invoke('local-db:bots:update', { id: 'bot-1', ...patch([]) })).resolves.toBeTruthy();+ expect(resolveBotAgentKind).not.toHaveBeenCalled();+ },+ );++ it('validates a settings grant against the model chain saved in the same update', async () => {+ h.customMcpConfigs.push({ id: 'events', name: 'Events', transport: 'sse', url: 'https://example.invalid/sse', headers: {} });+ await refreshCustomMcpProviders();+ const chain: BotModelRoute[] = [{ harness: 'claude', model: 'claude-x', providerId: null, effort: '', fastMode: false }];+ await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { modelChain: chain } });+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 2,+ });+ const apply = vi.fn();+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,+ read: async () => ({ chain, current: { agentKind: 'claude-code', model: 'claude-x', providerId: null, effort: null, fastMode: false }, hasRuntimeOverride: true }), apply });+ const resolveBotAgentKind = vi.fn(async (id: string, draft?: BotModelRoute[]) => (await reconcile.preview(id, draft))?.agentKind ?? null);+ const service = createBotCapabilityService({ ...capabilityDeps, resolveBotAgentKind });+ h.validateCapabilityAdditions.mockImplementation(service.validateAdditions);+ const next = [{ ...chain[0]!, harness: 'codex', model: 'codex-x' }];+ await expect(invoke('local-db:bots:update', { id: 'bot-1', capabilities: { modelChain: next, mcpServers: ['events'] } }))+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(resolveBotAgentKind).toHaveBeenLastCalledWith(created.session.id, next);+ expect(h.sqlite!.prepare('SELECT current_version FROM bot_profiles WHERE id = ?').pluck().get('bot-1')).toBe(2);+ expect(apply).not.toHaveBeenCalled();+ });++ it.each(['owner', 'version'])('does not commit a validated settings grant after an in-flight %s change', async (change) => {+ await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ const service = createBotCapabilityService({ ...capabilityDeps,+ listMcpServers: async (input) => {+ if (change === 'owner') h.ownerScopeKey = 'another-owner';+ else h.sqlite!.prepare('UPDATE bot_profiles SET current_version = current_version + 1 WHERE id = ?').run('bot-1');+ return capabilityDeps.listMcpServers(input);+ },+ });+ h.validateCapabilityAdditions.mockImplementation(service.validateAdditions);+ await expect(invoke('local-db:bots:update', { id: 'bot-1', capabilities: { mcpServers: ['shared-docs'] } })).rejects.toBeTruthy();+ expect(h.sqlite!.prepare('SELECT COUNT(*) FROM bot_profile_versions WHERE bot_id = ?').pluck().get('bot-1')).toBe(1);+ });+it('validates model-side grants against the next configured route while the old turn is running', async () => {let chain: BotModelRoute[] = [{ harness: 'claude', model: 'claude-x', providerId: null, effort: '', fastMode: false }];h.customMcpConfigs.push({ id: 'events', name: 'Events', transport: 'sse', url: 'https://example.invalid/sse', headers: {} });diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex b6301a12fc..7419dbecb3 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -84,7 +84,8 @@ import { BOT_DELEGATION_CLIENT_ID } from '../../../shared/botCollaboration.js';import { botInvitationProgress } from '../../../shared/botInvitation.js';import { queueBotInvitation as enqueueBotInvitation } from '../../maker-ipc/botInvitation.js';-import { getMakerIfReady } from '../../maker-host/index.js';+import { getMakerIfReady, validateBotCapabilityAdditions } from '../../maker-host/index.js';+import type { BotCapabilityUpdate } from '../../maker-ipc/botCapabilityService.js';import { getResolvedMainLocale } from '../../i18n.js';import { broadcastBotRemoteResourceChanged } from '../../maker-ipc/botRemoteResourceInvalidation.js';@@ -1078,7 +1079,8 @@ export async function createBotProfile(raw: unknown) {}/** Shared profile mutation for trusted settings and owner-bound capability selection. */-export async function updateBotProfile(raw: unknown, expectedVersion?: number) {+export async function updateBotProfile(raw: unknown, expectedVersion?: number,+ validateAdditions?: (update: BotCapabilityUpdate) => Promise<void>) {const body =raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};const id = readText(body.id, 'botId', 128, true);@@ -1191,6 +1193,11 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number) {previousIdentitySource: version?.identitySource ?? '',nextIdentitySource,});+ // Only the renderer save boundary needs this hook; model-side selections already validate+ // before calling this function. Both paths retain the transaction's profile-version CAS.+ await validateAdditions?.({ botId: id, canonicalSessionId: current.canonicalSessionId,+ previous, next: normalizedNextConfig });+ owner.assertCurrent();await client.tx('bots.updateProfile', {id,...(patch.displayName !== undefined ? { displayName: patch.displayName } : {}),@@ -1425,7 +1432,7 @@ export function registerBotIpc(): void {ipcMain.handle('local-db:bots:update', async (event, raw: unknown) => {assertTrustedAppRendererEvent(event);- return updateBotProfile(raw);+ return updateBotProfile(raw, undefined, validateBotCapabilityAdditions);});const createBotCanonicalSessionUnlocked = async (diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 41c77c8ee8..c305f825b2 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -57,7 +57,7 @@ import {} from '../maker-ipc/botProfileRuntime.js';import { collectBotOwnSkillMounts } from '../maker-ipc/botSkillService.js';import { buildBotMcpCatalog } from './botMcpCatalog.js';-import { createBotCapabilityService, type BotCapabilityServiceDeps } from '../maker-ipc/botCapabilityService.js';+import { createBotCapabilityService, type BotCapabilityServiceDeps, type BotCapabilityUpdate } from '../maker-ipc/botCapabilityService.js';import {botProfileDir,ensureBotContentDirs,@@ -746,6 +746,19 @@ export async function listBotRuntimeMcpServers({ agentKind }: { agentKind: Agent});}+function createDesktopBotCapabilityService() {+ return createBotCapabilityService({+ getMaker, getPluginRegistry, isBotToolsetAvailable,+ listMcpServers: listBotRuntimeMcpServers,+ resolveBotAgentKind: async (sessionId, chain) => _resolveBotCapabilityAgentKind?.(sessionId, chain) ?? null,+ });+}++/** Settings IPC reuses the model-side catalog at its save boundary. */+export async function validateBotCapabilityAdditions(update: BotCapabilityUpdate): Promise<void> {+ await createDesktopBotCapabilityService().validateAdditions(update);+}+/** Get the plugin registry singleton (delegates to plugins/index.ts module-level cache). */export function getPluginRegistry() {return createPluginRegistry();@@ -863,11 +876,7 @@ export function getMaker(): Maker {};const makerMemoryProviderDeps = {- botCapabilities: createBotCapabilityService({- getMaker, getPluginRegistry, isBotToolsetAvailable,- listMcpServers: listBotRuntimeMcpServers,- resolveBotAgentKind: async (sessionId) => _resolveBotCapabilityAgentKind?.(sessionId) ?? null,- }),+ botCapabilities: createDesktopBotCapabilityService(),createMediaDownloadContext: (sessionId: string, sessionInstanceId: string) => {const session = _maker?.getSession(sessionId);if (!session || session.instanceId !== sessionInstanceId) return undefined;diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.tsindex c91d37f2b4..f9da30e180 100644--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts@@ -9,17 +9,26 @@ import type { AgentKind, Maker } from '@cindy/maker-core';import type { PluginRegistry } from '../maker-host/plugins/plugin-registry.js';import type { BotToolsetContext } from '../../shared/botRemoteCapabilities.js';import type { BotProfileRuntimeDeps } from './botProfileRuntime.js';+import type { BotModelRoute } from '../../shared/botModelChain.js';+import { readEffectiveBotModelChain } from '../maker-host/bot-model-chain-settings-store.js';+import { throwIpcError } from '../utils/ipcValidate.js';type Kind = 'skill' | 'mcp' | 'toolset';type Input = { callerSessionId: string; kind: Kind };type Entry = { id: string; name: string; description: string; available: boolean; joined: boolean };export interface BotCapabilityServiceDeps {getMaker: () => Pick<Maker, 'listAgentSkills'>;- resolveBotAgentKind: (sessionId: string) => Promise<AgentKind | null>;+ resolveBotAgentKind: (sessionId: string, modelChain?: BotModelRoute[]) => Promise<AgentKind | null>;getPluginRegistry: () => Pick<PluginRegistry, 'getPlugins' | 'getEnableState'>;isBotToolsetAvailable: (input: BotToolsetContext & { toolsetId: string }) => boolean;listMcpServers: NonNullable<BotProfileRuntimeDeps['listMcpServers']>;}+export interface BotCapabilityUpdate {+ botId: string;+ canonicalSessionId: string | null;+ previous: Record<string, unknown>;+ next: Record<string, unknown>;+}const fields: Record<Kind, { list: string; mode: string }> = {skill: { list: 'skills', mode: 'skillMode' },mcp: { list: 'mcpServers', mode: 'mcpMode' },@@ -83,13 +92,14 @@ async function context(callerSessionId: string) {return { ...row, config, assertOwner };}-async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>, deps: BotCapabilityServiceDeps): Promise<Entry[]> {+async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>, deps: BotCapabilityServiceDeps,+ options?: { modelChain?: BotModelRoute[]; forceReload?: boolean }): Promise<Entry[]> {const joined = new Set(strings(ctx.config[fields[input.kind].list]).filter((id) => input.kind !== 'toolset' || !BOT_BASELINE_PLUGIN_IDS.has(id),));const { getMaker, getPluginRegistry, isBotToolsetAvailable } = deps;// Grants apply next turn, so use the same preview as settings and send-time reconciliation.- const agentKind = await deps.resolveBotAgentKind(input.callerSessionId);+ const agentKind = await deps.resolveBotAgentKind(input.callerSessionId, options?.modelChain);ctx.assertOwner();if (!agentKind) throw new Error('Bot next-turn route is unavailable');const workingDir = ctx.workingDir ?? '';@@ -98,6 +108,7 @@ async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>, dconst result = await getMaker().listAgentSkills(agentKind, {workingDir,remoteHostId: ctx.remoteHostId ?? undefined,+ ...(options?.forceReload ? { forceReload: true } : {}),});items = result.skills.map((skill) => ({id: skill.name,@@ -181,7 +192,7 @@ async function selectBotCapability(input: Input & { id: string; joined: booleanconst field = fields[input.kind];const previous = strings(ctx.config[field.list]);if (input.joined) {- const item = (await catalog(input, ctx, deps)).find((entry) => entry.id === input.id);+ const item = (await catalog(input, ctx, deps, { forceReload: true })).find((entry) => entry.id === input.id);if (!item?.available)return {ok: false as const,@@ -213,5 +224,30 @@ export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {return {list: (input: Input & { query?: string }) => findBotCapabilities(input, deps),select: (input: Input & { id: string; joined: boolean }) => selectBotCapability(input, deps),+ /** Renderer saves may contain stale selections; validate only new references before persistence. */+ async validateAdditions(update: BotCapabilityUpdate): Promise<void> {+ const additions = (Object.keys(fields) as Kind[]).map((kind) => {+ const field = fields[kind].list;+ const previous = new Set(strings(update.previous[field]));+ return { kind, ids: strings(update.next[field]).filter((id) => !previous.has(id)) };+ }).filter((entry) => entry.ids.length > 0);+ if (additions.length === 0) return;+ try {+ if (!update.canonicalSessionId) throw new Error('Missing canonical task');+ const ctx = await context(update.canonicalSessionId);+ if (ctx.botId !== update.botId) throw new Error('Canonical task owner mismatch');+ const modelChain = readEffectiveBotModelChain(update.next);+ for (const { kind, ids } of additions) {+ const entries = await catalog({ callerSessionId: update.canonicalSessionId, kind }, ctx, deps,+ { modelChain, forceReload: true });+ if (ids.some((id) => !entries.some((entry) => entry.id === id && entry.available))) {+ throw new Error('Capability unavailable');+ }+ }+ ctx.assertOwner();+ } catch {+ throwIpcError('PRECONDITION_FAILED', '所选能力已不可用或伙伴状态已变化,请刷新后重试');+ }+ },};}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 2f3601de77..887a369710 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -10659,8 +10659,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},});- setBotCapabilityAgentKindResolver(async (sessionId) =>- (await reconcileBotModelRoute.preview(sessionId))?.agentKind ?? null);+ setBotCapabilityAgentKindResolver(async (sessionId, chain) =>+ (await reconcileBotModelRoute.preview(sessionId, chain))?.agentKind ?? null);const readBotFallbackCandidate = async (sessionId: string,diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 3d9f3272bb..6e1f774a5d 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -78,7 +78,7 @@ import {import { botSessionLinks, sessions } from '../localDb/schema.js';export interface DesktopMcpProvidersDeps {- botCapabilities: ReturnType<typeof createBotCapabilityService>;+ botCapabilities: Pick<ReturnType<typeof createBotCapabilityService>, 'list' | 'select'>;createMediaDownloadContext?: CindyGhostsHostDeps['createMediaDownloadContext'];/** 当前 Desktop 版本,供 Forge 为具体插件包生成默认 minCindyVersion。 */getAppVersion?: () => string;