Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): persist saved model intent and guard shadow restores
Chrisd8fbff59a52a
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 12822688e6..ee3d123b6e 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -668,6 +668,8 @@ export interface BotsCreateProfileArgs {export interface BotsUpdateProfileArgs {id: string;+ /** A saved model choice supersedes automation restores in the same commit. */+ clearScheduledModelBaseline?: boolean;/** Explicit settings changes also update the permanent chat in this transaction. */canonicalPermissionMode?: 'ask' | 'auto' | 'bypassPermissions';displayName?: string;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 770659b224..9fb48f9bf8 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -9855,6 +9855,42 @@ describe('Bot self control uses the same profile authority as settings', () => {describe('Teammate model selection shares profile persistence and route reconciliation', () => {+ // #6895 DB regression: a crash after the profile commit but before the async+ // runtime refresh must not restore the superseded choice on the next cold send.+ it('commits a new model and retires its restore before runtime refresh, while unrelated edits retain it', async () => {+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ const sessionId = created.session.id;+ const baseline = JSON.stringify({ scopeId: 'automation', agentKind: 'pi', model: 'old-model', providerId: null, effort: null, fastMode: false });+ h.sqlite!.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?').run(baseline, sessionId);+ const readBaseline = () => (h.sqlite!.prepare('SELECT scheduled_model_baseline AS baseline FROM sessions WHERE id = ?').get(sessionId) as { baseline: string | null }).baseline;+ await invoke('local-db:bots:update', { id: 'bot-1', name: 'Renamed companion' });+ expect(readBaseline()).toBe(baseline);+ h.requestRuntimeRefresh.mockClear();+ const runTx = h.tx!;+ h.tx = async (name, args) => {+ const result = await runTx(name, args);+ if (name === 'bots.updateProfile') throw new Error('simulated process loss after commit');+ return result;+ };+ await expect(invoke('local-db:bots:update', { id: 'bot-1', capabilities: {+ modelChainOverride: [{ harness: 'codex', model: 'new-saved-model', providerId: null, effort: 'medium', fastMode: false }],+ } })).rejects.toThrow('simulated process loss after commit');+ expect(h.requestRuntimeRefresh).not.toHaveBeenCalled();+ expect(readBaseline()).toBeNull();+ const profile = await invoke('local-db:bots:get', 'bot-1');+ const chain = await modelSettings.readEffectiveBotModelChain(profile.capabilities);+ const apply = vi.fn();+ const cold = createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,+ read: async () => ({ chain, current: { agentKind: 'pi', model: 'temporary-model', providerId: null, effort: null, fastMode: false },+ scheduledModelBaseline: readBaseline() ? JSON.parse(readBaseline()!) : null, hasRuntimeOverride: false }), apply,+ });+ expect(await cold.preview(sessionId)).toMatchObject({ agentKind: 'codex', model: 'new-saved-model' });+ await cold(sessionId);+ expect(apply).toHaveBeenCalledWith(sessionId, expect.objectContaining({ agentKind: 'codex', model: 'new-saved-model' }), expect.anything());+ });+async function setupModelControl() {const canonical = await invoke('local-db:bots:create-canonical-session', {botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex c56f96b1c9..0ff772c968 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -1961,7 +1961,8 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,const normalizedNextConfig = normalizeBotModelCapabilitiesOrThrow(nextConfig);// Legacy chain-only profiles gain mirrored fields during normalization.// Compare the same representation so unrelated edits do not validate stale routes.- if (botProfileModelSelectionChanged(normalizeBotModelCapabilitiesOrThrow(previous), normalizedNextConfig)) {+ const modelSelectionChanged = botProfileModelSelectionChanged(normalizeBotModelCapabilitiesOrThrow(previous), normalizedNextConfig);+ if (modelSelectionChanged) {const primary = (await readEffectiveBotModelChain(normalizedNextConfig))[0];owner.assertCurrent();if (!primary || !await validateTaskModel(primary)) {@@ -1997,6 +1998,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,&& Object.prototype.hasOwnProperty.call(body.capabilities, 'permissions');await client.tx('bots.updateProfile', {id,+ ...(modelSelectionChanged ? { clearScheduledModelBaseline: true } : {}),...(changesPermissions ? { canonicalPermissionMode: botSessionPermissionMode(normalizedNextConfig) } : {}),...(patch.displayName !== undefined ? { displayName: patch.displayName } : {}),...(patch.description !== undefined ? { description: patch.description } : {}),@@ -2065,7 +2067,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,.limit(1);owner.assertCurrent();if (canonical) requestBotRuntimeEpochRefresh(canonical.sessionId,- botProfileModelSelectionChanged(previous, normalizedNextConfig) ? 'model' : 'profile');+ modelSelectionChanged ? 'model' : 'profile');}const profile = await readProfile(client, id);owner.assertCurrent();diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.tsindex 851e5a6eb8..4051882d56 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts@@ -13,7 +13,7 @@ describe('Bot named worker transactions', () => {CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT NOT NULL, working_dir TEXT, workspace_kind TEXT NOT NULL,model TEXT NOT NULL, effort TEXT NOT NULL, permission_mode TEXT NOT NULL, status TEXT NOT NULL,- scheduled_model_baseline TEXT,+ scheduled_model_baseline TEXT, agent_device_id TEXT,sdk_session_id TEXT, total_token_usage INTEGER NOT NULL, total_cost_usd REAL NOT NULL,context_tokens INTEGER NOT NULL, context_window INTEGER NOT NULL, fast_mode INTEGER NOT NULL,plan_mode_enabled INTEGER NOT NULL, cleared_at INTEGER, pinned_at INTEGER, user_send_at INTEGER,@@ -130,6 +130,37 @@ describe('Bot named worker transactions', () => {).toEqual({ hiddenAt: null, pinnedAt: null });});+ // #6895: model saves must retire only live profile-following restores, and+ // a later write failure must roll back both the profile and the restore clear.+ it('retires only active profile-following restores atomically with the model save', () => {+ tx(db, { name: 'bots.createProfile', args: {+ id: 'bot-1', displayName: 'Hermes', description: '', avatar: '🤖', avatarColor: 'violet',+ identitySource: 'identity', capabilitiesJson: '{}', now: 1,+ } });+ for (const role of ['canonical', 'group', 'channel', 'thread', 'worker', 'archived']) {+ db.prepare(`INSERT INTO sessions+ (id, title, workspace_kind, model, effort, permission_mode, status, total_token_usage,+ total_cost_usd, context_tokens, context_window, fast_mode, plan_mode_enabled, agent_kind,+ extra_dirs, source, created_at, updated_at, scheduled_model_baseline)+ VALUES (?, 'Hermes', 'dialogue', 'temporary', 'high', 'ask', 'active',+ 0, 0, 0, 0, 0, 0, 'codex', '[]', 'bot', 2, 2, 'old-route')`).run(role);+ db.prepare(`INSERT INTO bot_session_links+ (id, bot_id, session_id, profile_version, role, created_at, archived_at)+ VALUES (?, 'bot-1', ?, 1, ?, 2, ?)`).run(`link-${role}`, role, role === 'archived' ? 'channel' : role, role === 'archived' ? 3 : null);+ }+ const args = { id: 'bot-1', identitySource: 'identity', capabilitiesJson: '{"model":"new"}',+ profileContentChanged: true, expectedCurrentVersion: 1, clearScheduledModelBaseline: true, now: 4 };+ // The permission write follows restore retirement in this existing transaction.+ expect(() => tx(db, { name: 'bots.updateProfile', args: { ...args, canonicalPermissionMode: 'invalid' } }))+ .toThrow('Invalid canonical permission mode');+ expect(db.prepare('SELECT current_version FROM bot_profiles').pluck().get()).toBe(1);+ expect(db.prepare('SELECT COUNT(*) FROM sessions WHERE scheduled_model_baseline IS NOT NULL').pluck().get()).toBe(6);+ tx(db, { name: 'bots.updateProfile', args });+ expect(db.prepare('SELECT id FROM sessions WHERE scheduled_model_baseline IS NOT NULL ORDER BY id').pluck().all())+ .toEqual(['archived', 'worker']);+ expect(db.prepare('SELECT current_version FROM bot_profiles').pluck().get()).toBe(2);+ });+it('creates a local-first profile and keeps one permanent canonical Session', () => {tx(db, { name: 'bots.createProfile', args: {id: 'bot-1', displayName: 'Hermes', description: '', avatar: '🤖', avatarColor: 'violet',diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 61d3a37c31..24bf2d672d 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -372,6 +372,9 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersiif (avatarRef && p.avatar === undefined) {throw new Error('botAvatarRef requires an avatar address');}+ if (p.clearScheduledModelBaseline !== undefined && typeof p.clearScheduledModelBaseline !== 'boolean') {+ throw new Error('clearScheduledModelBaseline must be a boolean');+ }return db.transaction(() => {const current = db.prepare('SELECT current_version AS currentVersion, display_name AS displayName, avatar FROM bot_profiles WHERE id = ?').get(id) as { currentVersion: number; displayName: string; avatar: string } | undefined;@@ -444,6 +447,14 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersiWHERE bot_id = ? AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL`).run(nextVersion, id);}+ if (p.clearScheduledModelBaseline === true) {+ // Persist the user's new model intent atomically with the profile. A crash+ // before runtime refresh must not revive the superseded automation restore.+ // Frozen delegated tasks and archived lanes retain their own selection.+ db.prepare(`UPDATE sessions SET scheduled_model_baseline = NULL WHERE id IN+ (SELECT session_id FROM bot_session_links WHERE bot_id = ? AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL)`)+ .run(id);+ }if (p.canonicalPermissionMode !== undefined) {const mode = expectString(p.canonicalPermissionMode, 'canonicalPermissionMode');if (!['ask', 'auto', 'bypassPermissions'].includes(mode)) throw new Error('Invalid canonical permission mode');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.tsindex 7566d20e14..4606f2770f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts@@ -1,3 +1,4 @@+import { isShadowedCompanionCanonical } from '../botSessionInputGuard.js';import { createScheduledModelScope } from '../scheduledModelSelection.js';import { assertTaskActionCurrent, hasTaskActionAuthorization } from '../taskActionAuthorization.js';/**@@ -246,6 +247,29 @@ function botTaskDispatchHarness(// Execute that production closure with the real restore scope (unit behavior in// this existing guard fixture); assert the route used to send, not call strings.describe('companion internal delivery after automation', () => {+ // #6895: rejected input must not bootstrap the old primary or consume its restore.+ it.each(['already-shadowed', 'shadowed-while-waiting'] as const)('preserves automation state when %s', async (timing) => {+ let shadowed = timing === 'already-shadowed';+ let baseline: string | null = 'saved-pi-route';+ const restore = vi.fn(async () => { baseline = null; });+ const reconcile = vi.fn(async () => undefined);+ const dbChain = { from: () => dbChain, where: () => dbChain,+ limit: async () => [{ role: 'canonical', botId: 'companion' }] };+ const h = botTaskDispatchHarness({ child: { permissionMode: 'auto', planModeEnabled: false } }, {}, {+ getDbClient: () => ({ drizzle: { select: () => dbChain } }),+ isShadowedCompanionCanonical, isCompanionShadowed: () => shadowed,+ scheduledModelScope: { restore }, reconcileBotModelRoute: reconcile,+ waitForSendToSessionLock: async () => { shadowed = true; },+ });+ expect(await h.dispatchBotSessionMessage({ targetSessionId: 'child', message: 'Late cloud input' }))+ .toMatchObject({ ok: false, errorCode: 'AGENT_NOT_READY' });+ expect(baseline).toBe('saved-pi-route');+ expect(restore).not.toHaveBeenCalled();+ expect(h.bootstrapped).toEqual([]);+ expect(h.sentTo).toEqual([]);+ if (timing === 'already-shadowed') expect(reconcile).not.toHaveBeenCalled();+ });+it.each(['live', 'resumed'] as const)('restores before %s dispatch reads its model', async (path) => {const saved = { agentKind: 'pi' as const, model: 'saved-model', providerId: 'fixture-provider', effort: null, fastMode: false };let current = { ...saved, agentKind: 'codex' as 'codex' | 'pi', model: 'temporary-model' };diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 27e953a4d6..1ce77c9261 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -11500,6 +11500,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)persistedText: extractPlainText(persistedContent ?? message),};+ // Check before route/capability reconciliation, then again after waiting for+ // the send lock: a rejected old primary must not bootstrap or consume a restore.+ const rejectShadowedCompanion = async (sessionId: string) => {+ const [link] = await getDbClient().drizzle+ .select({ role: botSessionLinks.role, botId: botSessionLinks.botId })+ .from(botSessionLinks).where(eq(botSessionLinks.sessionId, sessionId)).limit(1);+ return isShadowedCompanionCanonical(link, isCompanionShadowed)+ ? { ok: false as const, errorCode: 'AGENT_NOT_READY' as const, message: SHADOWED_COMPANION_INPUT_MESSAGE }+ : null;+ };+if (targetSessionId) {try {await assertReviewExternalInputAllowed(targetSessionId);@@ -11511,6 +11522,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)message: error instanceof Error ? error.message : String(error),};}+ const shadowed = await rejectShadowedCompanion(targetSessionId);+ if (shadowed) return shadowed;await reconcileBotModelRoute(targetSessionId);const compactedRuntime = maker.getSession(targetSessionId);if (compactedRuntime) await refreshBotCapabilityEpochBeforeSend(compactedRuntime);@@ -11819,6 +11832,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)let lockStage = 'resolve-session-meta+row';const run = waitPrev.then(async () => {await assertTaskActionCurrent();+ const shadowed = await rejectShadowedCompanion(targetSessionId);+ if (shadowed) return shadowed;// Internal idle deliveries (including companion cloud-room input) bypass// the ordinary send transaction. Restore under this send lock before// reading metadata or dispatching; busy inputs defer to the queued path.@@ -11850,13 +11865,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)message: `session ${targetSessionId} is deleted`,};}- // Internal sends (plugins, tasks, routines) reach idle sessions without sendToAgentAccepted.- const [companionLink] = await getDbClient().drizzle- .select({ role: botSessionLinks.role, botId: botSessionLinks.botId })- .from(botSessionLinks).where(eq(botSessionLinks.sessionId, targetSessionId)).limit(1);- if (isShadowedCompanionCanonical(companionLink, isCompanionShadowed)) {- return { ok: false as const, errorCode: 'AGENT_NOT_READY' as const, message: SHADOWED_COMPANION_INPUT_MESSAGE };- }// 崩溃恢复:在路由决策前加载快照,确保恢复的排队 prompt 不被跳过。// 失败时 shouldQueueNewTurn 仍返回 true(未恢复即入队),消息不丢。@@ -16008,7 +16016,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await stageSessionRouteSelection(sessionId, { ...route, agentDeviceId: route.agentDeviceId ?? null }, current.agentKind);// A changed permanent companion choice supersedes the automation's saved// preference, even if it selects the already-running temporary model.- // Keep the old preference if staging fails; never detach IM default following.+ // Profile saves retire it atomically in the DB; other route changes retire+ // it only after staging succeeds. Never detach IM default following.await updateScheduledPreference(sessionId, null);// Consume the same model/Harness intent as the normal send path. Its// verified window protection and history handoff also apply here; a Botdiff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex cb851237dc..e4601547c3 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -371,7 +371,7 @@ harness + provider + model + effort + fastMode- 同一轮最多按生效候选链各尝试一次;不得循环。用户显式配置的链不得追加目录候选。- 同 harness 可在安全边界切模型;跨 harness 必须走既有 agent-switch / 交接重建事务。- 伙伴设置中的显式模型保存立即同步当前主任务的运行选择;空闲时在既有安全边界完成切换,运行中先记录最新选择,在回复、工具与审批结束后的安全边界接替,不要求用户再发一条消息才能登记。连续改选以最后一次为准,选回当前路由应取消不同的待切换路由。-- 自动化指定的临时模型在本轮发送中不被伙伴默认模型对齐覆盖,包括跟随全局默认的伙伴。主人随后保存新的伙伴模型选择时,该选择取代自动化留下的旧恢复偏好;即使新选择恰好等于临时运行模型,下一次聊天也不得恢复到旧选择。普通内部投递也在发送边界恢复原选择;能力设置预览使用下一轮普通聊天的选择,不因预览消费恢复记录。+- 自动化指定的临时模型在本轮发送中不被伙伴默认模型对齐覆盖,包括跟随全局默认的伙伴。主人随后保存新的伙伴模型选择时,在同一数据库事务中清除活跃主任务及群/IM 专线的旧恢复偏好,确保设置已保存但运行态刷新前退出也不会复活旧选择;即使新选择恰好等于临时运行模型,下一次聊天也不得恢复到旧选择。普通内部投递先拒绝已降级的伙伴副本,再在发送边界恢复原选择;能力设置预览使用下一轮普通聊天的选择,不因预览消费恢复记录。- 模型配置只保留统一选择器入口,备用链仍在原组件内折叠;思考深度、Fast 与 Harness 不拆成独立设置页。缩窗交接复用已经核实目标窗口的延迟选择处理,完整记录与主任务身份保留,不绕过原生副作用重放限制。- fallback 只改变当前任务的有效路由,不暗改 Profile 顺序。下一次确定性重建仍从首选开始。- 存量单模型配置归一成一项候选链,不能在升级时改变用户已有选择。