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): merge concurrent capability edits and refresh skill catalogs

zqchris37f134271ef6
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 39de8d16e3..48ffbc0497 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -174,6 +174,7 @@ vi.mock('../../../appSessionState.js', async (importOriginal) => {
import {
createBotCanonicalSession,
registerBotIpc,
+ updateBotProfile as updateStoredBotProfile,
getBotRemoteResourceSource,
listBotRemoteResourceSources,
} from '../bots';
@@ -1781,7 +1782,7 @@ describe('Bot canonical Session lifecycle', () => {
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]) }))
+ await expect(invoke('local-db:bots:update', { id: 'bot-1', name: 'Unsaved name', ...patch([id]), capabilityBaseline: { [field]: [] } }))
.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' });
@@ -1797,6 +1798,46 @@ describe('Bot canonical Session lifecycle', () => {
},
);
+ it.each(['skills', 'mcpServers', 'toolsets'] as const)('merges stale settings %s without losing concurrent joins or restoring external removals', async (field) => {
+ const patch = (ids: string[]) => field === 'skills' ? { skills: ids } : { capabilities: { [field]: ids } };
+ const selected = (profile: { skills: string[]; capabilities: { mcpServers: string[]; toolsets: string[] } }): string[] =>
+ field === 'skills' ? profile.skills : profile.capabilities[field];
+ // Model-side writes use the same mutation with their captured version. The
+ // renderer has not received this new snapshot when its request reaches Main.
+ await updateStoredBotProfile({ id: 'bot-1', ...patch(['external']) }, 1);
+ const saved = await invoke('local-db:bots:update', {
+ id: 'bot-1', ...patch(['local']), capabilityBaseline: { [field]: [] },
+ });
+ expect(selected(saved)).toEqual(['external', 'local']);
+ expect(h.validateCapabilityAdditions).toHaveBeenLastCalledWith(expect.objectContaining({
+ next: expect.objectContaining({ [field]: ['external', 'local'] }),
+ }));
+ expect(saved).not.toHaveProperty('capabilityBaseline');
+ // A trailing save can run before the merged response is rendered. Its local
+ // baseline still lacks external; removing local must leave external alone.
+ const trailing = await invoke('local-db:bots:update', {
+ id: 'bot-1', ...patch([]), capabilityBaseline: { [field]: ['local'] },
+ });
+ expect(selected(trailing)).toEqual(['external']);
+ await updateStoredBotProfile({ id: 'bot-1', ...patch([]) }, trailing.currentVersion);
+ const afterRemoval = await invoke('local-db:bots:update', {
+ id: 'bot-1', ...patch(['external', 'new-local']), capabilityBaseline: { [field]: ['external'] },
+ });
+ expect(selected(afterRemoval)).toEqual(['new-local']);
+ // Repeating the same local delta is idempotent.
+ const repeated = await invoke('local-db:bots:update', {
+ id: 'bot-1', ...patch(['external', 'new-local']), capabilityBaseline: { [field]: ['external'] },
+ });
+ expect(selected(repeated)).toEqual(['new-local']);
+ expect(repeated.currentVersion).toBe(afterRemoval.currentVersion);
+ });
+
+ it.each([null, [], { skills: [42] }, { toolsets: [] }])('rejects malformed or unmatched capability baselines: %j', async (capabilityBaseline) => {
+ await expect(invoke('local-db:bots:update', { id: 'bot-1', skills: ['new'], capabilityBaseline }))
+ .rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(h.sqlite!.prepare('SELECT current_version FROM bot_profiles WHERE id = ?').pluck().get('bot-1')).toBe(1);
+ });
+
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();
@@ -1831,7 +1872,7 @@ describe('Bot canonical Session lifecycle', () => {
},
});
h.validateCapabilityAdditions.mockImplementation(service.validateAdditions);
- await expect(invoke('local-db:bots:update', { id: 'bot-1', capabilities: { mcpServers: ['shared-docs'] } })).rejects.toBeTruthy();
+ await expect(invoke('local-db:bots:update', { id: 'bot-1', capabilities: { mcpServers: ['shared-docs'] }, capabilityBaseline: { mcpServers: [] } })).rejects.toBeTruthy();
expect(h.sqlite!.prepare('SELECT COUNT(*) FROM bot_profile_versions WHERE bot_id = ?').pluck().get('bot-1')).toBe(1);
});
diff --git a/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts b/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts
index f51b31ed1c..64c65d9fe4 100644
--- a/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts
+++ b/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts
@@ -1,3 +1,7 @@
+import { normalizeBotModelChain } from '../../../shared/botModelChain.js';
+import { reconcileBotCapabilityList } from '../../../shared/botCapabilitySelection.js';
+import { throwIpcError } from '../../utils/ipcValidate.js';
+
export function botProfileContentChanged(input: {
previousCapabilities: Record<string, unknown>;
nextCapabilities: Record<string, unknown>;
@@ -15,6 +19,7 @@ export function mergeBotProfileCapabilities(input: {
capabilities?: Record<string, unknown>;
skills?: unknown;
hasSkills: boolean;
+ capabilityBaseline?: unknown;
}): Record<string, unknown> {
const next = input.capabilities
? { ...input.previous, ...input.capabilities }
@@ -28,6 +33,26 @@ export function mergeBotProfileCapabilities(input: {
.slice(0, 100)
: [];
}
+ if (input.capabilityBaseline !== undefined) {
+ const baseline = input.capabilityBaseline;
+ if (!baseline || typeof baseline !== 'object' || Array.isArray(baseline)) {
+ throwIpcError('INVALID_PARAMS', 'capabilityBaseline must be an object');
+ }
+ for (const key of ['skills', 'mcpServers', 'toolsets'] as const) {
+ const before = (baseline as Record<string, unknown>)[key];
+ if (before === undefined) continue;
+ const local = next[key];
+ const hasSelection = key === 'skills' ? input.hasSkills
+ : Object.prototype.hasOwnProperty.call(input.capabilities ?? {}, key);
+ if (!hasSelection || !Array.isArray(before) || !before.every((id) => typeof id === 'string')
+ || !Array.isArray(local) || !local.every((id) => typeof id === 'string')) {
+ throwIpcError('INVALID_PARAMS', 'capabilityBaseline requires matching string lists');
+ }
+ const current = input.previous[key];
+ next[key] = reconcileBotCapabilityList(before, local,
+ Array.isArray(current) ? current.filter((id): id is string => typeof id === 'string') : []);
+ }
+ }
return next;
}
@@ -62,4 +87,3 @@ export function normalizeBotProfileModelChain(
}
return next;
}
-import { normalizeBotModelChain } from '../../../shared/botModelChain.js';
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 201f937105..e04a782f7f 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -1167,6 +1167,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,
: undefined,
skills: body.skills,
hasSkills: Object.prototype.hasOwnProperty.call(body, 'skills'),
+ capabilityBaseline: body.capabilityBaseline,
});
// Keep preparation checkpoints outside caller-editable capabilities.
if (previous.invitation) nextConfig.invitation = previous.invitation;
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts
index 814ee7f2f9..e198b319c8 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts
@@ -265,7 +265,7 @@ describe('piEnvironment per-session identity', () => {
config!.disposeSessionCtx!();
});
- it('gives a Bot only its frozen built-ins plus configured custom MCPs', async () => {
+ it.each([true, false])('keeps the plugin gateway with frozen Bot tools when memory is %s', async (memoryEnabled) => {
const config = await getPiExtraSpawnConfig([
makeProvider('cindy'),
makeProvider('cindy_memory'),
@@ -277,7 +277,7 @@ describe('piEnvironment per-session identity', () => {
sessionId: 'pi-bot-minimal-tools',
workingDir: '/repo',
memoryScopeKey: 'bot:bot-minimal-tools',
- memoryEnabled: true,
+ memoryEnabled,
vendorOptions: {
[CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: ['memory', 'xdt_helper'],
},
@@ -293,10 +293,29 @@ describe('piEnvironment per-session identity', () => {
expect(config?.mcpBridge?.servers.map((server) => server.name).sort()).toEqual([
'cindy',
'cindy_helper',
- 'cindy_memory',
+ ...(memoryEnabled ? ['cindy_memory'] : []),
'custom_probe',
]);
expect(config?.mcpBridge?.botMemoryFacade).toBe(true);
+ const gateway = config!.mcpBridge!.servers.find((server) => server.name === 'cindy')!;
+ const headers = {
+ authorization: `Bearer ${config!.mcpBridge!.token}`,
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+ const initialized = await fetch(gateway.url, { method: 'POST', headers, body: INIT_BODY(1) });
+ expect(initialized.status).toBe(200);
+ const mcpSessionId = initialized.headers.get('mcp-session-id')!;
+ await initialized.text();
+ const called = await fetch(gateway.url, {
+ method: 'POST', headers: { ...headers, 'mcp-session-id': mcpSessionId },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call',
+ params: { name: 'current_session', arguments: {} } }),
+ });
+ expect(called.status).toBe(200);
+ expect(await readRpcText(called)).toMatchObject({
+ result: { content: [{ type: 'text', text: 'pi-bot-minimal-tools' }] },
+ });
config?.disposeSessionCtx?.();
});
diff --git a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx
index 10363490fd..7d4e0ef921 100644
--- a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx
@@ -94,6 +94,7 @@ export function BotCapabilitySettings({
if (!agentKind) throw new Error('Missing next-turn route');
const results = await Promise.allSettled([
api.listAgentSkills(agentKind, {
+ forceReload: true,
workingDir: session.workingDir ?? undefined,
remoteHostId: session.remoteHostId ?? undefined,
}),
diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
index ce013586f0..5feccaebf5 100644
--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
@@ -110,7 +110,7 @@ export function BotSettings({
async (payload: BotSettingsPayload) => {
savingProfileRef.current = true;
try {
- await updateBotProfile(bot.id, botSettingsChanges(savedSettingsRef.current, payload));
+ await updateBotProfile(bot.id, botSettingsChanges(savedSettingsRef.current, payload, true));
savedSettingsRef.current = payload;
} finally {
savingProfileRef.current = false;
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 3043604c2e..8c1446c701 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
@@ -566,9 +566,9 @@ describe('same-Bot capability updates while editing settings', () => {
});
}
const cases = [
- { name: 'release-check', selected: { skills: ['release-check'], capabilities: capabilities({ skillMode: 'allowlist' }) }, empty: { skills: [], capabilities: capabilities({ skillMode: 'allowlist' }) }, patch: { skills: [] }, addPatch: { skills: ['release-check'] } },
- { name: 'Shared Docs', selected: { capabilities: capabilities({ mcpMode: 'allowlist', mcpServers: ['shared-docs'] }) }, empty: { capabilities: capabilities({ mcpMode: 'allowlist' }) }, patch: { capabilities: { mcpServers: [] } }, addPatch: { capabilities: { mcpServers: ['shared-docs'] } } },
- { name: 'Documents', selected: { capabilities: capabilities({ toolsetMode: 'allowlist', toolsets: ['docs'] }) }, empty: { capabilities: capabilities({ toolsetMode: 'allowlist' }) }, patch: { capabilities: { toolsets: [] } }, addPatch: { capabilities: { toolsets: ['docs'] } } },
+ { name: 'release-check', selected: { skills: ['release-check'], capabilities: capabilities({ skillMode: 'allowlist' }) }, empty: { skills: [], capabilities: capabilities({ skillMode: 'allowlist' }) }, patch: { skills: [], capabilityBaseline: { skills: ['release-check'] } }, addPatch: { skills: ['release-check'], capabilityBaseline: { skills: [] } } },
+ { name: 'Shared Docs', selected: { capabilities: capabilities({ mcpMode: 'allowlist', mcpServers: ['shared-docs'] }) }, empty: { capabilities: capabilities({ mcpMode: 'allowlist' }) }, patch: { capabilities: { mcpServers: [] }, capabilityBaseline: { mcpServers: ['shared-docs'] } }, addPatch: { capabilities: { mcpServers: ['shared-docs'] }, capabilityBaseline: { mcpServers: [] } } },
+ { name: 'Documents', selected: { capabilities: capabilities({ toolsetMode: 'allowlist', toolsets: ['docs'] }) }, empty: { capabilities: capabilities({ toolsetMode: 'allowlist' }) }, patch: { capabilities: { toolsets: [] }, capabilityBaseline: { toolsets: ['docs'] } }, addPatch: { capabilities: { toolsets: ['docs'] }, capabilityBaseline: { toolsets: [] } } },
];
function sseCatalog(agentKind: 'claude-code' | 'codex'): CustomMcpListResult {
@@ -681,7 +681,7 @@ describe('same-Bot capability updates while editing settings', () => {
expect(checkbox.disabled).toBe(false);
expect(mocks.updateBotProfile).not.toHaveBeenCalled();
fireEvent.click(checkbox);
- await waitFor(() => expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { capabilities: { mcpServers: [] } }));
+ await waitFor(() => expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { capabilities: { mcpServers: [] }, capabilityBaseline: { mcpServers: ['events'] } }));
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;
@@ -689,6 +689,30 @@ describe('same-Bot capability updates while editing settings', () => {
expect(off).toHaveBeenCalledOnce();
});
+ it.each([undefined, 'ssh-host'])('reloads installed and deleted Codex Skills on reopen for target %s', async (remoteHostId) => {
+ let disk = ['old-skill'];
+ let cached = [...disk];
+ mocks.getSession.mockResolvedValue({ agentKind: 'codex', workingDir: '/bot/workspace', remoteHostId });
+ mocks.listCustomMcpServers.mockResolvedValue({ agentKind: 'codex', servers: [] });
+ mocks.listAgentSkills.mockImplementation(async (_kind, options) => {
+ if (options?.forceReload) cached = [...disk];
+ return { success: true, skills: cached.map((name) => ({ name })) };
+ });
+ renderSettings();
+ await openCapabilities();
+ expect(screen.getByRole('checkbox', { name: 'old-skill' })).toBeTruthy();
+ const details = screen.getByText('bots.capabilities.title').parentElement as HTMLDetailsElement;
+ await act(async () => { details.open = false; fireEvent(details, new Event('toggle')); });
+ disk = ['new-skill'];
+ await openCapabilities();
+ expect(screen.queryByRole('checkbox', { name: 'old-skill' })).toBeNull();
+ expect(screen.getByRole('checkbox', { name: 'new-skill' })).toBeTruthy();
+ expect(mocks.listAgentSkills).toHaveBeenLastCalledWith('codex', {
+ forceReload: true, workingDir: '/bot/workspace', remoteHostId,
+ });
+ expect(mocks.updateBotProfile).not.toHaveBeenCalled();
+ });
+
it('invalidates selectable MCPs immediately and ignores an outdated refresh after another change', async () => {
mocks.listCustomMcpServers.mockResolvedValue(sseCatalog('claude-code'));
const off = vi.fn();
@@ -759,7 +783,7 @@ describe('same-Bot capability updates while editing settings', () => {
expect(unavailable.checked).toBe(true);
fireEvent.click(unavailable);
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
- expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { capabilities: { mcpServers: [] } });
+ expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { capabilities: { mcpServers: [] }, capabilityBaseline: { mcpServers: ['bad-headers'] } });
expect(unavailable.disabled).toBe(true);
});
@@ -798,7 +822,7 @@ describe('same-Bot capability updates while editing settings', () => {
expect((screen.getByRole('checkbox', { name: 'Documents' }) as HTMLInputElement).checked).toBe(true);
expect((screen.getByRole('checkbox', { name: 'Scheduler' }) as HTMLInputElement).checked).toBe(true);
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
- expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { name: 'Local name', capabilities: { toolsets: ['docs', 'scheduler'] } });
+ expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { name: 'Local name', capabilities: { toolsets: ['docs', 'scheduler'] }, capabilityBaseline: { toolsets: ['docs'] } });
});
it('keeps edits made during a successful save and adopts concurrent capability updates', async () => {
@@ -842,6 +866,6 @@ describe('same-Bot capability updates while editing settings', () => {
view.rerender(<BotSettings bot={bot({ currentVersion: 2, capabilities: capabilities({ toolsetMode: 'allowlist', toolsets: ['contacts'] }) })} onBack={view.onBack} onOpenSession={view.onOpenSession} />);
expect((screen.getByRole('checkbox', { name: /Contacts/ }) as HTMLInputElement).disabled).toBe(false);
fireEvent.click(screen.getByRole('checkbox', { name: /Contacts/ }));
- await waitFor(() => expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { capabilities: { toolsets: [] } }));
+ await waitFor(() => expect(mocks.updateBotProfile).toHaveBeenLastCalledWith('bot-1', { capabilities: { toolsets: [] }, capabilityBaseline: { toolsets: ['contacts'] } }));
});
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSettingsAutosave.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botSettingsAutosave.test.ts
index af913e3de7..0e5a6afece 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSettingsAutosave.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSettingsAutosave.test.ts
@@ -388,4 +388,16 @@ describe('settings changes preserve independently joined capabilities', () => {
it('updates only the selected capability group', () => {
expect(botSettingsChanges(payload(), payload({ capabilities: capabilities({ mcpServers: ['docs'] }) }))).toEqual({ capabilities: { mcpServers: ['docs'] } });
});
+ it('carries only edited list baselines across consecutive saves', () => {
+ const before = payload({ skills: ['old'], capabilities: capabilities({ mcpServers: ['mcp'], toolsets: ['tool'] }) });
+ const after = { ...before, skills: ['new'], capabilities: { ...before.capabilities, toolsets: [] } };
+ expect(botSettingsChanges(before, after, true)).toEqual({
+ skills: ['new'], capabilities: { toolsets: [] },
+ capabilityBaseline: { skills: ['old'], toolsets: ['tool'] },
+ });
+ expect(botSettingsChanges(after, { ...after, skills: [] }, true)).toEqual({
+ skills: [], capabilityBaseline: { skills: ['new'] },
+ });
+ expect(botSettingsChanges(after, { ...after, name: 'Updated' }, true)).toEqual({ name: 'Updated' });
+ });
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botStore.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botStore.test.ts
index e1661bbc09..af4ec017ab 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botStore.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botStore.test.ts
@@ -486,6 +486,24 @@ describe('保存失败只回滚自己那一行', () => {
};
}
+ it('forwards the editing baseline to Main without adding it to optimistic profile state', async () => {
+ const bot = addBotProfile({ name: 'Settings merge', description: '' });
+ createdIds.push(bot.id);
+ stubDeferredUpdates();
+ const update = vi.fn(async () => ({ ...bot, skills: ['external', 'local'], currentVersion: 3 }));
+ const api = (globalThis as unknown as { window: { electronAPI: { localDb: { bots: { update: unknown } } } } }).window.electronAPI.localDb.bots;
+ api.update = update;
+ const pending = updateBotProfile(bot.id, {
+ skills: ['local'], capabilityBaseline: { skills: [] },
+ });
+ expect(update).toHaveBeenCalledWith(expect.objectContaining({
+ id: bot.id, skills: ['local'], capabilityBaseline: { skills: [] },
+ }));
+ expect(getBotProfiles().find((item) => item.id === bot.id)).not.toHaveProperty('capabilityBaseline');
+ await expect(pending).resolves.toMatchObject({ skills: ['external', 'local'] });
+ expect(getBotProfiles().find((item) => item.id === bot.id)).toMatchObject({ skills: ['external', 'local'] });
+ });
+
it('另一个伙伴在同期保存的修改不被撤销', async () => {
const failing = addBotProfile({ name: 'Failing', description: '' });
const other = addBotProfile({ name: 'Other', description: '' });
diff --git a/apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts b/apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts
index 736971614a..b10879c4f1 100644
--- a/apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts
+++ b/apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts
@@ -23,6 +23,7 @@
*/
import type { BotCapabilities, BotProfileUpdatePatch } from './botStore';
+import { reconcileBotCapabilityList } from '../../../shared/botCapabilitySelection';
/** 提交给 `updateBotProfile` 的字段集合(与手动保存时的载荷完全一致)。 */
export interface BotSettingsPayload {
@@ -131,13 +132,22 @@ export function botSettingsPayloadEqual(a: BotSettingsPayload, b: BotSettingsPay
}
/** Send only edited fields, preserving capabilities joined concurrently by the companion. */
-export function botSettingsChanges(previous: BotSettingsPayload, next: BotSettingsPayload): BotProfileUpdatePatch {
+export function botSettingsChanges(previous: BotSettingsPayload, next: BotSettingsPayload, includeCapabilityBaseline = false): BotProfileUpdatePatch {
const { capabilities, ...values } = next;
const changed = Object.fromEntries(Object.entries(values).filter(([key, value]) =>
!capabilityValueEqual(value, previous[key as keyof typeof values])));
const capabilityChanges = Object.fromEntries(Object.entries(capabilities).filter(([key, value]) =>
!capabilityValueEqual(value, previous.capabilities[key as keyof BotCapabilities])));
- return { ...changed, ...(Object.keys(capabilityChanges).length ? { capabilities: capabilityChanges } : {}) };
+ const capabilityBaseline = {
+ ...('skills' in changed ? { skills: previous.skills } : {}),
+ ...('mcpServers' in capabilityChanges ? { mcpServers: previous.capabilities.mcpServers } : {}),
+ ...('toolsets' in capabilityChanges ? { toolsets: previous.capabilities.toolsets } : {}),
+ };
+ return {
+ ...changed,
+ ...(Object.keys(capabilityChanges).length ? { capabilities: capabilityChanges } : {}),
+ ...(includeCapabilityBaseline && Object.keys(capabilityBaseline).length ? { capabilityBaseline } : {}),
+ };
}
/** Advance untouched fields to a live profile without discarding pending local edits. */
@@ -148,21 +158,17 @@ export function reconcileBotSettingsDraft(
): BotSettingsDraft {
const normalized = normalizeBotSettingsPayload(draft, baseline.name);
const changes = botSettingsChanges(baseline, normalized);
- const reconcileList = (previous: string[], local: string[], remote: string[]) => [
- ...remote.filter((id) => !previous.includes(id) || local.includes(id)),
- ...local.filter((id) => !previous.includes(id) && !remote.includes(id)),
- ];
return {
...incoming,
...Object.fromEntries(Object.keys(changes)
.filter((key) => key !== 'capabilities')
.map((key) => [key, draft[key as keyof BotSettingsDraft]])),
- skills: reconcileList(baseline.skills, draft.skills, incoming.skills),
+ skills: reconcileBotCapabilityList(baseline.skills, draft.skills, incoming.skills),
capabilities: {
...incoming.capabilities,
...changes.capabilities,
- mcpServers: reconcileList(baseline.capabilities.mcpServers, draft.capabilities.mcpServers, incoming.capabilities.mcpServers),
- toolsets: reconcileList(baseline.capabilities.toolsets, draft.capabilities.toolsets, incoming.capabilities.toolsets),
+ mcpServers: reconcileBotCapabilityList(baseline.capabilities.mcpServers, draft.capabilities.mcpServers, incoming.capabilities.mcpServers),
+ toolsets: reconcileBotCapabilityList(baseline.capabilities.toolsets, draft.capabilities.toolsets, incoming.capabilities.toolsets),
},
};
}
diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.ts
index 5def77adad..60d35b4eb5 100644
--- a/apps/desktop/src/renderer/features/bots/botStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botStore.ts
@@ -16,6 +16,7 @@ import { getBotLastReadAtMap, pruneBotReadState, seedMissingBotReadState } from
import type { BotGender } from '../../../shared/botGender';
import { BOT_FAILURE_REASONS, type BotFailureReason } from '../../../shared/botFailureReason';
import type { BotTemplatePresetId } from '../../../shared/botTemplatePreset';
+import type { BotCapabilityBaseline } from '../../../shared/botCapabilitySelection';
import { NEW_BOT_DEFAULT_PERMISSIONS, normalizeBotPermissions } from './botCapabilityDefaults';
import {
BOT_MODEL_CHAIN_MAX,
@@ -953,13 +954,17 @@ export type BotProfileUpdatePatch = Partial<
| 'canonicalSessionId'
| 'sessions'
>
-> & { avatarUploadToken?: string; capabilities?: Partial<BotCapabilities> };
+> & {
+ avatarUploadToken?: string;
+ capabilities?: Partial<BotCapabilities>;
+ capabilityBaseline?: BotCapabilityBaseline;
+};
export function updateBotProfile(id: string, patch: BotProfileUpdatePatch): Promise<BotProfile> {
ensureProfileOwner();
const before = profiles.find((bot) => bot.id === id);
if (!before) return Promise.reject(new Error('Bot not found'));
- const { avatarUploadToken, ...profilePatch } = patch;
+ const { avatarUploadToken, capabilityBaseline, ...profilePatch } = patch;
// 这一行的写入代际。回填与回滚都要求「我仍然是这一行最新的那次写」——
// 落后的响应一律丢弃,不许覆盖更新的状态(见下面两处 isLatestWrite)。
const generation = (profileWriteGenerations.get(id) ?? 0) + 1;
@@ -980,6 +985,7 @@ export function updateBotProfile(id: string, patch: BotProfileUpdatePatch): Prom
.update({
id,
...profilePatch,
+ ...(capabilityBaseline ? { capabilityBaseline } : {}),
...(avatarUploadToken ? { avatarUploadToken } : {}),
...(profilePatch.avatar !== undefined || avatarUploadToken
? { expectedAvatar: before.avatar }
diff --git a/apps/desktop/src/shared/botCapabilitySelection.ts b/apps/desktop/src/shared/botCapabilitySelection.ts
new file mode 100644
index 0000000000..c1e14285e4
--- /dev/null
+++ b/apps/desktop/src/shared/botCapabilitySelection.ts
@@ -0,0 +1,12 @@
+/** Editing baseline, sent only for capability lists changed by the settings form. */
+export type BotCapabilityBaseline = Partial<Record<'skills' | 'mcpServers' | 'toolsets', string[]>>;
+
+/** Apply the local additions/removals to the latest list, preserving concurrent changes. */
+export function reconcileBotCapabilityList(previous: string[], local: string[], remote: string[]): string[] {
+ const baseline = new Set(previous);
+ const selected = new Set(local);
+ return [...new Set([
+ ...remote.filter((id) => !baseline.has(id) || selected.has(id)),
+ ...local.filter((id) => !baseline.has(id)),
+ ])];
+}