Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
merge(main): preserve scheduled model recovery across profile saves
ylliuuu6604a91bd86e60
diff --cc apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex a4b610104c,8ecc6ef4de..a8ffba9019--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@@ -10042,6 -10046,185 +10046,195 @@@ describe('Bot self control uses the samdescribe('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 s.agent_kind AS agentKind, s.model, s.provider_id AS providerId, s.effort, s.fast_mode AS fastMode,+ s.scheduled_model_baseline AS baseline, json_array(p.id, p.current_version) AS profileRevision+ FROM sessions s JOIN bot_session_links l ON l.session_id = s.id+ JOIN bot_profiles p ON p.id = l.bot_id WHERE s.id = ?`)+ .get(sessionId) as ScheduledModelSelection & { baseline: string | null; profileRevision: string };+ return { profile: { ...row, fastMode: !!row.fastMode }, baseline: row.baseline, profileRevision: row.profileRevision };+ };+ 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 };++ scheduledModelBaseline: state.baseline };+ }, apply,++ onSelectionAccepted: async (id, expected) => h.sqlite!.prepare(++ 'UPDATE sessions SET scheduled_model_baseline = NULL WHERE id = ? AND scheduled_model_baseline IS ?',++ ).run(id, expected ?? null).changes === 1,+ });+ 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: Parameters<typeof writeScheduledModelBaselineIfProfileCurrent>[2] | null, revision?: string | null) => {+ if (baseline) return writeScheduledModelBaselineIfProfileCurrent({+ exec: async (sql, params) => h.sqlite!.prepare(sql).run(...params),+ }, sessionId, baseline, revision ?? null);+ 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: {+ // Combined settings also enter the permission commit fence from #6782.+ permissions: 'auto',+ 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();++ expect(JSON.parse((await read()).baseline!)).toMatchObject({ pendingBotProfileVersion: 2 });+ } else {+ await save();+ }+ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE id = ?').pluck().get(sessionId)).toBe('auto');+ // 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 review, DB tier: a lane linked after the follower snapshot has no+ // send lock in that save. The real IPC save and conditional baseline writer+ // must reject its post-commit write, rather than resurrect A after restart.+ it('fences a new lane baseline writer outside the model-save lock snapshot', async () => {+ let sessionId = '';+ const read = async () => {+ const row = h.sqlite!.prepare(`SELECT s.agent_kind AS agentKind, s.model, s.provider_id AS providerId,+ s.effort, s.fast_mode AS fastMode, s.scheduled_model_baseline AS baseline,+ json_array(p.id, p.current_version) AS profileRevision+ FROM sessions s JOIN bot_session_links l ON l.session_id = s.id+ JOIN bot_profiles p ON p.id = l.bot_id WHERE s.id = ?`).get(sessionId) as+ ScheduledModelSelection & { baseline: string | null; profileRevision: string };+ return { profile: { ...row, fastMode: !!row.fastMode }, baseline: row.baseline, profileRevision: row.profileRevision };+ };+ const db = { exec: async (sql: string, params: unknown[]) => h.sqlite!.prepare(sql).run(...params) };+ configureBotModelSelectionCoordinator(async (ids, operation) => {+ const lane = await ensureBotChannelLaneSession({ botId: 'bot-1', routeKey: 'im:feishu:fixture:g:save-race', title: 'New lane' });+ if (!lane.ok) throw new Error(lane.message);+ sessionId = lane.sessionId;+ expect(ids).not.toContain(sessionId);+ let reachedWrite!: () => void;+ const writing = new Promise<void>((resolve) => { reachedWrite = resolve; });+ let releaseWrite!: () => void;+ const committed = new Promise<void>((resolve) => { releaseWrite = resolve; });+ const scope = createScheduledModelScope({ read, createId: () => 'late-lane', isBusy: () => false,+ apply: async () => undefined,+ write: async (id, baseline, revision) => {+ if (!baseline) return;+ reachedWrite();+ await committed;+ return writeScheduledModelBaselineIfProfileCurrent(db, id, baseline, revision ?? null);+ },+ });+ const capture = scope.begin(sessionId);+ await writing;+ const result = await operation().finally(releaseWrite);+ await expect(capture).rejects.toThrow(ScheduledModelSelectionBusyError);+ return result;+ });+ await invoke('local-db:bots:update', { id: 'bot-1', capabilities: {+ modelChainOverride: [{ harness: 'codex', model: 'new-saved-model', providerId: null, effort: 'medium', fastMode: false }],+ } });- expect((await read()).baseline).toBeNull();++ expect(JSON.parse((await read()).baseline!)).toMatchObject({ pendingBotProfileVersion: 2 });+ const bot = await invoke('local-db:bots:get', 'bot-1');+ const apply = async (_id: string, route: ScheduledModelSelection) => {+ 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 cold = createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,+ read: async () => ({ chain: await modelSettings.readEffectiveBotModelChain(bot.capabilities),- current: (await read()).profile, hasRuntimeOverride: false, scheduledModelBaseline: null }), apply,++ current: (await read()).profile, hasRuntimeOverride: false, scheduledModelBaseline: (await read()).baseline }), apply,++ onSelectionAccepted: async (id, expected) => h.sqlite!.prepare(++ 'UPDATE sessions SET scheduled_model_baseline = NULL WHERE id = ? AND scheduled_model_baseline IS ?',++ ).run(id, expected ?? null).changes === 1,+ });+ expect(await cold.preview(sessionId)).toMatchObject({ model: 'new-saved-model' });+ const deps = { read, apply, isBusy: () => false, createId: () => 'retry', prepareBaseline: cold,+ write: async (id: string, baseline: Parameters<typeof writeScheduledModelBaselineIfProfileCurrent>[2] | null, revision?: string | null) => {+ if (baseline) return writeScheduledModelBaselineIfProfileCurrent(db, id, baseline, revision ?? null);+ h.sqlite!.prepare('UPDATE sessions SET scheduled_model_baseline = NULL WHERE id = ?').run(id);+ },+ };+ await createScheduledModelScope(deps).begin(sessionId);+ expect(JSON.parse((await read()).baseline!)).toMatchObject({ model: 'new-saved-model' });+ await apply(sessionId, { agentKind: 'pi', model: 'temporary', providerId: null, effort: null, fastMode: false });+ await createScheduledModelScope(deps).restore(sessionId);+ expect((await read()).profile).toMatchObject({ model: 'new-saved-model' });+ });++ // #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();++ expect(JSON.parse(readBaseline()!)).toMatchObject({ pendingBotProfileVersion: 3 });+ 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,++ scheduledModelBaseline: readBaseline(), hasRuntimeOverride: false }), apply,++ onSelectionAccepted: async (id, expected) => h.sqlite!.prepare(++ 'UPDATE sessions SET scheduled_model_baseline = NULL WHERE id = ? AND scheduled_model_baseline IS ?',++ ).run(id, expected ?? null).changes === 1,+ });+ 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());++ expect(readBaseline()).toBeNull();+ });+async function setupModelControl() {const canonical = await invoke('local-db:bots:create-canonical-session', {botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,diff --cc apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.tsindex 72c3e25380,b4a02ef527..a2f0fc4817--- a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts@@@ -2,11 -2,6 +2,11 @@@ import Database from 'better-sqlite3'import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { tx } from '../tx.js';+import { normalizeBotProfileModelChain } from '../../../ipc/botProfileVersioning';+import { createBotModelRouteReconciler } from '../../../../maker-ipc/botModelRouteReconciler';- import { createScheduledModelScope } from '../../../../maker-ipc/scheduledModelSelection';++import { createScheduledModelScope, writeScheduledModelBaselineIfProfileCurrent } from '../../../../maker-ipc/scheduledModelSelection';+import { normalizeBotModelChain } from '../../../../../shared/botModelChain';+import type { ScheduledModelSelection } from '../../../../maker-ipc/scheduledModelSelection';describe('Bot named worker transactions', () => {let db: Database.Database;@@@ -55,253 -50,6 +55,258 @@@afterEach(() => db.close());+ // #6759: exercise the actual save transaction, then discard process-local+ // reconciliation state before IM preparation and automation restore.+ function savedModelFixture() {+ const original: ScheduledModelSelection = {+ agentKind: 'codex', model: 'old', providerId: 'connected-custom', effort: 'high', fastMode: false,+ };+ let current = { ...original, model: 'temporary' };+ let owner = 'account-a';+ const capabilities = (model: string) => JSON.stringify({ modelChain: [{+ harness: 'codex', model, providerId: 'connected-custom', effort: 'high', fastMode: false,+ }] });+ tx(db, { name: 'bots.createProfile', args: {+ id: 'saved-bot', displayName: 'Saved', description: '', avatar: '', avatarColor: 'blue',+ identitySource: 'identity', capabilitiesJson: capabilities('old'), now: 1,+ } });+ tx(db, { name: 'bots.replaceCanonicalSession', args: {+ botId: 'saved-bot', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ session: { id: 'saved-session', title: 'Saved', workingDir: '/tmp/saved-session',+ workspaceKind: 'dialogue', model: 'temporary', effort: 'high', permissionMode: 'ask',+ agentKind: 'codex', remoteHostId: null, providerId: 'connected-custom', extraDirs: '[]',+ source: 'bot', createdAt: 2, updatedAt: 2 }, now: 2,+ } });+ const readBaseline = () => db.prepare('SELECT scheduled_model_baseline FROM sessions WHERE id = ?')+ .pluck().get('saved-session') as string | null;+ const writeBaseline = (value: string | null) => {+ db.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?').run(value, 'saved-session');+ };+ writeBaseline(JSON.stringify({ ...original, scopeId: 'automation' }));+ const pause = (paused: boolean) => {+ db.prepare('UPDATE bot_profiles SET status = ? WHERE id = ?').run(paused ? 'paused' : 'active', 'saved-bot');+ };+ const save = (model: string, expectedCurrentVersion = 1, extra: Record<string, unknown> = {}) => tx(db, {+ name: 'bots.updateProfile', args: { id: 'saved-bot', expectedCurrentVersion,+ identitySource: 'identity', capabilitiesJson: capabilities(model), profileContentChanged: true, now: 3, ...extra },+ });+ let failApply = false;+ const reconcile = () => createBotModelRouteReconciler({+ ownerEpoch: () => owner,+ read: async () => {+ const row = db.prepare(`SELECT p.status, v.capabilities_json AS capabilities FROM bot_profiles p+ JOIN bot_profile_versions v ON v.bot_id = p.id AND v.version = p.current_version+ WHERE p.id = 'saved-bot'`).get() as { status: string; capabilities: string };+ return row.status === 'active' ? {+ chain: normalizeBotModelChain(JSON.parse(row.capabilities).modelChain), current,+ hasRuntimeOverride: false, scheduledModelBaseline: readBaseline(),+ } : null;+ },+ apply: async (_id, route) => {+ if (failApply) throw new Error('provider unavailable');+ current = { ...route, effort: route.effort as ScheduledModelSelection['effort'] };+ },+ onSelectionAccepted: async () => { writeBaseline(null); },+ });+ const scopeDeps: Parameters<typeof createScheduledModelScope>[0] = {- read: async () => ({ profile: current, baseline: readBaseline() }),- write: async (sessionId, baseline, expectedBaseline) => {- if (baseline) return tx(db, { name: 'sessions.createScheduledModelBaseline', args: {- sessionId, baseline: JSON.stringify(baseline), expectedBaseline,- } }) as boolean;++ read: async () => ({ profile: current, baseline: readBaseline(),++ profileRevision: db.prepare("SELECT json_array(id, current_version) FROM bot_profiles WHERE id = 'saved-bot'").pluck().get() as string,++ }),++ write: async (sessionId, baseline, revision, expectedBaseline) => {++ if (baseline) return writeScheduledModelBaselineIfProfileCurrent({++ exec: async (sql, params) => db.prepare(sql).run(...params),++ }, sessionId, baseline, revision ?? null, expectedBaseline);+ writeBaseline(null);+ },+ apply: async (_id, route) => { current = route; }, isBusy: () => false, createId: () => 'unused',+ };+ const scope = createScheduledModelScope(scopeDeps);+ return { original, readBaseline, pause, save, reconcile, scope, scopeDeps, writeBaseline, current: () => current,+ changeOwner: () => { owner = 'account-b'; }, failApply: (fail: boolean) => { failApply = fail; } };+ }++ // Permission-only saves can now create a Profile version without model input.+ // Exercise their intersection with the durable automation restore transaction.+ it.each([false, true])('preserves the fallback on a permission-only save (stale payload: %s)', async stalePayload => {+ const h = savedModelFixture();+ const baseline = h.readBaseline();+ expect(tx(db, { name: 'bots.updateProfile', args: {+ id: 'saved-bot', expectedCurrentVersion: 1, now: 3, profileContentChanged: false,+ canonicalPermissionMode: 'bypassPermissions',+ ...(stalePayload ? { capabilitiesJson: JSON.stringify({ model: 'stale' }) } : {}),+ } })).toEqual({ currentVersion: 2 });+ expect(h.readBaseline()).toBe(baseline);+ const saved = db.prepare('SELECT identity_source AS identity, capabilities_json AS config FROM bot_profile_versions WHERE version = 2')+ .get() as { identity: string; config: string };+ expect(saved.identity).toBe('identity');+ expect(JSON.parse(saved.config)).toMatchObject({ permissions: 'trusted', modelChain: [{ model: 'old' }] });+ expect(db.prepare('SELECT permission_mode FROM sessions').pluck().get()).toBe('bypassPermissions');+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current()).toMatchObject(h.original);+ });++ it('accepts a model save without reverting a newer permission choice', async () => {+ const h = savedModelFixture();+ tx(db, { name: 'bots.persistSessionPermission', args: { sessionId: 'saved-session', mode: 'bypassPermissions' } });+ h.save('permanent');+ expect(JSON.parse(h.readBaseline()!)).toMatchObject({ pendingBotProfileVersion: 2 });+ expect(JSON.parse(db.prepare('SELECT capabilities_json FROM bot_profile_versions WHERE version = 2').pluck().get() as string))+ .toMatchObject({ permissions: 'trusted' });+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('permanent');+ expect(h.readBaseline()).toBeNull();+ expect(db.prepare('SELECT permission_mode FROM sessions').pluck().get()).toBe('bypassPermissions');+ });++ it('keeps the baseline and permission when the expected Profile version is missing', () => {+ const h = savedModelFixture();+ const baseline = h.readBaseline();+ db.prepare('DELETE FROM bot_profile_versions').run();+ expect(() => h.save('permanent', 1, { canonicalPermissionMode: 'bypassPermissions' }))+ .toThrowError(expect.objectContaining({ code: 'PRECONDITION_FAILED' }));+ expect(h.readBaseline()).toBe(baseline);+ expect(db.prepare('SELECT permission_mode FROM sessions').pluck().get()).toBe('ask');+ expect(db.prepare('SELECT current_version FROM bot_profiles').pluck().get()).toBe(1);+ });++ it.each(['restart', 'account-change'])('accepts a paused permanent save after %s before restoring automation', async boundary => {+ const h = savedModelFixture();+ h.pause(true);+ let reconcile = h.reconcile();+ h.save('permanent');+ await reconcile.profileChanged('saved-session');+ if (boundary === 'restart') reconcile = h.reconcile();+ else h.changeOwner();+ h.pause(false);+ await reconcile('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('permanent');+ expect(h.readBaseline()).toBeNull();+ });++ it('accepts a same-route permanent save after restart without restoring the old provider choice', async () => {+ const h = savedModelFixture();+ h.pause(true);+ h.save('temporary');+ h.pause(false);+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('temporary');+ expect(h.readBaseline()).toBeNull();+ });++ it('keeps the durable save and old baseline on failure, without restoring it while paused', async () => {+ const h = savedModelFixture();+ h.pause(true);+ h.save('permanent');+ const pending = h.readBaseline();+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('temporary');+ expect(h.readBaseline()).toBe(pending);+ h.pause(false);+ h.failApply(true);+ await expect(h.reconcile()('saved-session')).rejects.toThrow('provider unavailable');+ expect(h.readBaseline()).toBe(pending);+ h.failApply(false);+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('permanent');+ });++ it('does not invalidate a baseline for a non-model profile edit or a rejected save', async () => {+ const h = savedModelFixture();+ const baseline = h.readBaseline();+ h.save('old', 1, { identitySource: 'new identity' });+ expect(h.readBaseline()).toBe(baseline);+ expect(() => h.save('permanent')).toThrow('Profile');+ expect(h.readBaseline()).toBe(baseline);+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current()).toMatchObject(h.original);+ });++ it.each(['canonical', 'group', 'channel', 'thread', 'background', 'archived'])('marks only following profile links: %s', role => {+ const h = savedModelFixture();+ const baseline = h.readBaseline();+ if (role === 'archived') db.prepare('UPDATE bot_session_links SET archived_at = 4').run();+ else db.prepare('UPDATE bot_session_links SET role = ?').run(role);+ h.save('permanent');+ if (role === 'background' || role === 'archived') expect(h.readBaseline()).toBe(baseline);+ else expect(JSON.parse(h.readBaseline()!)).toMatchObject({ pendingBotProfileVersion: 2, model: 'old' });+ });++ it('rolls back the pending marker with a failed profile transaction', () => {+ const h = savedModelFixture();+ const baseline = h.readBaseline();+ expect(() => h.save('permanent', 1, { canonicalPermissionMode: 'invalid' })).toThrow('permission mode');+ expect(h.readBaseline()).toBe(baseline);+ expect(db.prepare('SELECT current_version FROM bot_profiles').pluck().get()).toBe(1);+ expect(db.prepare('SELECT count(*) FROM bot_profile_versions').pluck().get()).toBe(1);+ });++ it('persists a permanent save even before the first automation scope exists', async () => {+ const h = savedModelFixture();+ h.writeBaseline(null);+ h.save('permanent');+ expect(JSON.parse(h.readBaseline()!)).toMatchObject({ pendingBotProfileVersion: 2 });+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('permanent');+ });++ it.each(['save-before-begin', 'save-during-begin', 'save-after-begin'].flatMap(order =>+ [null, '{broken'].map(initialBaseline => ({ order, initialBaseline })),+ ))('serializes the real scope writer and permanent save: $order / $initialBaseline', async ({ order, initialBaseline }) => {+ const h = savedModelFixture();+ h.writeBaseline(initialBaseline);+ const scope = createScheduledModelScope({ ...h.scopeDeps,+ write: async (...args) => {+ if (order === 'save-during-begin') h.save('permanent');+ return h.scopeDeps.write(...args);+ },+ });+ if (order === 'save-before-begin') h.save('permanent');- if (order === 'save-during-begin') await expect(scope.begin('saved-session')).rejects.toThrow('changed');++ if (order === 'save-before-begin') await expect(scope.begin('saved-session')).rejects.toThrow('pending');++ else if (order === 'save-during-begin') await expect(scope.begin('saved-session')).rejects.toThrow('changed');+ else await scope.begin('saved-session');+ if (order === 'save-after-begin') h.save('permanent');+ expect(JSON.parse(h.readBaseline()!)).toMatchObject({ pendingBotProfileVersion: 2 });+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('permanent');+ expect(h.readBaseline()).toBeNull();+ });+- it('keeps begin valid across an unrelated profile edit and across a rolled-back save', async () => {++ it('retries capture across an unrelated profile revision and preserves a rolled-back save', async () => {+ const h = savedModelFixture();+ h.writeBaseline(null);+ const scope = createScheduledModelScope({ ...h.scopeDeps, write: async (...args) => {+ expect(() => h.save('permanent', 1, { canonicalPermissionMode: 'invalid' })).toThrow('permission mode');+ h.save('old', 1, { identitySource: 'new identity' });+ return h.scopeDeps.write(...args);+ } });- await expect(scope.begin('saved-session')).resolves.toBe('unused');++ await expect(scope.begin('saved-session')).rejects.toThrow('changed');++ expect(h.readBaseline()).toBeNull();++ await expect(h.scope.begin('saved-session')).resolves.toBe('unused');+ expect(JSON.parse(h.readBaseline()!).pendingBotProfileVersion).toBeUndefined();+ });++ it('preserves runtime fallback when a non-model edit normalizes a legacy chain-only profile', async () => {+ const h = savedModelFixture();+ const fallback = { ...h.original, model: 'runtime-fallback', scopeId: 'automation' };+ h.writeBaseline(JSON.stringify(fallback));+ const previous = JSON.parse(db.prepare('SELECT capabilities_json FROM bot_profile_versions').pluck().get() as string);+ expect(previous.model).toBeUndefined();+ const next = normalizeBotProfileModelChain({ ...previous, skills: ['new-skill'] });+ h.save('old', 1, { capabilitiesJson: JSON.stringify(next), identitySource: 'edited identity' });+ expect(h.readBaseline()).toBe(JSON.stringify(fallback));+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('runtime-fallback');+ });+it('atomically rejects duplicate names and a second Cindy without touching the first profile', () => {const args = { id: 'first', displayName: 'Renamed', description: '', avatar: '🤖', avatarColor: 'blue', identitySource: 'Custom identity', capabilitiesJson: '{"templateId":"cindy"}', now: 1 };tx(db, { name: 'bots.createProfile', args });@@@ -382,6 -130,40 +387,44 @@@).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 };+ // Fail the permission write after restore retirement, not its early input+ // validation, so this still verifies rollback of the combined transaction.+ db.exec(`CREATE TRIGGER reject_permission_write BEFORE UPDATE OF permission_mode ON sessions+ BEGIN SELECT RAISE(ABORT, 'permission write failed'); END`);+ expect(() => tx(db, { name: 'bots.updateProfile', args: { ...args, canonicalPermissionMode: 'auto' } }))+ .toThrow('permission write failed');+ 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);+ db.exec('DROP TRIGGER reject_permission_write');+ 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']);++ const restores = db.prepare('SELECT id, scheduled_model_baseline AS baseline FROM sessions ORDER BY id')++ .all() as Array<{ id: string; baseline: string }>;++ for (const row of restores) {++ if (row.id === 'archived' || row.id === 'worker') expect(row.baseline).toBe('old-route');++ else expect(JSON.parse(row.baseline)).toMatchObject({ pendingBotProfileVersion: 2, model: 'temporary' });++ }+ expect(db.prepare('SELECT current_version FROM bot_profiles').pluck().get()).toBe(2);+ });// #6782: production worker transactions; unit tier. Existing tests do not// interleave a composer permission commit with a settings save captured earlier.it.each([['ask', 'bypassPermissions', 'trusted'], ['trusted', 'ask', 'ask']])(diff --cc apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 66d46ccde2,d4d38608b9..11a8cd4d6a--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@@ -480,30 -467,6 +470,30 @@@ function botsUpdateProfile(db: DatabaseVALUES (?, ?, ?, ?, ?, ?)`).run(`${id}:v${nextVersion}`, id, nextVersion, p.identitySource === undefined ? latest!.identity : expectString(p.identitySource, 'identitySource'),JSON.stringify(nextConfig), now);- if (botProfileModelSelectionChanged(latestConfig ?? {}, nextConfig ?? {})) {++ if (p.clearScheduledModelBaseline === true || botProfileModelSelectionChanged(latestConfig ?? {}, nextConfig ?? {})) {+ // Save the pending choice in the same transaction as the profile. A+ // paused runtime may not receive its refresh before restart/account exit.+ const targets = db.prepare(`SELECT id, scheduled_model_baseline AS baseline,+ agent_kind AS agentKind, model, provider_id AS providerId, effort, fast_mode AS fastMode+ FROM sessions 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)`)+ .all(id) as Array<{ id: string; baseline: string | null; agentKind: string; model: string;+ providerId: string | null; effort: string; fastMode: number | string }>;++ const update = db.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?');+ for (const target of targets) {+ // A save must also fence a begin that read a null baseline, or begins+ // before the async profile refresh. This record is never restored:+ // only acceptance of this permanent choice may consume it.+ const baseline = parseScheduledModelBaseline(target.baseline) ?? parseScheduledModelBaseline(JSON.stringify({+ scopeId: `${target.id}:profile:${nextVersion}`, agentKind: dbToMakerAgentKind(target.agentKind),+ model: target.model, providerId: target.providerId, effort: target.effort,+ fastMode: fastModeFromStorage(target.fastMode),+ }));+ if (baseline) update.run(JSON.stringify({ ...baseline, pendingBotProfileVersion: nextVersion }), target.id);+ }+ }// Hermes capability epoch: the permanent canonical Chat, the Bot's// group-chat lanes and its IM channel lanes follow the latest Profile on// their next runtime bootstrap. Route/worker links remain pinned to theirdiff --cc apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.tsindex 321b2c8f91,d2759a39bf..71a0d583ba--- a/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts@@@ -20,6 -18,48 +20,49 @@@ function harness()}describe('permanent Bot model selection', () => {+ // Real companion automation failed before queued dispatch because its ordinary+ // send reconciler switched back to the profile. Cover that consumer's decision,+ // including cold startup and companions following the global default (unit tier).+ it.each([false, true])('preserves an automation route across repeated sends and restart (default=%s)', async (followsCindyDefault) => {+ const h = harness();- const state = { ...h.state, followsCindyDefault, scheduledModelBaseline: { ...h.state.current } as SessionRuntimeProfile | null };++ const state = { ...h.state, followsCindyDefault, scheduledModelBaseline: JSON.stringify({ ...h.state.current, scopeId: 'automation' }) as string | null };+ const deps = { ownerEpoch: () => 'owner', read: async () => state, apply: h.apply };+ const reconcile = createBotModelRouteReconciler(deps);+ await reconcile('canonical');+ await reconcile('canonical');+ await createBotModelRouteReconciler(deps)('canonical');+ expect(h.apply).not.toHaveBeenCalled();+ state.scheduledModelBaseline = null;+ await reconcile('canonical');+ expect(h.apply).toHaveBeenCalledWith('canonical', expect.objectContaining({ model: 'luna' }), state.current);+ });+ // Capability grants apply to the next ordinary turn, including after restart.+ // The temporary automation route must not choose a different Harness catalog.+ it('previews the saved route without restoring or consuming it', async () => {+ const h = harness();+ const baseline = { ...h.state.current, agentKind: 'claude-code' as const, model: 'saved-model' };- const state = { ...h.state, scheduledModelBaseline: baseline };++ const state = { ...h.state, scheduledModelBaseline: JSON.stringify({ ...baseline, scopeId: 'automation' }) };+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => 'owner', read: async () => state, apply: h.apply });+ expect(await reconcile.preview('canonical')).toEqual(baseline);+ const draft = [{ harness: 'codex' as const, model: 'new-choice', providerId: 'xd', effort: 'medium', fastMode: false }];+ expect(await reconcile.preview('canonical', draft)).toMatchObject({ agentKind: 'codex', model: 'new-choice' });+ expect(await reconcile.preview('canonical')).toEqual(baseline);+ await reconcile('canonical');+ expect(h.apply).not.toHaveBeenCalled();- expect(state.scheduledModelBaseline).toEqual(baseline);++ expect(state.scheduledModelBaseline).toBe(JSON.stringify({ ...baseline, scopeId: 'automation' }));+ });+ it('lands a saved companion choice even when it equals the temporary automation route', async () => {+ const h = harness();- const state = { ...h.state, scheduledModelBaseline: { ...h.state.current } as SessionRuntimeProfile | null };- const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => 'owner', read: async () => state, apply: h.apply });++ const state = { ...h.state, scheduledModelBaseline: JSON.stringify({ ...h.state.current, scopeId: 'automation' }) as string | null };++ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => 'owner', read: async () => state, apply: h.apply, onSelectionAccepted: h.onSelectionAccepted });+ await reconcile('canonical');+ state.chain = [{ harness: 'pi', model: 'glm', providerId: 'xd', effort: 'high', fastMode: false }];+ await reconcile.profileChanged('canonical');+ // The landing callback must retire the old saved preference even for a no-op+ // runtime switch, so the next ordinary message cannot resurrect the old model.- expect(h.apply).toHaveBeenCalledExactlyOnceWith('canonical', state.current, state.current);++ expect(h.apply).not.toHaveBeenCalled();++ expect(h.onSelectionAccepted).toHaveBeenCalledExactlyOnceWith('canonical', state.scheduledModelBaseline);+ });it('stops a send instead of retaining the old runtime model when no enabled default remains', async () => {const h = harness();h.state.chain = [];diff --cc apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.tsindex 4e42c0cd02,80634a92d6..407e2f4de9--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts@@@ -58,6 -45,34 +58,52 @@@ describe('one-run automation model prefawait 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);+ });+ // #6895 unit regression: a lane outside the save's lock snapshot can see+ // Profile B after preparation applied A. Do not stamp A with B's revision.+ it('retries capture when the profile changes during route preparation', async () => {+ const h = scopeFixture();+ let profileRevision = 'A';+ const write = vi.fn(h.deps.write);+ const scope = createScheduledModelScope({ ...h.deps, write,+ read: async () => ({ ...await h.deps.read(), profileRevision }),+ prepareBaseline: async () => { profileRevision = 'B'; },+ });+ await expect(scope.begin('task')).rejects.toThrow(ScheduledModelSelectionBusyError);+ expect(write).not.toHaveBeenCalled();+ expect(h.state().baseline).toBeNull();+ });++ // Main's prepare hook and #6759's durable pending marker must agree before++ // a new automation captures its restore. Failure/owner change must retain it.++ it.each(['failed', 'unaccepted', 'owner-changed'] as const)('retains a pending permanent choice when preparation is %s', async (mode) => {++ const h = scopeFixture();++ await h.deps.write('task', { ...h.original, scopeId: 'pending', pendingBotProfileVersion: 2 });++ const before = h.state().baseline;++ let owner = 'a';++ const write = vi.fn(h.deps.write);++ const scope = createScheduledModelScope({ ...h.deps, write, ownerEpoch: () => owner,++ prepareBaseline: async () => {++ if (mode === 'failed') throw new Error('offline');++ if (mode === 'owner-changed') owner = 'b';++ },++ });++ await expect(scope.begin('task')).rejects.toThrow();++ expect(write).not.toHaveBeenCalled();++ expect(h.state().baseline).toBe(before);++ });// 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 --cc apps/desktop/src/main/maker-ipc/botModelRouteReconciler.tsindex 74a704443d,cbe1af6a87..f4aefe0a31--- a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts+++ b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts@@@ -28,6 -27,9 +28,9 @@@ function configuredRoute): RuntimeRoute | null {const key = JSON.stringify(chain);const isDraftChange = key !== JSON.stringify(state.chain);+ // An automation owns its temporary route until ordinary input restores it.+ // This also applies to companions following Cindy defaults and after restart.- if (!isDraftChange && state.scheduledModelBaseline && (previous === undefined || previous === key)) return null;++ if (!isDraftChange && parseScheduledModelBaseline(state.scheduledModelBaseline) && (previous === undefined || previous === key)) return null;if (!state.followsCindyDefault && !isDraftChange && state.hasRuntimeOverride && (previous === undefined || previous === key)) return null;const primary = chain[0];if (!primary) return null;@@@ -41,6 -43,6 +44,15 @@@};}++function savedRuntimeRoute(state: BotRouteState): RuntimeRoute | null {++ const baseline = parseScheduledModelBaseline(state.scheduledModelBaseline);++ if (!baseline || baseline.pendingBotProfileVersion) return null;++ const { agentKind, model, providerId, effort, fastMode } = baseline;++ return { agentKind, model, providerId, effort, fastMode,++ ...(state.current.agentDeviceId ? { agentDeviceId: state.current.agentDeviceId } : {}),++ };++}++function sameRoute(a: RuntimeRoute, b: RuntimeRoute): boolean {return a.agentKind === b.agentKind && a.model === b.model && a.providerId === b.providerId&& a.effort === b.effort && a.fastMode === b.fastMode && (a.agentDeviceId ?? null) === (b.agentDeviceId ?? null);@@@ -159,6 -153,7 +175,7 @@@ export function createBotModelRouteRecodraftChain ? normalizeBotModelChain(draftChain) : undefined,) ??state.next ??- state.scheduledModelBaseline ??++ savedRuntimeRoute(state) ??state.current);},diff --cc apps/desktop/src/main/maker-ipc/register.tsindex 8922be849d,673d6a56b8..7ba66693c9--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@@ -197,7 -199,7 +199,7 @@@ importreadInputDeliveryClientIds,} from '@cindy/device-link';import { and, asc, desc, eq, gte, inArray, isNull, like, lt, or, sql } from 'drizzle-orm';- import { applyScheduledModelSelection, createScheduledModelScope, createScheduledModelSelectionResolver, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';-import { applyScheduledModelSelection, createScheduledModelScope, writeScheduledModelBaselineIfProfileCurrent, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';++import { applyScheduledModelSelection, createScheduledModelScope, createScheduledModelSelectionResolver, writeScheduledModelBaselineIfProfileCurrent, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';import { parseScheduledModelBaseline } from '../../shared/scheduledModelBaseline';import { recordTurnModelChange, type TurnModelIdentity } from './turnModelChange';import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';@@@ -11081,14 -11112,9 +11110,14 @@@ export function registerMakerIpc(makereffort: row.effort, fastMode: row.fastMode,} } : null;},- write: async (sessionId, baseline, expectedBaseline) => {- write: async (sessionId, baseline, profileRevision) => {++ write: async (sessionId, baseline, profileRevision, expectedBaseline = null) => {+ const owner = captureSessionRuntimeControlOwnerEpoch();+ const client = getDbClient();if (baseline) {- const written = await client.tx('sessions.createScheduledModelBaseline', {- sessionId, baseline: JSON.stringify(baseline), expectedBaseline,- });- const written = await writeScheduledModelBaselineIfProfileCurrent(getDbClient(), sessionId, baseline, profileRevision ?? null);++ const written = await writeScheduledModelBaselineIfProfileCurrent(++ client, sessionId, baseline, profileRevision ?? null, expectedBaseline,++ );+ if (!sessionRuntimeControlOwnerEpochMatches(owner)) throw new Error('Account changed during scheduled model selection');if (written) await broadcastSessionRuntimeProjection(sessionId);return written;}diff --cc apps/desktop/src/main/maker-ipc/scheduledModelSelection.tsindex 86ab99319d,a72d971ed1..caeddd4a0d--- a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts@@@ -25,8 -25,9 +25,9 @@@ export function createScheduledModelScoeffort: ScheduledModelSelection['effort'] | '';};baseline: string | null;+ profileRevision?: string | null;} | null>;- write: (sessionId: string, baseline: ScheduledModelBaseline | null, expectedBaseline: string | null) => Promise<void | boolean>;- write: (sessionId: string, baseline: ScheduledModelBaseline | null, profileRevision?: string | null) => Promise<void | boolean>;++ write: (sessionId: string, baseline: ScheduledModelBaseline | null, profileRevision?: string | null, expectedBaseline?: string | null) => Promise<void | boolean>;isBusy: (sessionId: string) => boolean;apply: (sessionId: string, profile: ScheduledModelSelection) => Promise<void>;createId: () => string;@@@ -42,11 -44,25 +44,29 @@@assertOwner(owner);if (!row) return undefined;const existing = parseScheduledModelBaseline(row.baseline);-- if (existing) return existing.scopeId;++ if (existing && !existing.pendingBotProfileVersion) return existing.scopeId;+ const profileRevision = row.profileRevision;+ // 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;+ }+ if (row.profileRevision !== profileRevision) {+ throw new ScheduledModelSelectionBusyError('Companion profile changed during baseline preparation');+ }- const scopeId = deps.createId();- const written = await deps.write(sessionId, { ...row.profile, effort: row.profile.effort || null, scopeId }, profileRevision);- if (written === false) {- throw new ScheduledModelSelectionBusyError('Companion profile changed during baseline capture');++ const prepared = parseScheduledModelBaseline(row.baseline);++ if (prepared?.pendingBotProfileVersion) {++ throw new ScheduledModelSelectionBusyError('Permanent model selection is still pending');+ }++ if (prepared) return prepared.scopeId;+ const scopeId = deps.createId();- const written = await deps.write(sessionId, { ...row.profile, effort: row.profile.effort || null, scopeId }, row.baseline);++ const written = await deps.write(sessionId, { ...row.profile, effort: row.profile.effort || null, scopeId }, profileRevision, row.baseline);+ assertOwner(owner);+ if (written === false) throw new ScheduledModelSelectionBusyError('Scheduled model selection changed before scope creation');return scopeId;},async restore(sessionId: string, expectedScopeId?: string): Promise<void> {@@@ -62,13 -75,31 +82,34 @@@// Keep the saved choice on failure so the next input retries before dispatch.await deps.apply(sessionId, baseline);assertOwner(owner);- const written = await deps.write(sessionId, null, row!.baseline);- await deps.write(sessionId, null);++ const written = await deps.write(sessionId, null, row!.profileRevision, row!.baseline);+ assertOwner(owner);+ if (written === false) throw new ScheduledModelSelectionBusyError('Scheduled model selection changed before scope cleanup');},};}+ /** Fence even lanes linked after the settings save took its send-lock snapshot.+ * The revision is read with the route; checking and writing are one DB statement.+ * Ordinary sessions use null, so acquiring a companion link also invalidates capture.+ */+ export async function writeScheduledModelBaselineIfProfileCurrent(+ db: { exec: (sql: string, params: unknown[]) => Promise<{ changes: number }> },+ sessionId: string,+ baseline: ScheduledModelBaseline,+ profileRevision: string | null,++ expectedBaseline: string | null = null,+ ): Promise<boolean> {+ const result = await db.exec(`UPDATE sessions SET scheduled_model_baseline = ?- WHERE id = ? AND status = 'active'++ WHERE id = ? AND status = 'active' AND scheduled_model_baseline IS ?+ AND (SELECT json_array(p.id, p.current_version)+ FROM bot_session_links l JOIN bot_profiles p ON p.id = l.bot_id+ WHERE l.session_id = sessions.id AND l.archived_at IS NULL+ AND l.role IN ('canonical', 'group', 'channel', 'thread') LIMIT 1) IS ?`,- [JSON.stringify(baseline), sessionId, profileRevision]);++ [JSON.stringify(baseline), sessionId, expectedBaseline, profileRevision]);+ return result.changes === 1;+ }+export class ScheduledModelSelectionBusyError extends Error {}interface ScheduledModelTarget {