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 capabilities for the next-turn route

zqchris63088e10e8d7
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts
index b3ed62fc94..263db758e0 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts
@@ -1,9 +1,11 @@
import { describe, expect, it, vi } from 'vitest';
import { createBotModelRouteReconciler } from '../botModelRouteReconciler';
+import type { BotModelRoute } from '../../../shared/botModelChain';
+import type { SessionRuntimeProfile } from '../sessionRuntimeControl';
function harness() {
let owner = 'owner-a';
- const state = {
+ const state: { chain: BotModelRoute[]; current: SessionRuntimeProfile; hasRuntimeOverride: boolean; next?: SessionRuntimeProfile } = {
chain: [{ harness: 'codex' as const, model: 'luna', providerId: 'xd', effort: 'medium', fastMode: false }],
current: { agentKind: 'pi' as const, model: 'glm', providerId: 'xd', effort: 'high', fastMode: false },
hasRuntimeOverride: false,
@@ -15,6 +17,52 @@ function harness() {
}
describe('permanent Bot model selection', () => {
+ it('previews the preserved effective or pending fallback without changing the runtime', async () => {
+ const h = harness();
+ h.state.hasRuntimeOverride = true;
+ expect(await h.reconcile.preview('canonical')).toEqual(h.state.current);
+ h.state.next = { ...h.state.current, agentKind: 'claude-code', model: 'pending' };
+ expect(await h.reconcile.preview('canonical')).toEqual(h.state.next);
+ expect(h.apply).not.toHaveBeenCalled();
+ });
+ it('previews a draft and then saved chain without consuming the next-send change', async () => {
+ const h = harness();
+ h.state.hasRuntimeOverride = true;
+ await h.reconcile('canonical');
+ const draft: BotModelRoute[] = [{ ...h.state.chain[0]!, harness: 'claude', model: 'new-primary' }];
+ const expected = expect.objectContaining({ agentKind: 'claude-code', model: 'new-primary' });
+ expect(await h.reconcile.preview('canonical', draft)).toEqual(expected);
+ expect(h.apply).not.toHaveBeenCalled();
+ expect(await h.reconcile.preview('canonical')).toEqual(h.state.current);
+ h.state.chain = draft;
+ expect(await h.reconcile.preview('canonical', draft)).toEqual(expected);
+ expect(h.apply).not.toHaveBeenCalled();
+ await h.reconcile('canonical');
+ expect(h.apply).toHaveBeenCalledWith('canonical', expected, h.state.current);
+ h.state.next = { ...h.state.current, model: 'new-fallback' };
+ expect(await h.reconcile.preview('canonical', draft)).toEqual(h.state.next);
+ });
+ it('invalidates fallback when a later chain candidate changes, even with the same primary', async () => {
+ const h = harness();
+ h.state.hasRuntimeOverride = true;
+ await h.reconcile('canonical');
+ const draft: BotModelRoute[] = [...h.state.chain, { ...h.state.chain[0]!, harness: 'pi', model: 'secondary' }];
+ expect(await h.reconcile.preview('canonical', draft)).toMatchObject({ agentKind: 'codex', model: 'luna' });
+ expect(h.apply).not.toHaveBeenCalled();
+ });
+ it('normalizes draft chains the same way as the persisted profile', async () => {
+ const h = harness();
+ h.state.hasRuntimeOverride = true;
+ await h.reconcile('canonical');
+ expect(await h.reconcile.preview('canonical', [...h.state.chain, ...h.state.chain])).toEqual(h.state.current);
+ expect(h.apply).not.toHaveBeenCalled();
+ });
+ it('rejects an owner change during a preview', async () => {
+ const h = harness();
+ h.read.mockImplementationOnce(async () => { h.changeOwner(); return h.state; });
+ await expect(h.reconcile.preview('canonical')).rejects.toThrow('owner changed');
+ expect(h.apply).not.toHaveBeenCalled();
+ });
it('applies the configured harness before the first send after restart', async () => {
const h = harness();
await h.reconcile('canonical');
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts
index adf1ad9aeb..80b25b8730 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts
@@ -66,6 +66,7 @@ function mountDb(): void {
function makeDeps(over: Partial<McpHandlerDeps> = {}): McpHandlerDeps {
return {
listMcpServers: vi.fn(async () => []),
+ resolveBotAgentKind: vi.fn(async () => 'claude-code' as const),
refreshProviders: vi.fn(async () => {}),
broadcastChanged: vi.fn(() => {}),
invalidateCodex: vi.fn(async () => {}),
@@ -116,13 +117,41 @@ describe('mcp:custom:* CRUD handlers', () => {
const result = await harness.invoke(MAKER_INVOKE.MCP_CUSTOM_LIST, { agentKind });
expect(deps.listMcpServers).toHaveBeenCalledWith({ agentKind });
- expect(result).toEqual({ servers: rawList.map((server) => ({
+ expect(result).toEqual({ agentKind, servers: rawList.map((server) => ({
...server, available: server.id === 'mytools' || (server.id === 'events' && agentKind !== 'codex'),
})) });
},
);
- it.each([null, {}, { agentKind: 'unknown' }])('rejects an invalid catalog context: %j', async (context) => {
+ it('uses the canonical next-turn route instead of the renderer hint', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const chain = [{ harness: 'claude' as const, model: 'claude-x', providerId: null, effort: '', fastMode: false }];
+ const deps = makeDeps({ resolveBotAgentKind: vi.fn(async () => 'codex' as const) });
+ registerMcpHandlers(harness, deps);
+ expect(await harness.invoke(MAKER_INVOKE.MCP_CUSTOM_LIST, {
+ agentKind: 'claude-code', botSessionId: 'canonical', modelChain: chain,
+ })).toEqual({ agentKind: 'codex', servers: [] });
+ expect(deps.resolveBotAgentKind).toHaveBeenCalledWith('canonical', chain);
+ expect(deps.listMcpServers).toHaveBeenCalledWith({ agentKind: 'codex' });
+ expect(deps.refreshProviders).not.toHaveBeenCalled();
+ });
+
+ it('does not fall back to a renderer hint for a missing canonical task', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const deps = makeDeps({ resolveBotAgentKind: vi.fn(async () => null) });
+ registerMcpHandlers(harness, deps);
+ await expect(harness.invoke(MAKER_INVOKE.MCP_CUSTOM_LIST, {
+ agentKind: 'claude-code', botSessionId: 'other-task',
+ })).rejects.toThrow(/NOT_FOUND/);
+ expect(deps.listMcpServers).not.toHaveBeenCalled();
+ });
+
+ it.each([null, {}, { agentKind: 'unknown' },
+ { agentKind: 'codex', modelChain: [] },
+ { agentKind: 'codex', botSessionId: 'canonical', modelChain: [{ harness: 'unknown', model: 'x' }] },
+ ])('rejects an invalid catalog context: %j', async (context) => {
mountDb();
const harness = new IpcHarness();
const deps = makeDeps();
diff --git a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts
index d0640e02be..18b95c26aa 100644
--- a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts
+++ b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts
@@ -1,5 +1,5 @@
import type { AgentKind } from '@cindy/maker-core';
-import type { BotModelRoute } from '../../shared/botModelChain.js';
+import { normalizeBotModelChain, type BotModelRoute } from '../../shared/botModelChain.js';
interface RuntimeRoute {
agentKind: AgentKind;
@@ -13,6 +13,20 @@ interface BotRouteState {
chain: BotModelRoute[];
current: RuntimeRoute;
hasRuntimeOverride: boolean;
+ next?: RuntimeRoute;
+}
+
+function configuredRoute(state: BotRouteState, previous: string | undefined, chain = state.chain): RuntimeRoute | null {
+ const key = JSON.stringify(chain);
+ const isDraftChange = key !== JSON.stringify(state.chain);
+ if (!isDraftChange && state.hasRuntimeOverride && (previous === undefined || previous === key)) return null;
+ const primary = chain[0];
+ if (!primary) return null;
+ return {
+ agentKind: primary.harness === 'claude' ? 'claude-code' : primary.harness,
+ model: primary.model, providerId: primary.providerId,
+ effort: primary.effort || null, fastMode: primary.fastMode,
+ };
}
/** Apply the permanent profile through ordinary Session model/switch controls.
@@ -27,13 +41,17 @@ export function createBotModelRouteReconciler(deps: {
let owner: string | undefined;
const configured = new Map<string, string>();
const inFlight = new Map<string, Promise<void>>();
- return async (sessionId: string): Promise<void> => {
+ const syncOwner = () => {
const epoch = deps.ownerEpoch();
if (owner !== epoch) {
owner = epoch;
configured.clear();
inFlight.clear();
}
+ return epoch;
+ };
+ const reconcile = async (sessionId: string): Promise<void> => {
+ const epoch = syncOwner();
const existing = inFlight.get(sessionId);
if (existing) return existing;
const operation = (async () => {
@@ -44,19 +62,11 @@ export function createBotModelRouteReconciler(deps: {
return;
}
const key = JSON.stringify(state.chain);
- const previous = configured.get(sessionId);
- if (state.hasRuntimeOverride && (previous === undefined || previous === key)) {
+ const route = configuredRoute(state, configured.get(sessionId));
+ if (!route) {
configured.set(sessionId, key);
return;
}
- const primary = state.chain[0];
- const route: RuntimeRoute = {
- agentKind: primary.harness === 'claude' ? 'claude-code' : primary.harness,
- model: primary.model,
- providerId: primary.providerId,
- effort: primary.effort || null,
- fastMode: primary.fastMode,
- };
const current = state.current;
if (route.agentKind !== current.agentKind || route.model !== current.model
|| route.providerId !== current.providerId || route.effort !== current.effort
@@ -71,4 +81,16 @@ export function createBotModelRouteReconciler(deps: {
if (inFlight.get(sessionId) === operation) inFlight.delete(sessionId);
}
};
+ return Object.assign(reconcile, {
+ /** Read-only preview: sharing the send decision must not consume a profile change. */
+ async preview(sessionId: string, draftChain?: BotModelRoute[]): Promise<RuntimeRoute | null> {
+ const epoch = syncOwner();
+ await inFlight.get(sessionId);
+ const state = await deps.read(sessionId);
+ if (deps.ownerEpoch() !== epoch) throw new Error('Bot model route owner changed');
+ if (!state?.chain.length) return null;
+ return configuredRoute(state, configured.get(sessionId), draftChain ? normalizeBotModelChain(draftChain) : undefined)
+ ?? state.next ?? state.current;
+ },
+ });
}
diff --git a/apps/desktop/src/main/maker-ipc/mcpHandlers.ts b/apps/desktop/src/main/maker-ipc/mcpHandlers.ts
index c3c37f786c..8e57060e5f 100644
--- a/apps/desktop/src/main/maker-ipc/mcpHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/mcpHandlers.ts
@@ -11,8 +11,10 @@
* handler body 可脱 Electron 用 IpcHarness + 内存 db 直接 invoke 单测(规则 14)。
*/
-import { requireEnum, requireObject, throwIpcError } from '../utils/ipcValidate.js';
+import { z } from 'zod';
+import { throwIpcError } from '../utils/ipcValidate.js';
import type { CustomMcpListContext } from '../../shared/customMcp.js';
+import { BOT_MODEL_CHAIN_MAX, type BotModelRoute } from '../../shared/botModelChain.js';
import type { BotProfileRuntimeDeps } from './botProfileRuntime.js';
import {
createCustomMcpServer,
@@ -29,6 +31,7 @@ import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
export interface McpHandlerDeps {
/** Same registered runtime catalog used by Bot capability tools and hydration. */
listMcpServers(context: CustomMcpListContext): ReturnType<NonNullable<BotProfileRuntimeDeps['listMcpServers']>>;
+ resolveBotAgentKind(sessionId: string, chain?: BotModelRoute[]): Promise<CustomMcpListContext['agentKind'] | null>;
/** CRUD 成功后刷新 agent mcpProviders 数组(生产 = refreshCustomMcpProviders)。 */
refreshProviders(): Promise<void>;
/** CRUD 成功后广播变更(生产 = 向所有窗口 send MCP_CHANGED)。 */
@@ -51,18 +54,33 @@ export interface McpHandlerDeps {
getReservedMcpIds?(): string[];
}
+const listContextSchema = z.object({
+ agentKind: z.enum(['claude-code', 'codex', 'pi']),
+ botSessionId: z.string().min(1).optional(),
+ modelChain: z.array(z.object({
+ harness: z.enum(['claude', 'codex', 'pi']),
+ model: z.string().trim().min(1),
+ providerId: z.string().nullable(),
+ effort: z.string(),
+ fastMode: z.boolean(),
+ })).min(1).max(BOT_MODEL_CHAIN_MAX).optional(),
+}).refine((value) => value.modelChain === undefined || value.botSessionId !== undefined);
+
export function registerMcpHandlers(registry: IpcHandlerRegistry, deps: McpHandlerDeps): void {
registry.handle(MAKER_INVOKE.MCP_CUSTOM_LIST, async (_event, context: unknown) => {
- const agentKind = context === undefined ? undefined : requireEnum(
- requireObject(context, 'context').agentKind, ['claude-code', 'codex', 'pi'] as const, 'agentKind',
- );
+ const parsed = context === undefined ? undefined : listContextSchema.safeParse(context);
+ if (parsed && !parsed.success) throwIpcError('INVALID_PARAMS', 'Invalid MCP catalog context');
+ const input = parsed?.data;
+ const agentKind = input?.botSessionId
+ ? await deps.resolveBotAgentKind(input.botSessionId, input.modelChain) : input?.agentKind;
+ if (input?.botSessionId && !agentKind) throwIpcError('NOT_FOUND', 'Canonical Bot task not found');
const servers = await listCustomMcpServers();
- if (agentKind === undefined) return { servers };
+ if (!agentKind) return { servers };
const catalog = await deps.listMcpServers({ agentKind });
const available = new Set(catalog
.filter((entry) => entry.source === 'custom' && entry.available !== false)
.map((entry) => entry.name));
- return { servers: servers.map((server) => ({ ...server, available: available.has(server.id) })) };
+ return { agentKind, servers: servers.map((server) => ({ ...server, available: available.has(server.id) })) };
});
// CRUD 成功后统一收尾:刷新 provider 数组 + 广播 + 失效 Codex app-server。
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index d46a940cca..a03b526fd5 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -5493,6 +5493,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// (下次新建会话生效)并广播 MCP_CHANGED 让设置页列表 live 刷新。
registerMcpHandlers(createElectronIpcHandlerRegistry(), {
listMcpServers: listBotRuntimeMcpServers,
+ resolveBotAgentKind: async (sessionId, chain) =>
+ (await reconcileBotModelRoute.preview(sessionId, chain))?.agentKind ?? null,
refreshProviders: () => refreshCustomMcpProviders(),
broadcastChanged: () => broadcastToAllWindows(MAKER_PUSH.MCP_CHANGED, {}),
// 内置 server 名对自定义 MCP 是保留名:撞名会在装配层顶替内置 server 并继承
@@ -10628,6 +10630,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
fastMode: live ? getSessionFastMode(sessionId) : !!row.fastMode,
},
hasRuntimeOverride: control.effectiveOverride !== null || control.pending !== null,
+ next: control.pending?.profile ?? control.effectiveOverride ?? undefined,
};
},
apply: async (sessionId, route, current) => {
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 6681ebcab8..d3c420a0cc 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5678,9 +5678,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
onLocalModelInstallProgress: fanOutMakerLocalModelInstallProgress,
// 自定义 MCP 服务器配置 CRUD(可选 bearer token 另走通用 safeStorage IPC,不经这里)。
- listCustomMcpServers: (context?: import('../shared/customMcp').CustomMcpListContext): Promise<{
- servers: import('../shared/customMcp').CustomMcpListEntry[];
- }> => context === undefined
+ listCustomMcpServers: (context?: import('../shared/customMcp').CustomMcpListContext): Promise<import('../shared/customMcp').CustomMcpListResult> => context === undefined
? ipcRenderer.invoke('maker:mcp:custom:list')
: ipcRenderer.invoke('maker:mcp:custom:list', context),
createCustomMcpServer: (
diff --git a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx
index a63ea09d45..32c52b85f2 100644
--- a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx
@@ -1,10 +1,13 @@
-import { useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { useBotTranslation } from './botPronounContext';
import type { BotCapabilities, BotProfile } from './botStore';
import * as sessionService from '@/lib/sessionService';
+import { onPatch } from '@/lib/sessionsBus';
+import type { Session } from '@/lib/ccAgent.types';
import {
getDataOwnerGeneration,
isDataOwnerGenerationCurrent,
+ isDataOwnerPushCurrent,
} from '@/contexts/dataOwnerGeneration';
type Kind = 'skill' | 'mcp' | 'toolset';
@@ -24,68 +27,106 @@ export function BotCapabilitySettings({
onChange: (kind: Kind, values: string[]) => void;
}) {
const { t } = useBotTranslation();
- const [entries, setEntries] = useState<Partial<Record<Kind, Entry[]>>>({});
+ const [catalog, setCatalog] = useState<{ key: string; entries: Partial<Record<Kind, Entry[]>> }>({ key: '', entries: {} });
+ const [open, setOpen] = useState(false);
+ const [revision, setRevision] = useState(0);
+ const requestRef = useRef(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
const [query, setQuery] = useState('');
const selected = { skill: skills, mcp: capabilities.mcpServers, toolset: capabilities.toolsets };
- const load = async () => {
- if (busy) return;
+ const modelChainKey = JSON.stringify(capabilities.modelChain);
+ const catalogKey = JSON.stringify([bot.id, bot.canonicalSessionId, modelChainKey, revision, open]);
+ // Invalidate during render as well as effect cleanup: stale checkboxes must never stay selectable.
+ const entries = catalog.key === catalogKey ? catalog.entries : {};
+ const refresh = useCallback(() => {
+ requestRef.current += 1;
+ setRevision((value) => value + 1);
+ }, []);
+
+ useEffect(() => {
+ if (!open) return;
+ const changed = (sessionId: string, patch: Partial<Session>) => {
+ if (sessionId !== bot.canonicalSessionId) return;
+ if (['agentKind', 'model', 'providerId', 'effort', 'fastMode', 'runtimeGeneration',
+ 'runtimeEffective', 'runtimePending', 'workingDir', 'remoteHostId'].some((key) => key in patch)) refresh();
+ };
+ const offLocal = onPatch(changed);
+ const offPush = window.electronAPI.localDb?.sessionsPush?.onPatched(({ sessionId, patch }, stamp) => {
+ if (isDataOwnerPushCurrent(stamp)) changed(sessionId, patch);
+ });
+ return () => { offLocal(); offPush?.(); };
+ }, [open, bot.canonicalSessionId, refresh]);
+
+ useEffect(() => {
+ if (!open) return;
+ const request = ++requestRef.current;
const owner = getDataOwnerGeneration();
+ const isCurrent = () => requestRef.current === request && isDataOwnerGenerationCurrent(owner);
setBusy(true);
setError(false);
- try {
- if (!bot.canonicalSessionId) throw new Error('Missing canonical task');
- const session = await sessionService.get(bot.canonicalSessionId);
- if (!isDataOwnerGenerationCurrent(owner)) return;
- const agentKind = capabilities.harness === 'claude' ? 'claude-code' : capabilities.harness;
- const api = window.electronAPI.maker;
- const results = await Promise.allSettled([
- api.listAgentSkills(agentKind, {
- workingDir: session.workingDir ?? undefined,
- remoteHostId: session.remoteHostId ?? undefined,
- }),
- api.listCustomMcpServers({ agentKind }),
- api.plugins.list(session.workingDir ?? undefined, true, {
- botId: bot.id, agentKind, remoteHostId: session.remoteHostId,
- }),
- ]);
- if (!isDataOwnerGenerationCurrent(owner)) return;
- const [skillResult, mcpResult, toolsetResult] = results;
- const next: Partial<Record<Kind, Entry[]>> = {};
- if (skillResult.status === 'fulfilled' && skillResult.value.success)
- next.skill = (skillResult.value.skills ?? []).map((item) => ({
- id: item.name,
- name: item.name,
- available: item.enabled !== false && item.runtimeStatus !== 'failed',
- }));
- if (mcpResult.status === 'fulfilled')
- next.mcp = mcpResult.value.servers.map((item) => ({
+ const load = async () => {
+ try {
+ if (!bot.canonicalSessionId) throw new Error('Missing canonical task');
+ const session = await sessionService.get(bot.canonicalSessionId);
+ if (!isCurrent()) return;
+ const api = window.electronAPI.maker;
+ const mcpResult = await api.listCustomMcpServers({
+ agentKind: session.runtimePending?.profile.agentKind ?? session.runtimeEffective?.agentKind
+ ?? (session.agentKind === 'codex' || session.agentKind === 'pi' ? session.agentKind : 'claude-code'),
+ botSessionId: bot.canonicalSessionId,
+ modelChain: JSON.parse(modelChainKey),
+ });
+ if (!isCurrent()) return;
+ const agentKind = mcpResult.agentKind;
+ if (!agentKind) throw new Error('Missing next-turn route');
+ const results = await Promise.allSettled([
+ api.listAgentSkills(agentKind, {
+ workingDir: session.workingDir ?? undefined,
+ remoteHostId: session.remoteHostId ?? undefined,
+ }),
+ api.plugins.list(session.workingDir ?? undefined, true, {
+ botId: bot.id, agentKind, remoteHostId: session.remoteHostId,
+ }),
+ ]);
+ if (!isCurrent()) return;
+ const [skillResult, toolsetResult] = results;
+ const next: Partial<Record<Kind, Entry[]>> = {};
+ if (skillResult.status === 'fulfilled' && skillResult.value.success)
+ next.skill = (skillResult.value.skills ?? []).map((item) => ({
+ id: item.name,
+ name: item.name,
+ available: item.enabled !== false && item.runtimeStatus !== 'failed',
+ }));
+ next.mcp = mcpResult.servers.map((item) => ({
id: item.id,
name: item.name,
available: item.available === true,
}));
- if (toolsetResult.status === 'fulfilled')
- next.toolset = toolsetResult.value
- .filter((item) => !['memory', 'xdt_helper', 'collab'].includes(item.id))
- .map((item) => ({
- id: item.id,
- name: item.name,
- available: item.available === true,
- }));
- setEntries(next);
- setError(kinds.some((kind) => !next[kind]));
- } catch {
- if (isDataOwnerGenerationCurrent(owner)) setError(true);
- } finally {
- if (isDataOwnerGenerationCurrent(owner)) setBusy(false);
- }
- };
+ if (toolsetResult.status === 'fulfilled')
+ next.toolset = toolsetResult.value
+ .filter((item) => !['memory', 'xdt_helper', 'collab'].includes(item.id))
+ .map((item) => ({
+ id: item.id,
+ name: item.name,
+ available: item.available === true,
+ }));
+ setCatalog({ key: catalogKey, entries: next });
+ setError(kinds.some((kind) => !next[kind]));
+ } catch {
+ if (isCurrent()) setError(true);
+ } finally {
+ if (isCurrent()) setBusy(false);
+ }
+ };
+ void load();
+ return () => { requestRef.current += 1; };
+ }, [open, catalogKey, bot.id, bot.canonicalSessionId, modelChainKey]);
return (
<details
className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]"
onToggle={(event) => {
- if (event.currentTarget.open) void load();
+ setOpen(event.currentTarget.open);
}}
>
<summary className="cursor-pointer px-4 py-3 text-12 font-medium text-[var(--text-secondary)]">
@@ -105,7 +146,7 @@ export function BotCapabilitySettings({
{error ? (
<button
type="button"
- onClick={() => void load()}
+ onClick={refresh}
className="rounded-full px-4 py-2 text-12 text-[var(--text-danger)]"
>
{t('bots.retry')}
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 1acf6eaa4b..2a4ac0c70f 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
@@ -3,7 +3,8 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BotCapabilities, BotProfile } from '../botStore';
-import type { CustomMcpListContext, CustomMcpListEntry } from '../../../../shared/customMcp';
+import type { CustomMcpListContext, CustomMcpListResult } from '../../../../shared/customMcp';
+import type { Session } from '@/lib/ccAgent.types';
const translate = (key: string, opts?: Record<string, unknown>) =>
opts ? `${key}:${JSON.stringify(opts)}` : key;
@@ -12,7 +13,11 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));
const mocks = vi.hoisted(() => ({
navigate: vi.fn(),
initialSearch: '' as string,
- listCustomMcpServers: vi.fn<(context?: CustomMcpListContext) => Promise<{ servers: CustomMcpListEntry[] }>>(),
+ listCustomMcpServers: vi.fn<(context?: CustomMcpListContext) => Promise<CustomMcpListResult>>(),
+ getSession: vi.fn<() => Promise<Partial<Session>>>(),
+ onSessionPatched: vi.fn(),
+ listAgentSkills: vi.fn(),
+ listToolsets: vi.fn(),
updateBotProfile: vi.fn(async (_id: string, patch: Record<string, unknown>) => ({
id: 'bot-1',
currentVersion: 1,
@@ -60,7 +65,7 @@ vi.mock('../BotLifecycleSettings', () => ({
BotLifecycleSettings: () => <div data-testid="bot-lifecycle-settings" />,
}));
vi.mock('@/components/new-chat/ModelSelector', () => ({
- ModelSelector: () => <div data-testid="model-selector" />,
+ ModelSelector: ({ onUnifiedSelect }: { onUnifiedSelect: (selection: unknown) => void }) => <button data-testid="model-selector" onClick={() => onUnifiedSelect({ engine: 'codex', modelId: 'codex-x', providerId: null, effort: 'medium', fast: false })}>Select Codex</button>,
}));
vi.mock('@/hooks/useAvailableAgents', () => ({
useAvailableAgents: () => ({ availableVendors: new Set(['cc', 'codex', 'pi']), loaded: true }),
@@ -76,7 +81,7 @@ vi.mock('@/state/newMakerDraft', () => ({
}),
}));
-vi.mock('@/lib/sessionService', () => ({ get: async () => ({ workingDir: '/bot/workspace' }) }));
+vi.mock('@/lib/sessionService', () => ({ get: mocks.getSession }));
import { BotSettings } from '../BotsHomeView';
@@ -155,21 +160,29 @@ beforeEach(() => {
mocks.openPath.mockReset();
mocks.openPath.mockResolvedValue({ success: true });
mocks.initialSearch = '';
+ mocks.getSession.mockReset().mockResolvedValue({ agentKind: 'cc', workingDir: '/bot/workspace' });
+ mocks.onSessionPatched.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 },
+ { id: 'scheduler', name: 'Scheduler', effectiveEnabled: true, available: true },
+ { id: 'contacts', name: 'Contacts', effectiveEnabled: true, available: false },
+ ]);
mocks.listCustomMcpServers.mockReset();
- mocks.listCustomMcpServers.mockResolvedValue({ servers: [
+ mocks.listCustomMcpServers.mockImplementation(async (context) => ({
+ agentKind: context?.modelChain?.[0]?.harness === 'codex' ? 'codex'
+ : context?.modelChain?.[0]?.harness === 'pi' ? 'pi' : 'claude-code',
+ servers: [
{ id: 'shared-docs', name: 'Shared Docs', transport: 'http', url: 'https://example.com/mcp', headers: {}, available: true },
{ id: 'bad-headers', name: 'Legacy MCP', transport: 'http', url: 'https://example.com/mcp', headers: {}, available: false },
- ] });
+ ] }));
(window as unknown as { electronAPI: unknown }).electronAPI = {
openPath: mocks.openPath,
+ localDb: { sessionsPush: { onPatched: mocks.onSessionPatched } },
maker: {
- listAgentSkills: async () => ({ success: true, skills: [{ name: 'release-check' }] }),
+ listAgentSkills: mocks.listAgentSkills,
listCustomMcpServers: mocks.listCustomMcpServers,
- 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 },
- ] },
+ plugins: { list: mocks.listToolsets },
},
};
});
@@ -300,12 +313,72 @@ describe('same-Bot capability updates while editing settings', () => {
{ name: 'Documents', selected: { capabilities: capabilities({ toolsetMode: 'allowlist', toolsets: ['docs'] }) }, empty: { capabilities: capabilities({ toolsetMode: 'allowlist' }) }, patch: { capabilities: { toolsets: [] } }, addPatch: { capabilities: { toolsets: ['docs'] } } },
];
+ function sseCatalog(agentKind: 'claude-code' | 'codex'): CustomMcpListResult {
+ return { agentKind, servers: [{ id: 'events', name: 'SSE Events', transport: 'sse', url: 'https://example.com/mcp', headers: {}, available: agentKind !== 'codex' }] };
+ }
+
+ it('uses the effective canonical fallback for every catalog despite a Claude primary', async () => {
+ mocks.getSession.mockResolvedValue({ agentKind: 'cc', workingDir: '/bot/workspace', runtimeEffective: { agentKind: 'codex', model: 'codex-x', providerId: null, effort: 'medium', fastMode: false } });
+ mocks.listCustomMcpServers.mockResolvedValue(sseCatalog('codex'));
+ renderSettings();
+ await openCapabilities();
+ expect(mocks.listCustomMcpServers).toHaveBeenLastCalledWith(expect.objectContaining({ agentKind: 'codex', botSessionId: 'bot-1-chat', modelChain: capabilities().modelChain }));
+ expect(mocks.listAgentSkills).toHaveBeenLastCalledWith('codex', expect.anything());
+ expect(mocks.listToolsets).toHaveBeenLastCalledWith('/bot/workspace', true, expect.objectContaining({ agentKind: 'codex' }));
+ expect((screen.getByRole('checkbox', { name: /SSE Events/ }) as HTMLInputElement).disabled).toBe(true);
+ });
+
+ it('refreshes an open panel on pending fallback and ignores unrelated session pushes', async () => {
+ mocks.listCustomMcpServers.mockResolvedValue(sseCatalog('claude-code'));
+ renderSettings();
+ await openCapabilities();
+ expect((screen.getByRole('checkbox', { name: /SSE Events/ }) as HTMLInputElement).disabled).toBe(false);
+ const patched = mocks.onSessionPatched.mock.calls[0]![0];
+ await act(async () => {
+ patched({ sessionId: 'other', patch: { agentKind: 'codex' } });
+ patched({ sessionId: 'bot-1-chat', patch: { totalCostUsd: 1 } });
+ });
+ expect(mocks.listCustomMcpServers).toHaveBeenCalledTimes(1);
+ const pending = { generation: 2, source: 'fallback' as const, profile: { agentKind: 'codex' as const, model: 'codex-x', providerId: null, effort: 'medium' as const, fastMode: false } };
+ mocks.getSession.mockResolvedValue({ agentKind: 'cc', workingDir: '/bot/workspace', runtimePending: pending });
+ mocks.listCustomMcpServers.mockResolvedValue(sseCatalog('codex'));
+ await act(async () => { patched({ sessionId: 'bot-1-chat', patch: { runtimePending: pending } }); });
+ expect(mocks.listCustomMcpServers).toHaveBeenCalledTimes(2);
+ expect(mocks.listCustomMcpServers).toHaveBeenLastCalledWith(expect.objectContaining({ agentKind: 'codex' }));
+ expect((screen.getByRole('checkbox', { name: /SSE Events/ }) as HTMLInputElement).disabled).toBe(true);
+ });
+
+ 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; }))
+ .mockResolvedValue(sseCatalog('codex'));
+ mocks.updateBotProfile.mockImplementationOnce(() => new Promise(() => {}));
+ renderSettings();
+ await openCapabilities();
+ await act(async () => { fireEvent.click(screen.getByTestId('model-selector')); });
+ expect(mocks.listCustomMcpServers).toHaveBeenLastCalledWith(expect.objectContaining({ modelChain: [expect.objectContaining({ harness: 'codex' })] }));
+ expect((screen.getByRole('checkbox', { name: /SSE Events/ }) as HTMLInputElement).disabled).toBe(true);
+ await act(async () => { finishOld(sseCatalog('claude-code')); });
+ expect((screen.getByRole('checkbox', { name: /SSE Events/ }) as HTMLInputElement).disabled).toBe(true);
+ expect(mocks.listAgentSkills).toHaveBeenCalledTimes(1);
+ expect(mocks.listAgentSkills).toHaveBeenLastCalledWith('codex', expect.anything());
+ });
+
+ it('refreshes when an external model-chain update arrives without reopening the panel', async () => {
+ const view = renderSettings();
+ await openCapabilities();
+ const chain = [{ ...capabilities().modelChain[0]!, harness: 'pi' as const, model: 'pi-x' }];
+ await act(async () => { view.rerender(<BotSettings bot={bot({ currentVersion: 2, capabilities: capabilities({ harness: 'pi', modelChain: chain }) })} onBack={view.onBack} onOpenSession={view.onOpenSession} />); });
+ expect(mocks.listCustomMcpServers).toHaveBeenLastCalledWith(expect.objectContaining({ modelChain: chain }));
+ expect(mocks.listAgentSkills).toHaveBeenLastCalledWith('pi', expect.anything());
+ });
+
it.each(['claude', 'codex', 'pi'] as const)('uses the %s runtime catalog and keeps unavailable MCP references removable', async (harness) => {
vi.useFakeTimers();
- const profile = capabilities({ harness, mcpMode: 'allowlist' });
+ const profile = capabilities({ harness, modelChain: [{ ...capabilities().modelChain[0]!, harness }], mcpMode: 'allowlist' });
const view = renderSettings({ capabilities: profile });
await openCapabilities();
- expect(mocks.listCustomMcpServers).toHaveBeenCalledWith({ agentKind: harness === 'claude' ? 'claude-code' : harness });
+ expect(mocks.listCustomMcpServers).toHaveBeenCalledWith({ agentKind: 'claude-code', botSessionId: 'bot-1-chat', modelChain: profile.modelChain });
const unavailable = screen.getByRole('checkbox', { name: /Legacy MCP/ }) as HTMLInputElement;
expect(unavailable.disabled).toBe(true);
expect(unavailable.checked).toBe(false);
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index bf1fb2a91f..d7674056e0 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5170,9 +5170,7 @@ interface ElectronAPI {
onProvidersChanged: (cb: () => void) => () => void;
// 自定义 MCP 服务器配置 CRUD(可选 bearer token 另走通用 safeStorage IPC,不经这里)。
- listCustomMcpServers: (context?: import('../shared/customMcp').CustomMcpListContext) => Promise<{
- servers: import('../shared/customMcp').CustomMcpListEntry[];
- }>;
+ listCustomMcpServers: (context?: import('../shared/customMcp').CustomMcpListContext) => Promise<import('../shared/customMcp').CustomMcpListResult>;
createCustomMcpServer: (
config: import('../shared/customMcp').CustomMcpConfig,
) => Promise<{ ok: true }>;
diff --git a/apps/desktop/src/shared/customMcp.ts b/apps/desktop/src/shared/customMcp.ts
index 217207d380..fbd28f0ce1 100644
--- a/apps/desktop/src/shared/customMcp.ts
+++ b/apps/desktop/src/shared/customMcp.ts
@@ -8,6 +8,7 @@
*/
import type { AgentKind } from '@cindy/maker-core';
+import type { BotModelRoute } from './botModelChain.js';
/** 支持的 transport 类型。 */
export const MCP_TRANSPORTS = ['http', 'sse'] as const;
@@ -30,9 +31,18 @@ export interface CustomMcpConfig {
/** Optional runtime projection for capability pickers; omitted for configuration CRUD. */
export interface CustomMcpListContext {
agentKind: AgentKind;
+ /** Preview a canonical Bot's next turn, optionally including an unsaved model chain. */
+ botSessionId?: string;
+ modelChain?: BotModelRoute[];
}
export interface CustomMcpListEntry extends CustomMcpConfig {
/** Present only when a runtime context was requested. */
available?: boolean;
}
+
+export interface CustomMcpListResult {
+ servers: CustomMcpListEntry[];
+ /** Authoritative route used for this catalog; absent for raw configuration queries. */
+ agentKind?: AgentKind;
+}