Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bots): refresh next-turn capability validation

zqchris3f931b7b2f73
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index a7152f89ca..61f0a612a3 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -6,6 +6,9 @@ import { rmSync } from 'node:fs';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { BOT_TEMPLATE_PRESET_IDENTITIES } from '../../../../shared/botTemplatePreset';
+import { 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 { buildBotMcpCatalog } from '../../../maker-host/botMcpCatalog';
import { CustomMcpProvider } from '../../../mcp-integrations/custom-mcp-provider';
@@ -409,13 +412,15 @@ async function invoke(channel: string, body: unknown): Promise<any> {
if (!handler) throw new Error(`${channel} handler not registered`);
return handler({}, body);
}
-const { list: findBotCapabilities, select: selectBotCapability } = createBotCapabilityService({
+const capabilityDeps = {
getMaker, getPluginRegistry, isBotToolsetAvailable,
- listMcpServers: async ({ agentKind }) => buildBotMcpCatalog({
+ resolveBotAgentKind: async (): Promise<AgentKind | null> => 'pi',
+ listMcpServers: async ({ agentKind }: { agentKind: AgentKind }) => buildBotMcpCatalog({
agentKind, providers: h.mcpProviders, builtinNames: getBuiltinMcpServerNames(),
customServers: h.customMcpConfigs.map((config) => ({ ...config, updatedAt: 1 })),
}),
-});
+};
+const { list: findBotCapabilities, select: selectBotCapability } = createBotCapabilityService(capabilityDeps);
beforeEach(async () => {
h.toolsetsAvailable = false;
@@ -1652,6 +1657,76 @@ describe('Bot canonical Session lifecycle', () => {
await expect(findBotCapabilities({ callerSessionId, kind: 'skill' })).resolves.toMatchObject({ capabilities: [{ id: 'release-check', joined: true }] });
});
+ 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: {} });
+ await refreshCustomMcpProviders();
+ 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 current = { agentKind: 'claude-code' as const, model: 'claude-x', providerId: null, effort: null, fastMode: false };
+ const apply = vi.fn(async () => {});
+ const reconcile = createBotModelRouteReconciler({
+ ownerEpoch: () => h.ownerScopeKey,
+ read: async () => ({ chain, current, hasRuntimeOverride: true }),
+ apply,
+ });
+ await reconcile(created.session.id);
+ const listAgentSkills = vi.fn(async (agentKind: AgentKind) => ({
+ skills: [{ kind: 'agent-skill' as const, name: 'route-skill', source: 'user' as const, enabled: agentKind === 'claude-code' }],
+ }));
+ const toolsetAvailable = vi.fn((ctx: { agentKind: AgentKind }) => ctx.agentKind === 'claude-code');
+ const service = createBotCapabilityService({
+ ...capabilityDeps,
+ getMaker: () => ({ getSession: () => current, listAgentSkills }),
+ isBotToolsetAvailable: toolsetAvailable,
+ resolveBotAgentKind: async (id) => (await reconcile.preview(id))?.agentKind ?? null,
+ });
+ const input = { callerSessionId: created.session.id, kind: 'mcp' as const, id: 'events' };
+ await expect(service.list(input)).resolves.toMatchObject({ capabilities: expect.arrayContaining([
+ expect.objectContaining({ id: 'events', available: true }),
+ ]) });
+ // The profile changes during the current Claude turn; it has not applied a switch yet.
+ chain = [{ ...chain[0]!, harness: 'codex', model: 'codex-x' }];
+ await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { modelChain: chain } });
+ for (const [kind, id] of [['mcp', 'events'], ['skill', 'route-skill'], ['toolset', 'contacts']] as const) {
+ await expect(service.list({ ...input, kind })).resolves.toMatchObject({
+ capabilities: expect.arrayContaining([expect.objectContaining({ id, available: false })]),
+ });
+ await expect(service.select({ ...input, kind, id, joined: true })).resolves.toMatchObject({ ok: false, errorCode: 'CAPABILITY_UNAVAILABLE' });
+ }
+ expect(listAgentSkills).toHaveBeenLastCalledWith('codex', expect.anything());
+ expect(toolsetAvailable).toHaveBeenLastCalledWith(expect.objectContaining({ agentKind: 'codex' }));
+ expect(apply).not.toHaveBeenCalled();
+ expect(h.sqlite!.prepare('SELECT current_version FROM bot_profiles WHERE id = ?').pluck().get('bot-1')).toBe(3);
+ // Previewing a grant must not consume the pending route change for the next send.
+ await reconcile(created.session.id);
+ expect(apply).toHaveBeenCalledWith(created.session.id, expect.objectContaining({ agentKind: 'codex' }), current);
+ });
+
+ it.each(['missing', 'error', 'owner-change'])('does not use the current route when next-turn preview fails: %s', async (reason) => {
+ await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { mcpServers: ['shared-docs'] } });
+ const created = await invoke('local-db:bots:create-canonical-session', {
+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 2,
+ });
+ const listMcpServers = vi.fn(capabilityDeps.listMcpServers);
+ const resolveBotAgentKind = vi.fn(async (): Promise<AgentKind | null> => {
+ if (reason === 'error') throw new Error('preview failed');
+ if (reason === 'owner-change') { h.ownerScopeKey = 'owner-b'; return 'claude-code'; }
+ return null;
+ });
+ const service = createBotCapabilityService({ ...capabilityDeps, listMcpServers, resolveBotAgentKind });
+ const input = { callerSessionId: created.session.id, kind: 'mcp' as const, id: 'shared-docs' };
+ await expect(service.select({ ...input, joined: true })).resolves.toMatchObject({ ok: false, errorCode: 'CAPABILITY_SELECTION_FAILED' });
+ expect(listMcpServers).not.toHaveBeenCalled();
+ expect(h.sqlite!.prepare('SELECT current_version FROM bot_profiles WHERE id = ?').pluck().get('bot-1')).toBe(2);
+ h.ownerScopeKey = 'owner-a:1';
+ resolveBotAgentKind.mockClear();
+ await expect(service.select({ ...input, joined: false })).resolves.toMatchObject({ ok: true });
+ expect(resolveBotAgentKind).not.toHaveBeenCalled();
+ });
+
it.each(['cindy_helper', '__proto__', 'constructor', 'bad_header'])('rejects MCP %s quarantined by the actual registry while keeping its saved reference removable', async (id) => {
h.customMcpConfigs.push({
id, name: 'Legacy MCP', transport: 'http', url: 'https://example.invalid/legacy',
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index caef0bcdd1..41c77c8ee8 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 } from '../maker-ipc/botCapabilityService.js';
+import { createBotCapabilityService, type BotCapabilityServiceDeps } from '../maker-ipc/botCapabilityService.js';
import {
botProfileDir,
ensureBotContentDirs,
@@ -521,6 +521,14 @@ export function setBeforeLocalCodexSessionStartHook(hook: (() => Promise<void>)
_beforeLocalCodexSessionStartHook = hook;
}
+// The IPC composition root owns route reconciliation; MCP factories bind before it is ready.
+let _resolveBotCapabilityAgentKind: BotCapabilityServiceDeps['resolveBotAgentKind'] | null = null;
+export function setBotCapabilityAgentKindResolver(
+ resolver: BotCapabilityServiceDeps['resolveBotAgentKind'] | null,
+): void {
+ _resolveBotCapabilityAgentKind = resolver;
+}
+
/**
* detach 某 host 上活跃的远端 codex session (跳过 turn 中的)。
* 使用点:daemon 被 (重) bootstrap 后 (bridge 重建恢复 / shutdown strip) —
@@ -858,6 +866,7 @@ export function getMaker(): Maker {
botCapabilities: createBotCapabilityService({
getMaker, getPluginRegistry, isBotToolsetAvailable,
listMcpServers: listBotRuntimeMcpServers,
+ resolveBotAgentKind: async (sessionId) => _resolveBotCapabilityAgentKind?.(sessionId) ?? null,
}),
createMediaDownloadContext: (sessionId: string, sessionInstanceId: string) => {
const session = _maker?.getSession(sessionId);
@@ -2690,6 +2699,7 @@ export function resetMaker(): void {
_registerPiAgent = null;
_codexAgent = null;
_mcpProviders = {};
+ _resolveBotCapabilityAgentKind = null;
// coordinator 闭包捕获了刚作废的那个 maker —— 不清掉的话,换账号窗口期内到达的 auth
// 事件会拿旧实例去拉模型清单(串号)。下次 getMaker() 会带着干净记账重建它。
_codexModelBackfill = null;
diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
index b47908b67c..c91d37f2b4 100644
--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
@@ -5,7 +5,7 @@ import { updateBotProfile } from '../localDb/ipc/bots.js';
import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { listCustomMcpServers } from '../maker-host/custom-mcp-store.js';
import { BOT_BASELINE_PLUGIN_IDS } from '../maker-host/plugins/types.js';
-import type { Maker } from '@cindy/maker-core';
+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';
@@ -13,8 +13,9 @@ import type { BotProfileRuntimeDeps } from './botProfileRuntime.js';
type Kind = 'skill' | 'mcp' | 'toolset';
type Input = { callerSessionId: string; kind: Kind };
type Entry = { id: string; name: string; description: string; available: boolean; joined: boolean };
-interface BotCapabilityServiceDeps {
- getMaker: () => Pick<Maker, 'getSession' | 'listAgentSkills'>;
+export interface BotCapabilityServiceDeps {
+ getMaker: () => Pick<Maker, 'listAgentSkills'>;
+ resolveBotAgentKind: (sessionId: string) => Promise<AgentKind | null>;
getPluginRegistry: () => Pick<PluginRegistry, 'getPlugins' | 'getEnableState'>;
isBotToolsetAvailable: (input: BotToolsetContext & { toolsetId: string }) => boolean;
listMcpServers: NonNullable<BotProfileRuntimeDeps['listMcpServers']>;
@@ -46,7 +47,6 @@ async function context(callerSessionId: string) {
archivedAt: botSessionLinks.archivedAt,
sessionStatus: sessions.status,
source: sessions.source,
- agentKind: sessions.agentKind,
workingDir: sessions.workingDir,
remoteHostId: sessions.remoteHostId,
config: botProfileVersions.capabilitiesJson,
@@ -88,9 +88,10 @@ async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>, d
(id) => input.kind !== 'toolset' || !BOT_BASELINE_PLUGIN_IDS.has(id),
));
const { getMaker, getPluginRegistry, isBotToolsetAvailable } = deps;
- const agentKind =
- getMaker().getSession(input.callerSessionId)?.agentKind ??
- (ctx.agentKind === 'cc' ? 'claude-code' : ctx.agentKind === 'pi' ? 'pi' : 'codex');
+ // Grants apply next turn, so use the same preview as settings and send-time reconciliation.
+ const agentKind = await deps.resolveBotAgentKind(input.callerSessionId);
+ ctx.assertOwner();
+ if (!agentKind) throw new Error('Bot next-turn route is unavailable');
const workingDir = ctx.workingDir ?? '';
let items: Omit<Entry, 'joined'>[];
if (input.kind === 'skill') {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 3c0c92c78a..2f3601de77 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -418,6 +418,7 @@ import {
prepareCodexForCustomProviderHostChange,
restartCodexAfterAuthModeChange,
setBeforeLocalCodexSessionStartHook,
+ setBotCapabilityAgentKindResolver,
} from '../maker-host/index.js';
import {
readMemorySettingsState,
@@ -10658,6 +10659,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
});
+ setBotCapabilityAgentKindResolver(async (sessionId) =>
+ (await reconcileBotModelRoute.preview(sessionId))?.agentKind ?? null);
+
const readBotFallbackCandidate = async (
sessionId: string,
current: SessionRuntimeProfile,
diff --git a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx
index 32c52b85f2..4dae7a4969 100644
--- a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx
@@ -55,7 +55,8 @@ export function BotCapabilitySettings({
const offPush = window.electronAPI.localDb?.sessionsPush?.onPatched(({ sessionId, patch }, stamp) => {
if (isDataOwnerPushCurrent(stamp)) changed(sessionId, patch);
});
- return () => { offLocal(); offPush?.(); };
+ const offMcp = window.electronAPI.maker.onMcpChanged(refresh);
+ return () => { offLocal(); offPush?.(); offMcp(); };
}, [open, bot.canonicalSessionId, refresh]);
useEffect(() => {
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
index 2a4ac0c70f..7cc47ec97e 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({
listCustomMcpServers: vi.fn<(context?: CustomMcpListContext) => Promise<CustomMcpListResult>>(),
getSession: vi.fn<() => Promise<Partial<Session>>>(),
onSessionPatched: vi.fn(),
+ onMcpChanged: vi.fn(),
listAgentSkills: vi.fn(),
listToolsets: vi.fn(),
updateBotProfile: vi.fn(async (_id: string, patch: Record<string, unknown>) => ({
@@ -162,6 +163,7 @@ beforeEach(() => {
mocks.initialSearch = '';
mocks.getSession.mockReset().mockResolvedValue({ agentKind: 'cc', workingDir: '/bot/workspace' });
mocks.onSessionPatched.mockReset().mockReturnValue(vi.fn());
+ mocks.onMcpChanged.mockReset().mockReturnValue(vi.fn());
mocks.listAgentSkills.mockReset().mockResolvedValue({ success: true, skills: [{ name: 'release-check' }] });
mocks.listToolsets.mockReset().mockResolvedValue([
{ id: 'docs', name: 'Documents', effectiveEnabled: true, available: true },
@@ -180,6 +182,7 @@ beforeEach(() => {
openPath: mocks.openPath,
localDb: { sessionsPush: { onPatched: mocks.onSessionPatched } },
maker: {
+ onMcpChanged: mocks.onMcpChanged,
listAgentSkills: mocks.listAgentSkills,
listCustomMcpServers: mocks.listCustomMcpServers,
plugins: { list: mocks.listToolsets },
@@ -348,6 +351,55 @@ describe('same-Bot capability updates while editing settings', () => {
expect((screen.getByRole('checkbox', { name: /SSE Events/ }) as HTMLInputElement).disabled).toBe(true);
});
+ it.each(['deleted', 'unavailable'] as const)('refreshes MCP %s while open and preserves removal of selected references', async (change) => {
+ const off = vi.fn();
+ mocks.onMcpChanged.mockReturnValue(off);
+ renderSettings({ capabilities: capabilities({ mcpMode: 'allowlist', mcpServers: ['events'] }) });
+ expect(mocks.onMcpChanged).not.toHaveBeenCalled();
+ mocks.listCustomMcpServers.mockResolvedValue(sseCatalog('claude-code'));
+ await openCapabilities();
+ expect((screen.getByRole('checkbox', { name: /SSE Events/ }) as HTMLInputElement).checked).toBe(true);
+ let finishRefresh!: (result: CustomMcpListResult) => void;
+ mocks.listCustomMcpServers.mockImplementationOnce(() => new Promise((resolve) => { finishRefresh = resolve; }));
+ await act(async () => { mocks.onMcpChanged.mock.calls[0]![0](); });
+ // The old available catalog is invalidated immediately, while the selected ref stays removable.
+ expect((screen.getByRole('checkbox', { name: /events/ }) as HTMLInputElement).disabled).toBe(false);
+ await act(async () => { finishRefresh(change === 'deleted' ? { agentKind: 'claude-code', servers: [] }
+ : { ...sseCatalog('claude-code'), servers: sseCatalog('claude-code').servers.map((entry) => ({ ...entry, available: false })) }); });
+ const checkbox = screen.getByRole('checkbox', { name: change === 'deleted' ? /events/ : /SSE Events/ }) as HTMLInputElement;
+ expect(checkbox.checked).toBe(true);
+ expect(checkbox.disabled).toBe(false);
+ expect(mocks.updateBotProfile).not.toHaveBeenCalled();
+ fireEvent.click(checkbox);
+ await waitFor(() => expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { capabilities: { mcpServers: [] } }));
+ if (change === 'unavailable') expect(checkbox.disabled).toBe(true);
+ else expect(screen.queryByRole('checkbox', { name: /events/ })).toBeNull();
+ const details = screen.getByText('bots.capabilities.title').parentElement as HTMLDetailsElement;
+ await act(async () => { details.open = false; fireEvent(details, new Event('toggle')); });
+ expect(off).toHaveBeenCalledOnce();
+ });
+
+ it('invalidates selectable MCPs immediately and ignores an outdated refresh after another change', async () => {
+ mocks.listCustomMcpServers.mockResolvedValue(sseCatalog('claude-code'));
+ const off = vi.fn();
+ mocks.onMcpChanged.mockReturnValue(off);
+ const view = renderSettings();
+ await openCapabilities();
+ expect((screen.getByRole('checkbox', { name: /SSE Events/ }) as HTMLInputElement).disabled).toBe(false);
+ let finishOld!: (result: CustomMcpListResult) => void;
+ mocks.listCustomMcpServers.mockImplementationOnce(() => new Promise((resolve) => { finishOld = resolve; }))
+ .mockResolvedValue({ agentKind: 'claude-code', servers: [] });
+ await act(async () => { mocks.onMcpChanged.mock.calls[0]![0](); });
+ expect(screen.queryByRole('checkbox', { name: /SSE Events/ })).toBeNull();
+ await act(async () => { mocks.onMcpChanged.mock.calls[0]![0](); });
+ expect(mocks.listCustomMcpServers).toHaveBeenCalledTimes(3);
+ await act(async () => { finishOld(sseCatalog('claude-code')); });
+ expect(screen.queryByRole('checkbox', { name: /SSE Events/ })).toBeNull();
+ expect(mocks.updateBotProfile).not.toHaveBeenCalled();
+ view.unmount();
+ expect(off).toHaveBeenCalledOnce();
+ });
+
it('refreshes on a local model-chain edit and discards the preceding catalog response', async () => {
let finishOld!: (value: CustomMcpListResult) => void;
mocks.listCustomMcpServers.mockImplementationOnce(() => new Promise((resolve) => { finishOld = resolve; }))