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): validate delegation and capability snapshots at use time

zqchris9b949d2d7edb
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 3362289287..c6564ea8a7 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -7,6 +7,8 @@ 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 { findBotCapabilities, selectBotCapability } from '../../../maker-ipc/botCapabilityService';
+import { buildBotMcpCatalog } from '../../../maker-host/botMcpCatalog';
+import { CustomMcpProvider } from '../../../mcp-integrations/custom-mcp-provider';
import {
botDelegations,
@@ -100,7 +102,7 @@ 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: () => ['contacts', 'lsp'].map((id) => ({ id, name: id, description: id })),
+ getPlugins: () => ['memory', 'xdt_helper', 'contacts', 'lsp'].map((id) => ({ id, name: id, description: id })),
getEnableState: async () => ({ effectiveEnabled: true }),
}),
isBotToolsetAvailable: () => h.toolsetsAvailable,
@@ -1614,6 +1616,49 @@ describe('Bot canonical Session lifecycle', () => {
await expect(findBotCapabilities({ callerSessionId, kind: 'skill' })).resolves.toMatchObject({ capabilities: [{ id: 'release-check', joined: true }] });
});
+ it('revalidates saved MCP transports on fallback and restores them when switching back', async () => {
+ const configs = (['http', 'sse'] as const).map((transport) => ({
+ id: transport, name: transport, transport, url: `https://example.invalid/${transport}`,
+ headers: { Authorization: 'FAKE_SECRET' }, updatedAt: 1,
+ }));
+ const providers = configs.map((config) => new CustomMcpProvider(config, () => 'FAKE_TOKEN'));
+ await invoke('local-db:bots:update', {
+ id: 'bot-1', capabilities: { mcpServers: ['http', 'sse'], mcpMode: 'allowlist' },
+ });
+ const created = await invoke('local-db:bots:create-canonical-session', {
+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 2,
+ });
+ for (const agentKind of ['claude-code', 'codex', 'pi', 'claude-code'] as const) {
+ const opts: MakerSessionCreateOpts = {
+ id: created.session.id, agentKind, workingDir: created.session.workingDir,
+ workspaceKind: 'dialogue', model: 'test-model', permissionMode: 'auto',
+ };
+ const snapshot = await hydrateBotProfileRuntime(opts, {
+ listMcpServers: async ({ agentKind: actualRoute }) => {
+ const catalog = buildBotMcpCatalog({
+ agentKind: actualRoute, providers, builtinNames: [], customServers: configs,
+ });
+ for (const provider of providers) {
+ const context = { agentKind: actualRoute, workingDir: created.session.workingDir };
+ const serialized = actualRoute === 'codex'
+ ? provider.toCodexMcpConfig(context) : provider.toClaudeSdkConfig(context);
+ expect(catalog.find((entry) => entry.name === provider.name)?.available).toBe(serialized !== null);
+ }
+ expect(JSON.stringify(catalog)).not.toMatch(/FAKE_SECRET|FAKE_TOKEN|example.invalid|Authorization/);
+ return catalog;
+ },
+ });
+ expect(snapshot).toMatchObject({
+ configuredMcpServers: ['http', 'sse'],
+ resolvedMcpServers: agentKind === 'codex' ? ['http'] : ['http', 'sse'],
+ unavailableMcpServers: agentKind === 'codex' ? ['sse'] : [],
+ });
+ expect(opts.botRuntimeProfile?.mcpPolicy.catalog).toContainEqual(expect.objectContaining({
+ name: 'sse', available: agentKind !== 'codex',
+ }));
+ }
+ });
+
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 };
@@ -1627,6 +1672,36 @@ describe('Bot canonical Session lifecycle', () => {
await expect(selectBotCapability({ ...input, joined: false })).resolves.toMatchObject({ ok: true, joined: false });
});
+ it.each([false, true])('keeps fixed toolsets out of selection even with saved references: %s', async (savedReferences) => {
+ await invoke('local-db:bots:update', {
+ id: 'bot-1',
+ capabilities: { toolsets: savedReferences ? ['memory', 'xdt_helper', 'retired-toolset'] : [] },
+ });
+ const created = await invoke('local-db:bots:create-canonical-session', {
+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 2,
+ });
+ const input = { callerSessionId: created.session.id, kind: 'toolset' as const };
+ h.toolsetsAvailable = true;
+ const discovered = await findBotCapabilities(input);
+ expect(discovered.ok).toBe(true);
+ if (!discovered.ok) throw new Error(discovered.message);
+ for (const id of ['memory', 'xdt_helper']) {
+ expect(discovered.capabilities.some((item) => item.id === id)).toBe(false);
+ for (const joined of [true, false]) {
+ await expect(selectBotCapability({ ...input, id, joined })).resolves.toMatchObject({
+ ok: false, errorCode: 'CAPABILITY_NOT_SELECTABLE',
+ });
+ }
+ }
+ expect(h.sqlite!.prepare('SELECT current_version FROM bot_profiles WHERE id = ?').pluck().get('bot-1')).toBe(2);
+ if (savedReferences) {
+ expect(discovered.capabilities).toContainEqual({
+ id: 'retired-toolset', name: 'retired-toolset', description: '', available: false, joined: true,
+ });
+ await expect(selectBotCapability({ ...input, id: 'retired-toolset', joined: false })).resolves.toMatchObject({ ok: true });
+ }
+ });
+
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' });
@@ -2835,6 +2910,38 @@ describe('Bot Session task end-to-end runtime', () => {
}
});
+ it.each(['ask', 'auto', null])('uses stable permission after asynchronous workspace preparation: %s', async (settledMode) => {
+ await seedPair();
+ let permission: string | null = 'bypassPermissions';
+ let finishPreparation!: () => void;
+ const preparation = new Promise<void>((resolve) => { finishPreparation = resolve; });
+ h.ensureGit.mockImplementationOnce(async () => { await preparation; return undefined; });
+ const runtime = createDelegationRuntime({ readCallerPermission: () => permission });
+ const starting = runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Run the requested checks.' });
+ try {
+ await vi.waitFor(() => expect(h.ensureGit).toHaveBeenCalledWith(expect.objectContaining({ source: 'bot-delegation' })));
+ permission = settledMode;
+ finishPreparation();
+ const result = await starting;
+ if (settledMode === null) {
+ expect(result).toMatchObject({ ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE' });
+ expect(h.sqlite!.prepare('SELECT count(*) FROM bot_delegations').pluck().get()).toBe(0);
+ expect(h.sqlite!.prepare('SELECT count(*) FROM sessions WHERE parent_session_id = ?').pluck().get('session-1')).toBe(0);
+ expect(runtime.started).toEqual([]);
+ } else {
+ expect(result.ok).toBe(true);
+ if (!result.ok) throw new Error(result.message);
+ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE id = ?').pluck().get(result.childSessionId)).toBe(settledMode);
+ const snapshot = h.sqlite!.prepare('SELECT permission_snapshot_json FROM bot_delegations WHERE id = ?').pluck().get(result.delegationId) as string;
+ expect(JSON.parse(snapshot).permission).toMatchObject({ mode: settledMode, requesterMode: settledMode });
+ }
+ } finally {
+ finishPreparation();
+ await starting;
+ runtime.dispose();
+ }
+ });
+
it('does not start a child with stale permissions during a live permission change', async () => {
await seedPair();
const runtime = createDelegationRuntime({ readCallerPermission: () => null });
diff --git a/apps/desktop/src/main/maker-host/botMcpCatalog.ts b/apps/desktop/src/main/maker-host/botMcpCatalog.ts
new file mode 100644
index 0000000000..c7818502e7
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/botMcpCatalog.ts
@@ -0,0 +1,25 @@
+import type { McpProvider, McpProviderContext } from '@cindy/maker-core';
+import type { McpTransport } from '../../shared/customMcp.js';
+
+/** Freeze only metadata; compatibility is recomputed for each actual start route. */
+export function buildBotMcpCatalog(input: {
+ agentKind: McpProviderContext['agentKind'];
+ providers: readonly Pick<McpProvider, 'name'>[];
+ builtinNames: readonly string[];
+ customServers: readonly { id: string; transport: McpTransport; updatedAt: number }[];
+}) {
+ const builtinNames = new Set(input.builtinNames);
+ const customServers = new Map(input.customServers.map((entry) => [entry.id, entry]));
+ return [...new Map(input.providers.map((provider) => {
+ const builtin = builtinNames.has(provider.name);
+ const custom = customServers.get(provider.name);
+ return [provider.name, {
+ name: provider.name,
+ source: builtin ? 'builtin' as const : 'custom' as const,
+ // CustomMcpProvider.toCodexMcpConfig cannot serialize the SSE transport.
+ available: builtin || input.agentKind !== 'codex' || custom?.transport !== 'sse',
+ generation: builtin ? 'builtin:1'
+ : custom ? `${custom.transport}:${custom.updatedAt}` : 'custom:unknown',
+ }];
+ })).values()];
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index f1d157d956..05bb88a324 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -55,6 +55,7 @@ import {
type BotProfileRuntimeSnapshot,
} from '../maker-ipc/botProfileRuntime.js';
import { collectBotOwnSkillMounts } from '../maker-ipc/botSkillService.js';
+import { buildBotMcpCatalog } from './botMcpCatalog.js';
import {
botProfileDir,
ensureBotContentDirs,
@@ -2299,26 +2300,12 @@ export function getMaker(): Maker {
: agentKind === 'codex'
? codexMcpProviders
: piMcpProviders;
- const builtinNames = new Set(getBuiltinMcpServerNames());
- const customGenerations = new Map(
- (await listCustomMcpRuntimeGenerations()).map((entry) => [
- entry.id,
- `${entry.transport}:${entry.updatedAt}`,
- ]),
- );
- return [...new Map(
- providers.map((provider) => [
- provider.name,
- {
- name: provider.name,
- source: builtinNames.has(provider.name) ? 'builtin' as const : 'custom' as const,
- available: true,
- generation: builtinNames.has(provider.name)
- ? 'builtin:1'
- : customGenerations.get(provider.name) ?? 'custom:unknown',
- },
- ]),
- ).values()];
+ return buildBotMcpCatalog({
+ agentKind,
+ providers,
+ builtinNames: getBuiltinMcpServerNames(),
+ customServers: await listCustomMcpRuntimeGenerations(),
+ });
},
listToolsets: async ({ botId, agentKind, workingDir, remoteHostId }) => {
const registry = getPluginRegistry();
diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
index fb277b074c..11831eb0f0 100644
--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
@@ -4,6 +4,7 @@ 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 { BOT_BASELINE_PLUGIN_IDS } from '../maker-host/plugins/types.js';
type Kind = 'skill' | 'mcp' | 'toolset';
type Input = { callerSessionId: string; kind: Kind };
@@ -73,7 +74,9 @@ 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 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 } = await import('../maker-host/index.js');
const agentKind =
getMaker().getSession(input.callerSessionId)?.agentKind ??
@@ -104,7 +107,7 @@ async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>):
items = await Promise.all(
registry
.getPlugins()
- .filter((plugin) => plugin.id !== 'collab')
+ .filter((plugin) => plugin.id !== 'collab' && !BOT_BASELINE_PLUGIN_IDS.has(plugin.id))
.map(async (plugin) => ({
id: plugin.id,
name: plugin.name,
@@ -151,6 +154,13 @@ export async function findBotCapabilities(input: Input & { query?: string }) {
export async function selectBotCapability(input: Input & { id: string; joined: boolean }) {
try {
const ctx = await context(input.callerSessionId);
+ if (input.kind === 'toolset' && BOT_BASELINE_PLUGIN_IDS.has(input.id)) {
+ return {
+ ok: false as const,
+ errorCode: 'CAPABILITY_NOT_SELECTABLE',
+ message: '该工具集是伙伴固定能力,无需加入且不能移除',
+ };
+ }
const field = fields[input.kind];
const previous = strings(ctx.config[field.list]);
if (input.joined) {
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index d32ae435d5..b36a854af9 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -1497,7 +1497,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
callerSessionId: string;
objective: string;
contextRefs: string[];
- plan: BotDelegationPlanSnapshot;
+ plan: Omit<BotDelegationPlanSnapshot, 'permission'>;
session: {
workingDir: string;
model: string;
@@ -1505,7 +1505,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
fastMode?: boolean;
providerId?: string | null;
agentKind: 'cc' | 'codex' | 'pi';
- permissionMode: string;
title: string;
source: 'desktop';
};
@@ -1515,9 +1514,34 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
status: 'queued' | 'running' | 'failed';
deadlineAt: number;
}>> => {
- const { plan } = input;
const delegationId = createId();
const childSessionId = resolveBusinessSessionId(undefined);
+ await ensureProjectGitInitialized({
+ workingDir: input.session.workingDir,
+ workspaceKind: 'dialogue',
+ remoteHostId: null,
+ sessionId: childSessionId,
+ autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,
+ source: 'bot-delegation',
+ });
+ // Read stable authority after asynchronous preparation, with no await before
+ // submitting creation. Both persisted records must use this same snapshot.
+ const callerPermission = deps.readCallerPermission
+ ? deps.readCallerPermission(input.callerSessionId)
+ : input.caller.permissionMode;
+ if (callerPermission === null) {
+ return { ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE', message: '伙伴权限正在切换或任务正在关闭,请稍后重试' };
+ }
+ const permissionMode = permissionModeOrAsk(callerPermission);
+ const plan: BotDelegationPlanSnapshot = {
+ ...input.plan,
+ permission: {
+ mode: permissionMode,
+ requesterMode: permissionMode,
+ // Legacy target-profile field; the effective child permission is mode.
+ targetConfigured: 'ask',
+ },
+ };
const createdAt = plan.createdAt;
const permissionSnapshotJson = JSON.stringify(plan);
const childRow = {
@@ -1534,7 +1558,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
? { providerId: input.session.providerId }
: {}),
agentKind: input.session.agentKind,
- permissionMode: input.session.permissionMode,
+ permissionMode,
parentSessionId: input.callerSessionId,
},
createdAt,
@@ -1543,14 +1567,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
source: input.session.source,
};
try {
- await ensureProjectGitInitialized({
- workingDir: input.session.workingDir,
- workspaceKind: 'dialogue',
- remoteHostId: null,
- sessionId: childSessionId,
- autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,
- source: 'bot-delegation',
- });
await getDbClient().tx('bots.createDelegation', {
maxActiveChildren,
session: {
@@ -1720,26 +1736,13 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
app.getPath('userData'),
);
}
- const callerPermission = deps.readCallerPermission
- ? deps.readCallerPermission(input.callerSessionId)
- : caller.permissionMode;
- if (callerPermission === null) {
- return { ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE', message: '伙伴权限正在切换或任务正在关闭,请稍后重试' };
- }
- const permissionMode = permissionModeOrAsk(callerPermission);
- const plan: BotDelegationPlanSnapshot = {
+ const plan: Omit<BotDelegationPlanSnapshot, 'permission'> = {
version: 1,
createdAt,
targetBotId: null,
access: { contextRefs: contextRefs.refs },
completionTarget: { parentSessionId: input.callerSessionId },
limits: { maxDepth: DEFAULT_MAX_DEPTH, timeoutMs, deadlineAt },
- permission: {
- mode: permissionMode,
- requesterMode: permissionMode,
- // Legacy target-profile field; the effective child permission is mode.
- targetConfigured: 'ask',
- },
};
const started = await startDelegation({
caller,
@@ -1756,7 +1759,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
: {}),
...(callerRuntime.providerId ? { providerId: callerRuntime.providerId } : {}),
agentKind: callerRuntime.agentKind as 'cc' | 'codex' | 'pi',
- permissionMode,
title: input.title?.trim() || objective.split('\n')[0]!.slice(0, 60),
source: 'desktop',
},