Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/desktop/src/main/localDb/client/tx/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,8 @@ export interface BotsUpdateProfileArgs {
inactiveCindyIds?: string[];
/** A saved model choice supersedes automation restores in the same commit. */
clearScheduledModelBaseline?: boolean;
/** A selected plugin primary cannot be applied to an active local canonical Lead. */
rejectPluginPrimaryForLocalLead?: boolean;
/** Explicit settings changes also update the permanent chat in this transaction. */
canonicalPermissionMode?: 'ask' | 'auto' | 'bypassPermissions';
displayName?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5724,6 +5724,45 @@ describe('Teammate model selection shares profile persistence and route reconcil
id: JSON.stringify(['pi', 'xd', model.id]), model };
}

// #12276, DB tier. Use the settings IPC with a built-in canonical session
// and an ACP primary. Before the fix the save advanced the profile version,
// even though the ordinary session switch could never apply it to the Lead.
it('rejects a plugin primary for a local canonical Lead and accepts a built-in recovery', async () => {
const { sessionId } = await setupModelControl();
const getProfile = () => invoke('local-db:bots:get', 'bot-1');
const save = (modelChainOverride: BotModelRoute[]) =>
invoke('local-db:bots:update', { id: 'bot-1', capabilities: { modelChainOverride } });
const setLead = (role: 'lead' | null) =>
h.sqlite!.prepare('UPDATE sessions SET orca_role = ? WHERE id = ?').run(role, sessionId);
const plugin: BotModelRoute = {
harness: 'acp', providerId: 'acp-plugin:fixture:echo', model: 'default', effort: '', fastMode: false,
};
const before = await getProfile();
const [builtIn] = before.capabilities.modelChain as BotModelRoute[];
if (!builtIn || builtIn.harness === 'acp') throw new Error('Expected a built-in fixture route');
setLead('lead');
h.requestRuntimeRefresh.mockClear();
await expect(save([plugin, builtIn])).rejects.toThrow('BOT_LEAD_PLUGIN_ENGINE_UNSUPPORTED');
const rejected = await getProfile();
expect(rejected.currentVersion).toBe(before.currentVersion);
expect(rejected.capabilities.modelChain).toEqual(before.capabilities.modelChain);
expect(h.requestRuntimeRefresh).not.toHaveBeenCalled();

await expect(save([builtIn, plugin])).resolves.toMatchObject({
capabilities: { modelChain: [builtIn, plugin] },
});
setLead(null);
await expect(save([plugin, builtIn])).resolves.toMatchObject({
capabilities: { modelChain: [plugin, builtIn] },
});
// Simulate a profile saved by an older build while the actual session kept its built-in route.
setLead('lead');
await expect(save([builtIn])).resolves.toMatchObject({
canonicalSessionId: sessionId,
capabilities: { modelChain: [builtIn] },
});
});

// #7177, DB tier: an explicit same-value tool selection must reach the
// acceptance transaction; a plain metadata edit must retain the old scope.
it('reaccepts the same model through the teammate tool without treating a rename as recovery', async () => {
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src/main/localDb/ipc/bots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2219,13 +2219,15 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,
// Compare the same representation so unrelated edits do not validate stale routes.
const modelSelectionChanged = botProfileModelSelectionChanged(normalizeBotModelCapabilitiesOrThrow(previous), normalizedNextConfig);
const acceptsModelSelection = modelSelectionChanged || acceptsSavedModel;
let pluginPrimarySelected = false;
if (acceptsModelSelection) {
const primary = (await readEffectiveBotModelChain(normalizedNextConfig))[0];
owner.assertCurrent();
if (!primary || !await validateTaskModel(primary)) {
throwIpcError('INVALID_PARAMS', 'Model route unavailable');
}
owner.assertCurrent();
pluginPrimarySelected = primary.harness === 'acp';
}
const nextIdentitySource =
body.identitySource !== undefined
Expand Down Expand Up @@ -2258,6 +2260,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,
await client.tx('bots.updateProfile', {
id,
...(acceptsModelSelection ? { clearScheduledModelBaseline: true } : {}),
...(pluginPrimarySelected ? { rejectPluginPrimaryForLocalLead: true } : {}),
...(changesPermissions ? { canonicalPermissionMode: botSessionPermissionMode(normalizedNextConfig) } : {}),
...(restored?.allowSameName === true ? { allowDuplicateName: true } : {}),
...(restored?.templateId === 'cindy' ? { inactiveCindyIds: inactiveCompanionCopyIds(companionHomes.snapshot()) } : {}),
Expand Down
15 changes: 14 additions & 1 deletion apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import { batchAutoReviewProjection, readAutoReviewProjectionTransaction } from '
import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from '../../sharedTaskClosureSql.js';
import { IDLE_ARCHIVE_GUARD_SQL } from '../../../task-management/eligibility.js';
import { assertSessionDeleteTarget, COMMITTED_SIDE_CHAT_WORKER_SQL, ORCA_WORKER_LINK_TEAM_SQL, SIDE_CHAT_CLOSE_TARGET_SQL } from '../../sessionDeleteTarget.js';
import { botProfileModelSelectionChanged } from '../../../../shared/botModelChain.js';
import { BOT_LEAD_PLUGIN_ENGINE_UNSUPPORTED, botProfileModelSelectionChanged } from '../../../../shared/botModelChain.js';
import { throwIpcError } from '../../../utils/ipcValidate.js';
import { dbToMakerAgentKind } from '../../../../shared/agentKindConversion.js';
import { parseScheduledModelBaseline } from '../../../../shared/scheduledModelBaseline.js';
import { normalizeBotName } from '../../../../shared/botCreation.js';
Expand Down Expand Up @@ -401,6 +402,7 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersi
const expectedVersion = expectNumber(p.expectedCurrentVersion, 'expectedCurrentVersion');
const now = expectNumber(p.now, 'now');
const allowDuplicateName = expectOptionalFlag(p.allowDuplicateName, 'allowDuplicateName');
const rejectPluginPrimaryForLocalLead = expectOptionalFlag(p.rejectPluginPrimaryForLocalLead, 'rejectPluginPrimaryForLocalLead');
const inactive = inactiveCindyIds(p.inactiveCindyIds);
const avatarRef = p.botAvatarRef === undefined
? null
Expand All @@ -424,6 +426,17 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersi
if (current.currentVersion !== expectedVersion) {
throw Object.assign(new Error('Bot Profile 已被另一处更新,请刷新后重试'), { code: 'PRECONDITION_FAILED' });
}
// Check the authoritative link and current role in the same commit as the choice.
if (rejectPluginPrimaryForLocalLead && db.prepare(`
SELECT 1 FROM bot_session_links l JOIN sessions s ON s.id = l.session_id
WHERE l.bot_id = ? AND l.role = 'canonical' AND l.archived_at IS NULL
AND s.source = 'bot' AND s.status = 'active' AND s.orca_role = 'lead'
AND s.remote_host_id IS NULL AND s.orca_remote_lead IS NULL
LIMIT 1
`).get(id)) {
throwIpcError('UNSUPPORTED_CAPABILITY',
`${BOT_LEAD_PLUGIN_ENGINE_UNSUPPORTED}: Choose a built-in engine for this companion chat while it leads a collaboration.`);
}
if (p.expectedAvatar !== undefined && current.avatar !== expectString(p.expectedAvatar, 'expectedAvatar')) {
throw Object.assign(new Error('Buddy avatar changed during update'), { code: 'PRECONDITION_FAILED' });
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Check } from 'lucide-react';
import { Spinner } from '@/components/ui/spinner';
import { useBotTranslation } from './botPronounContext';
import { BOT_LEAD_PLUGIN_ENGINE_ERROR_KEY } from './botSettingsAutosave';
import type { BotSettingsAutosaveController } from './useBotSettingsAutosave';

/** Shared settings header feedback; only a confirmed receipt becomes saved. */
Expand All @@ -23,7 +24,7 @@ export function BotSettingsSaveStatus({ autosave, modelPage, sourceTooLong }: {
if (autosave.status === 'error') return (
<p className="flex items-center gap-2 text-11 text-[var(--text-danger)]" role="alert">
{t(autosave.errorKey ?? 'bots.profileSaveFailed')}
{!sourceTooLong && <button type="button" onClick={() => void autosave.retry()}
{!sourceTooLong && autosave.errorKey !== BOT_LEAD_PLUGIN_ENGINE_ERROR_KEY && <button type="button" onClick={() => void autosave.retry()}
className="shrink-0 font-medium text-[var(--text-primary)]">
{t('bots.autosave.retry')}
</button>}
Expand Down
5 changes: 3 additions & 2 deletions apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import { BotMemorySettings } from './BotMemorySettings';
import { CompanionVoiceSettings } from './voice/CompanionVoiceSettings';
import { BotChannelsPage } from './BotChannelsPage';
import {
BOT_LEAD_PLUGIN_ENGINE_ERROR_KEY,
botSettingsChanges,
normalizeBotSettingsPayload,
reconcileBotSettingsDraft,
Expand Down Expand Up @@ -254,9 +255,9 @@ export function BotSettings({
&& userContextSource.trim() !== savedSettingsRef.current.userContextSource);
const canLeave = useCallback(async () => {
if (avatarInFlight.current) return false;
await autosave.flush();
const errorKey = await autosave.flush();
if (autosave.isDirty()) {
if (!sourceTooLong) return false;
if (!sourceTooLong && errorKey !== BOT_LEAD_PLUGIN_ENGINE_ERROR_KEY) return false;
const discard = await confirm({
title: t('bots.memory.unsavedTitle'),
description: t('bots.remoteSettings.leaveDescription'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,54 @@ describe('Bot settings profile consolidation', () => {
expect(mocks.updateBotProfile).toHaveBeenCalledTimes(2);
});

// #12276, unit. A permanent Lead rejection is actionable and the user can
// discard the rejected draft to leave settings and use the saved route.
it('lets a Lead discard an unsupported model choice and leave the model page', async () => {
mocks.updateBotProfile.mockRejectedValue(createIpcError(
'UNSUPPORTED_CAPABILITY', 'BOT_LEAD_PLUGIN_ENGINE_UNSUPPORTED: Choose a built-in engine.',
));
const view = renderSettings({ capabilities: capabilities({ modelChainOverride: capabilities().modelChain }) });
fireEvent.click(screen.getByRole('button', { name: 'bots.settingsTabs.model' }));
fireEvent.click(within(screen.getByTestId('bot-primary-model-controls')).getByTestId('codex-model-selector'));
expect((await screen.findByRole('alert')).textContent).toContain('bots.autosave.leadPluginEngineUnsupported');
expect(screen.queryByText('bots.autosave.retry')).toBeNull();

fireEvent.click(screen.getByRole('button', { name: 'bots.settingsBack' }));
fireEvent.click(await screen.findByRole('button', { name: 'bots.memory.discard' }));
await screen.findByRole('button', { name: 'bots.settingsTabs.model' });
const attempts = mocks.updateBotProfile.mock.calls.length;
view.unmount();
expect(mocks.updateBotProfile).toHaveBeenCalledTimes(attempts);
});

// #12276, unit. The first Back click must use the receipt from the pending save.
it.each(['rejected', 'saved'] as const)('handles Back during a model save that is %s', async (outcome) => {
let settle!: () => void;
if (outcome === 'rejected') {
const error = createIpcError('UNSUPPORTED_CAPABILITY', 'BOT_LEAD_PLUGIN_ENGINE_UNSUPPORTED: Choose a built-in engine.');
mocks.updateBotProfile.mockRejectedValue(error);
mocks.updateBotProfile.mockImplementationOnce(() => new Promise((_, reject) => {
settle = () => reject(error);
}));
} else {
mocks.updateBotProfile.mockImplementationOnce((id, patch) => new Promise(resolve => {
settle = () => resolve({ id, currentVersion: 2, ...patch });
}));
}
renderSettings({ capabilities: capabilities({ modelChainOverride: capabilities().modelChain }) });
fireEvent.click(screen.getByRole('button', { name: 'bots.settingsTabs.model' }));
fireEvent.click(within(screen.getByTestId('bot-primary-model-controls')).getByTestId('codex-model-selector'));
await waitFor(() => expect(mocks.updateBotProfile).toHaveBeenCalledTimes(1));
fireEvent.click(screen.getByRole('button', { name: 'bots.settingsBack' }));
expect(screen.queryByRole('button', { name: 'bots.memory.discard' })).toBeNull();
await act(async () => { settle(); });
if (outcome === 'rejected') {
fireEvent.click(await screen.findByRole('button', { name: 'bots.memory.discard' }));
}
await screen.findByRole('button', { name: 'bots.settingsTabs.model' });
expect(screen.queryByRole('button', { name: 'bots.memory.discard' })).toBeNull();
});

it('keeps a same-model choice through a failed save and a newer host profile', async () => {
vi.useFakeTimers();
const primary: BotModelRoute = { harness: 'pi', model: 'custom-model', providerId: 'custom', effort: 'high', fastMode: false };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@ import type { BotCapabilities, BotProfileUpdatePatch } from './botStore';
import { reconcileBotCapabilityList } from '../../../shared/botCapabilitySelection';
import { extractIpcError } from '../../../shared/ipcError';
import { readBotProfileSource, BotProfileSourceTooLong } from '../../../shared/botProfileSources';
import { BOT_LEAD_PLUGIN_ENGINE_UNSUPPORTED } from '../../../shared/botModelChain';

/** Bounds the UI wait, not the host transaction: a timeout cannot cancel a write. */
export const BOT_SETTINGS_SAVE_WAIT_MS = 30_000;
export const BOT_LEAD_PLUGIN_ENGINE_ERROR_KEY = 'bots.autosave.leadPluginEngineUnsupported';
export class BotSettingsSaveUnconfirmed extends Error {}

/** Only recognized causes become localized copy; never display raw host errors. */
Expand All @@ -51,7 +53,8 @@ export function botSettingsSaveErrorKey(error: unknown): string | null {
case 'DEVICE_LINK_DEVICE_UNRESPONSIVE':
return 'bots.remoteSettings.saveFailed';
case 'UNSUPPORTED_CAPABILITY':
return 'bots.remoteSettings.unsupported';
return failure.message.replace(/^\[UNSUPPORTED_CAPABILITY\]\s*/, '').startsWith(`${BOT_LEAD_PLUGIN_ENGINE_UNSUPPORTED}:`)
? BOT_LEAD_PLUGIN_ENGINE_ERROR_KEY : 'bots.remoteSettings.unsupported';
case 'PRECONDITION_FAILED':
return /伙伴配置已更新/.test(failure.message) ? 'bots.remoteSettings.conflict' : 'ipcError.PRECONDITION_FAILED';
default:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ export interface BotSettingsAutosaveController {
errorKey: string | null;
/** 字段变化:文本走防抖,离散选择走即时合并窗口。 */
onEdit: (trigger: BotAutosaveTrigger) => void;
/** blur / 返回聊天等显式边界的冲刷。 */
flush: () => Promise<void>;
/** Flush pending edits and return the latest error key for navigation guards. */
flush: () => Promise<string | null>;
/** 失败后重发。 */
retry: () => Promise<void>;
/** 是否有已改但未落库的内容。 */
Expand Down Expand Up @@ -103,6 +103,7 @@ export function useBotSettingsAutosave(
const [modelSelectionSaved, setModelSelectionSaved] = useState(false);
const completedModelSelectionRef = useRef(false);
const [errorKey, setErrorKey] = useState<string | null>(null);
const latestErrorKey = useRef<string | null>(null);
const savedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const mountedRef = useRef(true);

Expand All @@ -114,7 +115,8 @@ export function useBotSettingsAutosave(
}
setStatus(next);
setModelSelectionSaved(next === 'saved' && completedModelSelectionRef.current);
setErrorKey(next === 'error' ? botSettingsSaveErrorKey(error) : null);
latestErrorKey.current = next === 'error' ? botSettingsSaveErrorKey(error) : null;
setErrorKey(latestErrorKey.current);
if (next !== 'saved') return;
savedTimerRef.current = setTimeout(() => {
savedTimerRef.current = null;
Expand Down Expand Up @@ -183,9 +185,10 @@ export function useBotSettingsAutosave(
[autosave, captureIntentOwner],
);

const flush = useCallback(() => {
if (!enabledRef.current) return Promise.resolve();
return autosave.flush();
const flush = useCallback(async () => {
if (!enabledRef.current) return null;
await autosave.flush();
return latestErrorKey.current;
}, [autosave]);

const retry = useCallback(() => {
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/de/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11316,6 +11316,7 @@
"saved": "Gespeichert",
"unconfirmed": "Speichern nicht bestätigt",
"savedModel": "Gespeichert · ab nächstem Zug",
"leadPluginEngineUnsupported": "Dieser Chat ist der Lead der Zusammenarbeit. Wähle eine integrierte Engine.",
"retry": "Erneut speichern"
},
"retry": "Erneut versuchen",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11316,6 +11316,7 @@
"saved": "Saved",
"unconfirmed": "Save not confirmed",
"savedModel": "Saved · applies next turn",
"leadPluginEngineUnsupported": "This chat is the collaboration Lead. Choose a built-in engine.",
"retry": "Save Again"
},
"retry": "Retry",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/es/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11402,6 +11402,7 @@
"saved": "Guardado",
"unconfirmed": "Guardado sin confirmar",
"savedModel": "Guardado · desde el próximo turno",
"leadPluginEngineUnsupported": "Este chat es el Lead de la colaboración. Elige un motor integrado.",
"retry": "Guardar de nuevo"
},
"retry": "Reintentar",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/fr/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11402,6 +11402,7 @@
"saved": "Enregistré",
"unconfirmed": "Enregistrement non confirmé",
"savedModel": "Enregistré · dès le prochain tour",
"leadPluginEngineUnsupported": "Cette conversation est le Lead de la collaboration. Choisissez un moteur intégré.",
"retry": "Enregistrer à nouveau"
},
"retry": "Réessayer",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/ja/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11271,6 +11271,7 @@
"saved": "保存しました",
"unconfirmed": "保存を確認できません",
"savedModel": "保存済み・次のターンから適用",
"leadPluginEngineUnsupported": "この会話は協同の Lead です。組み込みのエンジンを選択してください。",
"retry": "再保存"
},
"retry": "再試行",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/ko/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11271,6 +11271,7 @@
"saved": "저장됨",
"unconfirmed": "저장을 확인하지 못함",
"savedModel": "저장됨 · 다음 턴부터 적용",
"leadPluginEngineUnsupported": "이 대화는 협업의 Lead입니다. 내장 엔진을 선택하세요.",
"retry": "다시 저장"
},
"retry": "다시 시도",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/pt-BR/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11402,6 +11402,7 @@
"saved": "Salvo",
"unconfirmed": "Salvamento não confirmado",
"savedModel": "Salvo · a partir do próximo turno",
"leadPluginEngineUnsupported": "Esta conversa é o Lead da colaboração. Escolha um motor integrado.",
"retry": "Salvar novamente"
},
"retry": "Tentar novamente",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/pt-PT/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11402,6 +11402,7 @@
"saved": "Guardado",
"unconfirmed": "Gravação não confirmada",
"savedModel": "Guardado · a partir do próximo turno",
"leadPluginEngineUnsupported": "Esta conversa é o Lead da colaboração. Escolhe um motor integrado.",
"retry": "Guardar novamente"
},
"retry": "Tentar novamente",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11271,6 +11271,7 @@
"saved": "已保存",
"unconfirmed": "尚未确认保存",
"savedModel": "已保存,下轮生效",
"leadPluginEngineUnsupported": "当前对话是协同 Lead,请选择内置引擎",
"retry": "重新保存"
},
"retry": "重试",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11271,6 +11271,7 @@
"saved": "已存",
"unconfirmed": "尚未核实存否",
"savedModel": "已存,下轮生效",
"leadPluginEngineUnsupported": "此对话为协同 Lead,请选内置引擎",
"retry": "再存"
},
"retry": "再试",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11271,6 +11271,7 @@
"saved": "已存",
"unconfirmed": "尚未核實存否",
"savedModel": "已存,下輪生效",
"leadPluginEngineUnsupported": "此對話為協同 Lead,請選內建引擎",
"retry": "再存"
},
"retry": "再試",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11271,6 +11271,7 @@
"saved": "已儲存",
"unconfirmed": "尚未確認儲存",
"savedModel": "已儲存,下輪生效",
"leadPluginEngineUnsupported": "目前對話是協同 Lead,請選擇內建引擎",
"retry": "重新儲存"
},
"retry": "重試",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/shared/botModelChain.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { normalizeCompanionModelRoute, modelRouteLocationKey, type CompanionModelRoute } from '@cindy/maker-shared/model-route';

export const BOT_MODEL_CHAIN_MAX = 5;
export const BOT_LEAD_PLUGIN_ENGINE_UNSUPPORTED = 'BOT_LEAD_PLUGIN_ENGINE_UNSUPPORTED';

export type BotHarness = CompanionModelRoute['harness'];

Expand Down
Loading
Loading