Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): serialize saved models with automation baseline capture
Chrisacf90c5d0d02
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 9fb48f9bf8..72623aef59 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -26,6 +26,9 @@ import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';import { BOT_TEMPLATE_PRESET_IDENTITIES } from '../../../../shared/botTemplatePreset';import { normalizeWorkingDirForStorage } from '../../../../shared/workingDir';import { createBotModelRouteReconciler } from '../../../maker-ipc/botModelRouteReconciler';+import { configureBotModelSelectionCoordinator, createBotModelSelectionCoordinator } from '../../../maker-ipc/botModelSelectionCoordinator';+import { createScheduledModelScope, type ScheduledModelSelection } from '../../../maker-ipc/scheduledModelSelection';+import { acquireSendToSessionLock, withSendToSessionLock } from '../../../maker-ipc/sendToSessionLock';import type { BotModelRoute } from '../../../../shared/botModelChain';import type { AgentKind } from '@cindy/maker-core';import { createBotCapabilityService, type BotCapabilityServiceDeps, type BotCapabilityUpdate } from '../../../maker-ipc/botCapabilityService';@@ -543,6 +546,7 @@ beforeEach(async () => {poolCapped: false,});configureBotCanonicalReplacementCoordinator(async (_sessionId, operation) => operation());+ configureBotModelSelectionCoordinator(async (_sessionIds, operation) => operation());h.sqlite?.close();createDb();registerBotIpc();@@ -9855,6 +9859,74 @@ describe('Bot self control uses the same profile authority as settings', () => {describe('Teammate model selection shares profile persistence and route reconciliation', () => {+ // #6895 P1: the previous crash test stopped at the profile commit. A subsequent+ // automation could recreate A before runtime refresh. DB tier: exercise the+ // real save transaction, send locks, reconciler and baseline writer in both+ // orders, then restore through a fresh scope (no runtime refresh or timers).+ it.each(['save-first', 'automation-first'] as const)('does not resurrect an old route when %s races baseline capture', async (order) => {+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ const sessionId = created.session.id as string;+ const read = async () => {+ const row = h.sqlite!.prepare('SELECT agent_kind AS agentKind, model, provider_id AS providerId, effort, fast_mode AS fastMode, scheduled_model_baseline AS baseline FROM sessions WHERE id = ?')+ .get(sessionId) as ScheduledModelSelection & { baseline: string | null };+ return { profile: { ...row, fastMode: !!row.fastMode }, baseline: row.baseline };+ };+ const apply = async (_id: string, route: Omit<ScheduledModelSelection, 'effort'> & { effort: string | null }) => {+ h.sqlite!.prepare('UPDATE sessions SET agent_kind = ?, model = ?, provider_id = ?, effort = ?, fast_mode = ? WHERE id = ?')+ .run(route.agentKind, route.model, route.providerId, route.effort ?? '', Number(route.fastMode), sessionId);+ };+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,+ withSessionLock: withSendToSessionLock,+ read: async () => {+ const state = await read();+ const bot = await invoke('local-db:bots:get', 'bot-1');+ return { chain: await modelSettings.readEffectiveBotModelChain(bot.capabilities),+ current: state.profile, hasRuntimeOverride: true,+ scheduledModelBaseline: state.baseline ? JSON.parse(state.baseline) : null };+ }, apply,+ });+ let savingReachedLock!: () => void;+ const waiting = new Promise<void>((resolve) => { savingReachedLock = resolve; });+ configureBotModelSelectionCoordinator(createBotModelSelectionCoordinator({+ acquireSessionLock: (id) => { savingReachedLock(); return acquireSendToSessionLock(id); },+ invalidate: reconcile.invalidate,+ }));+ const deps = { read, apply, isBusy: () => false, createId: () => 'race-scope',+ prepareBaseline: (id: string) => reconcile(id, true),+ write: async (_id: string, baseline: unknown) => {+ h.sqlite!.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?')+ .run(baseline ? JSON.stringify(baseline) : null, sessionId);+ },+ };+ const scope = createScheduledModelScope(deps);+ const save = () => invoke('local-db:bots:update', { id: 'bot-1', capabilities: {+ modelChainOverride: [{ harness: 'codex', model: 'new-saved-model', providerId: null, effort: 'medium', fastMode: false }],+ } });+ if (order === 'automation-first') {+ const release = await acquireSendToSessionLock(sessionId);+ const saving = save();+ try {+ await waiting;+ await scope.begin(sessionId);+ expect(JSON.parse((await read()).baseline!).model).not.toBe('new-saved-model');+ } finally { release(); }+ await saving;+ expect((await read()).baseline).toBeNull();+ } else {+ await save();+ }+ // requestRuntimeRefresh is inert in this fixture: begin must align the saved+ // route itself rather than relying on the asynchronous refresh continuation.+ await withSendToSessionLock(sessionId, () => scope.begin(sessionId));+ expect(JSON.parse((await read()).baseline!)).toMatchObject({ agentKind: 'codex', model: 'new-saved-model' });+ await apply(sessionId, { agentKind: 'pi', model: 'temporary', providerId: null, effort: null, fastMode: false });+ await withSendToSessionLock(sessionId, () => createScheduledModelScope(deps).restore(sessionId));+ expect((await read()).profile).toMatchObject({ agentKind: 'codex', model: 'new-saved-model' });+ expect((await read()).baseline).toBeNull();+ });+// #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 () => {diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex 0ff772c968..9fae2d11e2 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -223,6 +223,7 @@ async function syncBotProfileFolder(}import { buildDefaultBotIdentity } from '../../../shared/botProfileDefaults.js';import { coordinateBotCanonicalReplacement } from '../../maker-ipc/botCanonicalReplacementCoordinator.js';+import { coordinateBotModelSelection } from '../../maker-ipc/botModelSelectionCoordinator.js';import { searchConversations } from '../conversationSearch.js';import { registerBotAutonomyIpc } from '../../bot-autonomy/ipc.js';import { signalBotAutonomyBotsChanged } from '../../bot-autonomy/botsChangedSignal.js';@@ -1996,26 +1997,35 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,owner.assertCurrent();const changesPermissions = body.capabilities != null && typeof body.capabilities === 'object'&& 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 } : {}),- ...(patch.avatar !== undefined ? { avatar: patch.avatar } : {}),- ...(patch.avatarColor !== undefined ? { avatarColor: patch.avatarColor } : {}),- ...(patch.status !== undefined ? { status: patch.status } : {}),- ...(hiddenAt !== undefined ? { hiddenAt } : {}),- ...(pinnedAt !== undefined ? { pinnedAt } : {}),- identitySource: nextIdentitySource,- capabilitiesJson: safeJson(normalizedNextConfig),- profileContentChanged,- expectedCurrentVersion: current.currentVersion,- clearBotAvatarRefs:- patch.avatar !== undefined &&- isManagedBotAvatarUrl(current.avatar) &&- !isManagedBotAvatarUrl(patch.avatar),- now,+ const modelFollowers = modelSelectionChanged ? await db.select({ sessionId: botSessionLinks.sessionId })+ .from(botSessionLinks).where(and(eq(botSessionLinks.botId, id),+ inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread']),+ isNull(botSessionLinks.archivedAt))) : [];+ await coordinateBotModelSelection(modelFollowers.map((link) => link.sessionId), async () => {+ // Lock acquisition can wait behind an automation. Recheck the account before+ // committing; the worker still owns the profile-version CAS and atomic clear.+ owner.assertCurrent();+ 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 } : {}),+ ...(patch.avatar !== undefined ? { avatar: patch.avatar } : {}),+ ...(patch.avatarColor !== undefined ? { avatarColor: patch.avatarColor } : {}),+ ...(patch.status !== undefined ? { status: patch.status } : {}),+ ...(hiddenAt !== undefined ? { hiddenAt } : {}),+ ...(pinnedAt !== undefined ? { pinnedAt } : {}),+ identitySource: nextIdentitySource,+ capabilitiesJson: safeJson(normalizedNextConfig),+ profileContentChanged,+ expectedCurrentVersion: current.currentVersion,+ clearBotAvatarRefs:+ patch.avatar !== undefined &&+ isManagedBotAvatarUrl(current.avatar) &&+ !isManagedBotAvatarUrl(patch.avatar),+ now,+ });});owner.assertCurrent();if (changesPermissions) {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.tsindex e5b7ceb2c5..9aee8686fd 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts@@ -45,6 +45,20 @@ describe('one-run automation model preferences', () => {await scope.restore('task');expect(h.state()).toEqual({ profile: h.original, baseline: null });});+ // #6895 unit regression: preparing a newly saved route may defer/fail. The+ // stale session row must not become durable recovery state in that case.+ it('does not capture an old baseline when preparing the saved choice fails', async () => {+ const h = scopeFixture();+ const prepareBaseline = vi.fn(async () => { throw new ScheduledModelSelectionBusyError('waiting'); });+ const scope = createScheduledModelScope({ ...h.deps, prepareBaseline });+ await expect(scope.begin('task')).rejects.toThrow(ScheduledModelSelectionBusyError);+ expect(h.state().baseline).toBeNull();+ await h.scope.begin('task');+ // Existing scopes preserve the owner's original choice without switching+ // away from the automation just to capture it again.+ expect(await scope.begin('task')).toBe('scope-1');+ expect(prepareBaseline).toHaveBeenCalledTimes(1);+ });// PR #6559 + #6579 integration: the persisted scope must restore an// Ultrafast owner after automation/restart. Existing cases used booleans;// minimal failure is baseline JSON with fastMode='ultrafast'. Unit tier.diff --git a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.tsindex 0db5bcbd40..cbe1af6a87 100644--- a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts+++ b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts@@ -126,13 +126,17 @@ export function createBotModelRouteReconciler(deps: {if (inFlight.get(sessionId) === operation) inFlight.delete(sessionId);}};+ const invalidate = (sessionId: string): void => {+ syncOwner();+ revisions.set(sessionId, (revisions.get(sessionId) ?? 0) + 1);+ configured.set(sessionId, '');+ };return Object.assign(reconcile, {+ invalidate,/** Explicit saves invalidate fallback even before the first send. A newer* save during an in-flight switch is reread before this promise settles. */profileChanged(sessionId: string): Promise<void> {- syncOwner();- revisions.set(sessionId, (revisions.get(sessionId) ?? 0) + 1);- configured.set(sessionId, '');+ invalidate(sessionId);return reconcile(sessionId);},/** Read-only preview: sharing the send decision must not consume a profile change. */diff --git a/apps/desktop/src/main/maker-ipc/botModelSelectionCoordinator.ts b/apps/desktop/src/main/maker-ipc/botModelSelectionCoordinator.tsnew file mode 100644index 0000000000..72bb3ef27a--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/botModelSelectionCoordinator.ts@@ -0,0 +1,33 @@+type Coordinator = <T>(sessionIds: readonly string[], operation: () => Promise<T>) => Promise<T>;++// LocalDB may load before Maker. No automation can race before runtime wiring.+let coordinator: Coordinator = async (_sessionIds, operation) => operation();++export function configureBotModelSelectionCoordinator(next: Coordinator): void {+ coordinator = next;+}++export function coordinateBotModelSelection<T>(sessionIds: readonly string[], operation: () => Promise<T>): Promise<T> {+ return coordinator(sessionIds, operation);+}++/** Serialize the profile transaction with baseline writers in every following lane.+ * Invalidation is synchronous: a queued automation must see the saved choice even+ * when the fire-and-forget runtime refresh has not acquired its lock yet. */+export function createBotModelSelectionCoordinator(deps: {+ acquireSessionLock(sessionId: string): Promise<() => void>;+ invalidate(sessionId: string): void;+}): Coordinator {+ return async (sessionIds, operation) => {+ const ids = [...new Set(sessionIds)].sort();+ const releases: Array<() => void> = [];+ try {+ for (const id of ids) releases.push(await deps.acquireSessionLock(id));+ const result = await operation();+ for (const id of ids) deps.invalidate(id);+ return result;+ } finally {+ for (const release of releases.reverse()) release();+ }+ };+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 59a50adfb6..f3fe8a7ad4 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -652,6 +652,7 @@ import { listBotRecallSessionIds } from '../localDb/botHistoryScope.js';import { createWireNoteMemory } from './wireNoteMemory.js';import { isBotCanonicalReplacementBusy } from './botCanonicalReplacementGuard.js';import { configureBotCanonicalReplacementCoordinator } from './botCanonicalReplacementCoordinator.js';+import { configureBotModelSelectionCoordinator, createBotModelSelectionCoordinator } from './botModelSelectionCoordinator.js';import { botSessionInputBlockReason, isShadowedCompanionCanonical, SHADOWED_COMPANION_INPUT_MESSAGE } from './botSessionInputGuard.js';import { configureBotRuntimeEpochRefreshRequest } from './botRuntimeEpochRefreshSignal.js';import { createGitSnapshotCoordinator } from '../maker-host/git-snapshot-host.js';@@ -11061,6 +11062,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const scheduledModelScope = createScheduledModelScope({createId,ownerEpoch: captureSessionRuntimeControlOwnerEpoch,+ prepareBaseline: async (sessionId) => {+ await reconcileBotModelRoute(sessionId, true);+ // Reconciliation applies idle companion choices through the normal switch+ // path. A deferred or failed switch must not become a stale new baseline.+ if (agentSwitchPending.get(sessionId) || getPendingSessionRuntimeMutation(sessionId)) {+ if (!isSessionIdleForRouteApply(sessionId)) {+ throw new ScheduledModelSelectionBusyError('Scheduled model selection waits for the saved companion route');+ }+ throwIpcError('HARNESS_SWITCH_NOT_READY', 'Saved companion route did not become ready');+ }+ },read: async (sessionId) => {const [row] = await getDbClient().drizzle.select({agentKind: sessions.agentKind, model: sessions.model, providerId: sessions.providerId,@@ -16109,6 +16121,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},});+ configureBotModelSelectionCoordinator(createBotModelSelectionCoordinator({+ acquireSessionLock: (sessionId) => acquireSendToSessionLock(sessionId),+ invalidate: (sessionId) => reconcileBotModelRoute.invalidate(sessionId),+ }));+readPendingAgentSwitchRouteHolder = (sessionId) => {const intent = agentSwitchPending.get(sessionId);return intentdiff --git a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.tsindex 5652e90244..de671c48e4 100644--- a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts@@ -31,6 +31,7 @@ export function createScheduledModelScope(deps: {apply: (sessionId: string, profile: ScheduledModelSelection) => Promise<void>;createId: () => string;ownerEpoch?: () => string;+ prepareBaseline?: (sessionId: string) => Promise<void>;}) {const assertOwner = (owner: string | undefined) => {if (owner !== deps.ownerEpoch?.()) throw new Error('Account changed during scheduled model selection');@@ -38,11 +39,20 @@ export function createScheduledModelScope(deps: {return {async begin(sessionId: string): Promise<string | undefined> {const owner = deps.ownerEpoch?.();- const row = await deps.read(sessionId);+ let row = await deps.read(sessionId);assertOwner(owner);if (!row) return undefined;const existing = parseScheduledModelBaseline(row.baseline);if (existing) return existing.scopeId;+ // Settings may have committed while their asynchronous runtime refresh is+ // still queued. Align the owner under this same send lease before capture.+ if (deps.prepareBaseline) {+ await deps.prepareBaseline(sessionId);+ assertOwner(owner);+ row = await deps.read(sessionId);+ assertOwner(owner);+ if (!row) return undefined;+ }const scopeId = deps.createId();await deps.write(sessionId, { ...row.profile, effort: row.profile.effort || null, scopeId });return scopeId;diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex e4601547c3..6353af5907 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 专线的旧恢复偏好,确保设置已保存但运行态刷新前退出也不会复活旧选择;即使新选择恰好等于临时运行模型,下一次聊天也不得恢复到旧选择。普通内部投递先拒绝已降级的伙伴副本,再在发送边界恢复原选择;能力设置预览使用下一轮普通聊天的选择,不因预览消费恢复记录。+- 自动化指定的临时模型在本轮发送中不被伙伴默认模型对齐覆盖,包括跟随全局默认的伙伴。主人随后保存新的伙伴模型选择时,在发送锁内以同一数据库事务清除活跃主任务及群/IM 专线的旧恢复偏好,并同步标记模型对齐失效;新自动化记录恢复选择前在同一发送锁内对齐已保存模型,避免异步运行态刷新尚未执行时重新写回旧选择。设置已保存但运行态刷新前退出也不会复活旧选择;即使新选择恰好等于临时运行模型,下一次聊天也不得恢复到旧选择。普通内部投递先拒绝已降级的伙伴副本,再在发送边界恢复原选择;能力设置预览使用下一轮普通聊天的选择,不因预览消费恢复记录。- 模型配置只保留统一选择器入口,备用链仍在原组件内折叠;思考深度、Fast 与 Harness 不拆成独立设置页。缩窗交接复用已经核实目标窗口的延迟选择处理,完整记录与主任务身份保留,不绕过原生副作用重放限制。- fallback 只改变当前任务的有效路由,不暗改 Profile 顺序。下一次确定性重建仍从首选开始。- 存量单模型配置归一成一项候选链,不能在升级时改变用户已有选择。