Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): persist pending Bot model saves across restart
ylliuuu66de0fa6caf8c9
diff --cc apps/desktop/src/main/localDb/ipc/botProfileVersioning.tsindex 7874aed8ae,7874aed8ae..d3aa2ba53f--- a/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts+++ b/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts@@@ -14,11 -14,11 +14,7 @@@ export function botProfileContentChange);}--/** A saved model selection supersedes an earlier runtime-only fallback. */--export function botProfileModelSelectionChanged(previous: Record<string, unknown>, next: Record<string, unknown>): boolean {-- return ['modelChainOverride', 'modelOverride', 'modelChain', 'harness', 'model', 'providerId', 'effort', 'fastMode']-- .some((key) => JSON.stringify(previous[key] ?? null) !== JSON.stringify(next[key] ?? null));--}++export { botProfileModelSelectionChanged } from '../../../shared/botModelChain.js';export function mergeBotProfileCapabilities(input: {previous: Record<string, unknown>;diff --cc apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.tsindex 851e5a6eb8,851e5a6eb8..1a09d70e92--- 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,6 -2,6 +2,10 @@@ import Database from 'better-sqlite3'import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { tx } from '../tx.js';++import { createBotModelRouteReconciler } from '../../../../maker-ipc/botModelRouteReconciler';++import { createScheduledModelScope } 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;@@@ -13,7 -13,7 +17,7 @@@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,@@@ -50,6 -50,6 +54,143 @@@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 scope = createScheduledModelScope({++ read: async () => ({ profile: current, baseline: readBaseline() }),++ write: async (_id, baseline) => writeBaseline(baseline ? JSON.stringify(baseline) : null),++ apply: async (_id, route) => { current = route; }, isBusy: () => false, createId: () => 'unused',++ });++ return { original, readBaseline, pause, save, reconcile, scope, current: () => current,++ changeOwner: () => { owner = 'account-b'; }, failApply: (fail: boolean) => { failApply = fail; } };++ }++++ 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('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 });diff --cc apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 0d8760aad5,61d3a37c31..9d1461e307--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@@ -4,6 -4,6 +4,8 @@@ import { runTaskTagsTransaction } fromimport { recordMediaSpend } from './mediaSpendTx.js';import { batchAutoReviewProjection, readAutoReviewProjectionTransaction } from '../../autoReviewProjection.js';import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from '../../sharedTaskClosureSql.js';++import { botProfileModelSelectionChanged } from '../../../../shared/botModelChain.js';++import { parseScheduledModelBaseline } from '../../../../shared/scheduledModelBaseline.js';import { normalizeBotName } from '../../../../shared/botCreation.js';import { inferBotTemplatePresetId } from '../../../../shared/botTemplatePreset.js';// inproc 回滚口:仅在 XDT_DB_INPROC=true 时使用。@@@ -436,6 -436,6 +438,23 @@@ function botsUpdateProfile(db: DatabaseVALUES (?, ?, ?, ?, ?, ?)`).run(`${id}:v${nextVersion}`, id, nextVersion, expectString(p.identitySource, 'identitySource'),expectString(p.capabilitiesJson, 'capabilitiesJson'), now);++ const previous = db.prepare('SELECT capabilities_json AS capabilities FROM bot_profile_versions WHERE bot_id = ? AND version = ?')++ .get(id, expectedVersion) as { capabilities: string } | undefined;++ if (botProfileModelSelectionChanged(++ parsedObjectJson(previous?.capabilities ?? null) ?? {}, parsedObjectJson(expectString(p.capabilitiesJson, 'capabilitiesJson')) ?? {},++ )) {++ // 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 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)++ AND scheduled_model_baseline IS NOT NULL`).all(id) as Array<{ id: string; baseline: string }>;++ const update = db.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?');++ for (const target of targets) {++ const baseline = parseScheduledModelBaseline(target.baseline);++ 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 82d6a40e03,812ace0933..321b2c8f91--- a/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts@@@ -237,161 -232,3 +237,188 @@@ it('reconciles shared-to-local and locaawait h.reconcile.profileChanged('canonical');expect(h.apply).toHaveBeenLastCalledWith('canonical', local, h.state.current);});++// #6759: exercise the production reconciler before scope.restore, as IM sends do.+// A restart can lose the override marker while retaining a fallback baseline.+// Existing save tests did not cover ordinary reconciliation that applies a route.+function automationHarness() {+ const h = harness();+ const original = { ...h.state.current, model: 'runtime-fallback' };+ let baseline: string | null = JSON.stringify({ ...original, scopeId: 'automation' });+ h.apply.mockImplementation(async (_id, route) => {+ h.state.current = { ...route, effort: route.effort as SessionRuntimeProfile['effort'] };+ });+ h.onSelectionAccepted.mockImplementation(async () => { baseline = null; });+ const scope = createScheduledModelScope({+ read: async () => ({ profile: h.state.current, baseline }),+ write: async (_id, value) => { baseline = value ? JSON.stringify(value) : null; },+ apply: async (_id, profile) => {+ const { agentKind, model, providerId, effort, fastMode } = profile;+ h.state.current = { agentKind, model, providerId, effort, fastMode };+ },+ isBusy: () => false, createId: () => 'unused',+ });+ return { ...h, original, scope, baseline: () => baseline };+}++it.each(['restart', 'changed-chain', 'pending-route', 'follow-default'] as const)(+ 'restores the saved fallback after ordinary IM preparation: %s', async scenario => {+ const h = automationHarness();+ const primary = { agentKind: 'codex' as const, model: 'luna', providerId: 'xd', effort: 'medium' as const, fastMode: false };+ if (scenario === 'changed-chain') {+ h.state.current = primary;+ await h.reconcile('canonical');+ h.state.chain[0].model = 'changed-default';+ }+ h.state.current = { ...primary, model: 'automation-model' };+ if (scenario === 'pending-route') {+ h.state.current = primary;+ h.state.next = { ...primary, model: 'pending-automation' };+ }+ if (scenario === 'follow-default') {+ h.state.hasRuntimeOverride = true;+ h.state.followsCindyDefault = true;+ }+ const baseline = h.baseline();+ await h.reconcile('canonical');+ expect(h.apply).toHaveBeenCalledOnce();+ expect(h.onSelectionAccepted).not.toHaveBeenCalled();+ expect(h.baseline()).toBe(baseline);+ await h.scope.restore('canonical', 'automation');+ expect(h.state.current).toEqual(h.original);+ expect(h.baseline()).toBeNull();+ },+);++it.each([true, false])('invalidates the automation baseline after an explicit save (already current: %s)', async alreadyCurrent => {+ const h = automationHarness();+ const permanent = { agentKind: 'codex' as const, model: 'luna', providerId: 'xd', effort: 'medium' as const, fastMode: false };+ h.state.current = alreadyCurrent ? permanent : { ...permanent, model: 'temporary-model' };+ if (alreadyCurrent) {+ await h.reconcile('canonical');+ expect(h.baseline()).not.toBeNull();+ }+ await h.reconcile.profileChanged('canonical');+ await h.scope.restore('canonical', 'automation');+ expect(h.state.current).toEqual(permanent);+ expect(h.baseline()).toBeNull();+ expect(h.onSelectionAccepted).toHaveBeenCalledOnce();+ expect(h.apply).toHaveBeenCalledTimes(alreadyCurrent ? 0 : 1);+});++it('retains the baseline and retries an explicit save whose staging failed', async () => {+ const h = automationHarness();+ const baseline = h.baseline();+ h.apply.mockRejectedValueOnce(new Error('provider unavailable'));+ await expect(h.reconcile.profileChanged('canonical')).rejects.toThrow('provider unavailable');+ expect(h.onSelectionAccepted).not.toHaveBeenCalled();+ expect(h.baseline()).toBe(baseline);+ await h.reconcile('canonical');+ expect(h.onSelectionAccepted).toHaveBeenCalledOnce();+ await h.scope.restore('canonical', 'automation');+ expect(h.state.current.model).toBe('luna');+});++it('retries an accepted save whose baseline cleanup failed, even when the route already matches', async () => {+ const h = automationHarness();+ const baseline = h.baseline();+ h.onSelectionAccepted.mockRejectedValueOnce(new Error('storage unavailable'));+ await expect(h.reconcile.profileChanged('canonical')).rejects.toThrow('storage unavailable');+ expect(h.baseline()).toBe(baseline);+ await h.reconcile('canonical');+ expect(h.apply).toHaveBeenCalledOnce();+ await h.scope.restore('canonical', 'automation');+ expect(h.state.current.model).toBe('luna');+ expect(h.baseline()).toBeNull();+});++it('keeps the baseline when a newer explicit save fails after an ordinary reconcile was in flight', async () => {+ const h = automationHarness();+ const baseline = h.baseline();+ let finish!: () => void;+ h.apply.mockImplementationOnce(() => new Promise<void>(resolve => { finish = resolve; }));+ const ordinary = h.reconcile('canonical');+ await vi.waitFor(() => expect(h.apply).toHaveBeenCalledOnce());+ h.state.chain[0].model = 'new-permanent';+ h.apply.mockRejectedValueOnce(new Error('new provider unavailable'));+ const explicit = h.reconcile.profileChanged('canonical');+ const results = Promise.allSettled([ordinary, explicit]);+ finish();+ expect((await results).map(result => result.status)).toEqual(['rejected', 'rejected']);+ expect(h.onSelectionAccepted).not.toHaveBeenCalled();+ expect(h.baseline()).toBe(baseline);+ await h.reconcile('canonical');+ expect(h.onSelectionAccepted).toHaveBeenCalledOnce();+ await h.scope.restore('canonical', 'automation');+ expect(h.state.current.model).toBe('new-permanent');+});++// A paused Bot is absent from the production apply reader, but its settings+// can still save a permanent selection. Resume must accept that selection+// before the next IM restores a surviving automation baseline.+it.each([true, false])('retains a paused save until resume (already current: %s)', async alreadyCurrent => {+ const h = automationHarness();+ let paused = true;+ h.read.mockImplementation(async (_id, purpose) => paused && purpose === 'apply' ? null : h.state);+ h.state.hasRuntimeOverride = true;+ if (alreadyCurrent) {+ h.state.current = { agentKind: 'codex', model: 'luna', providerId: 'xd', effort: 'medium', fastMode: false };+ }+ const baseline = h.baseline();+ await h.reconcile.profileChanged('canonical');+ await h.reconcile('canonical');+ await h.reconcile.preview('canonical');+ expect(h.apply).not.toHaveBeenCalled();+ expect(h.onSelectionAccepted).not.toHaveBeenCalled();+ expect(h.baseline()).toBe(baseline);+ paused = false;+ await h.reconcile('canonical');+ await h.scope.restore('canonical', 'automation');+ expect(h.state.current.model).toBe('luna');+ expect(h.baseline()).toBeNull();+ expect(h.onSelectionAccepted).toHaveBeenCalledOnce();+ expect(h.apply).toHaveBeenCalledTimes(alreadyCurrent ? 0 : 1);+});++it('retries a paused save after its first resumed route fails without losing the baseline', async () => {+ const h = automationHarness();+ h.state.hasRuntimeOverride = true;+ h.read.mockResolvedValueOnce(null);+ const baseline = h.baseline();+ await h.reconcile.profileChanged('canonical');+ h.apply.mockRejectedValueOnce(new Error('provider unavailable'));+ await expect(h.reconcile('canonical')).rejects.toThrow('provider unavailable');+ expect(h.baseline()).toBe(baseline);+ expect(h.onSelectionAccepted).not.toHaveBeenCalled();+ await h.reconcile('canonical');+ await h.scope.restore('canonical', 'automation');+ expect(h.state.current.model).toBe('luna');+ expect(h.baseline()).toBeNull();+});++++// A profile commit may precede its in-process refresh callback. A failed++// compare-and-set must reread the durable save, even without profileChanged.++it('rereads a newer durable save when acceptance loses its database compare-and-set', async () => {++ const h = harness();++ let baseline = JSON.stringify({ ...h.state.current, scopeId: 'automation', pendingBotProfileVersion: 2 });++ const accepted = vi.fn(async (_id: string, expected?: string | null) => {++ if (expected !== baseline) return false;++ baseline = '';++ return true;++ });++ const reconcile = createBotModelRouteReconciler({++ ownerEpoch: () => 'owner', read: async () => ({ ...h.state, scheduledModelBaseline: baseline }),++ onSelectionAccepted: accepted,++ apply: async (_id, route) => {++ h.state.current = { ...route, effort: route.effort as SessionRuntimeProfile['effort'] };++ if (route.model === 'luna') {++ h.state.chain = [{ ...h.state.chain[0]!, model: 'newest-model' }];++ baseline = JSON.stringify({ ...h.state.current, scopeId: 'automation', pendingBotProfileVersion: 3 });++ }++ },++ });++ await reconcile('canonical');++ expect(h.state.current.model).toBe('newest-model');++ expect(accepted).toHaveBeenCalledTimes(2);++ expect(baseline).toBe('');++});diff --cc apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.tsindex 61c9d1c58d,e68182e145..f95da5ead6--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts@@@ -250,174 -253,3 +253,174 @@@ describe('bound target Harness capabiliexpect(() => assertScheduledHarnessSupported(null, 'pi')).not.toThrow();});});++// #6745: invoke the same production resolver wired into register.ts with the+// real persisted-scope lifecycle; only catalog, storage and engine I/O are fakes.+const remoteChoice: ScheduledModelSelection = {+ agentKind: 'codex', model: 'test-model', providerId: 'openai-shared', effort: 'high', fastMode: false,+};+function remoteCatalog(id: string): ProviderView[] {+ return [{ id, connected: true, agents: ['codex'], routing: { codex: {} }, source: 'user', models: { codex: [{+ id: 'test-model', efforts: ['low', 'high'], defaultEffort: 'low', supportsFastMode: false,+ }] } }] as ProviderView[];+}+function remoteFixture(device: string | null = 'share:test', status = 'active') {+ let current = { ...remoteChoice, agentDeviceId: device };+ let baseline: string | null = JSON.stringify({ ...remoteChoice, scopeId: 'old-run' });+ const local = remoteCatalog('openai');+ const remote = vi.fn(async () => remoteCatalog('openai-shared'));+ const guard = vi.fn(async (_agent: string, _model: string, providerId: string | null) => {+ if (!local.some(p => p.id === providerId)) throw new Error('provider unavailable on this computer');+ return undefined;+ });+ const switchHarness = vi.fn(async () => ({ engineReady: true }));+ const applyModel = vi.fn(async (route: ScheduledModelSelection) => {+ current = { ...current, ...route };+ });+ const apply = async (_id: string, selection: ScheduledModelSelection) => applyScheduledModelSelection(selection, {+ getTarget: async () => status === 'missing' ? null : ({ ...current, status }),+ isBusy: () => false,+ resolveSelection: createScheduledModelSelectionResolver({+ readRemoteProviders: remote,+ resolveLocalSelection: async route => {+ await guard(route.agentKind, route.model, route.providerId);+ return resolveScheduledModelSelection(route, local);+ },+ }),+ switchHarness, applyModel,+ });+ const deps = {+ read: async () => ({ profile: current, baseline }),+ write: async (_id: string, value: unknown) => { baseline = value ? JSON.stringify(value) : null; },+ isBusy: () => false, createId: () => 'new-run',+ apply: async (id: string, profile: ScheduledModelSelection) => { await apply(id, profile); },+ };+ return { deps, apply, remote, guard, switchHarness, applyModel, scope: createScheduledModelScope(deps),+ state: () => ({ current, baseline }), save: (value: unknown) => { baseline = JSON.stringify(value); } };+}++describe('automation restore uses the execution computer', () => {+ it.each(['share:test', 'other-device'])('restores a legacy baseline on %s after restart', async device => {+ const h = remoteFixture(device);+ await createScheduledModelScope(h.deps).restore('task');+ expect(h.remote).toHaveBeenCalledWith(device, 'codex', 'test-model', 'openai-shared');+ expect(h.guard).not.toHaveBeenCalled();+ expect(h.applyModel).toHaveBeenCalledOnce();+ expect(h.state().baseline).toBeNull();+ expect(h.state().current).toMatchObject(remoteChoice);+ });+ it('validates an automation choice on the same remote execution computer', async () => {+ const h = remoteFixture();+ await h.apply('task', remoteChoice);+ expect(h.remote).toHaveBeenCalledWith('share:test', 'codex', 'test-model', 'openai-shared');+ expect(h.guard).not.toHaveBeenCalled();+ expect(h.switchHarness).not.toHaveBeenCalled();+ expect(h.state().current.agentDeviceId).toBe('share:test');+ });+ it('keeps ordinary local-provider validation for a local task', async () => {+ const h = remoteFixture(null);+ h.save({ ...remoteChoice, providerId: 'openai', scopeId: 'old-run' });+ await h.scope.restore('task');+ expect(h.guard).toHaveBeenCalledWith('codex', 'test-model', 'openai');+ expect(h.remote).not.toHaveBeenCalled();+ expect(h.state().current.providerId).toBe('openai');+ expect(h.state().baseline).toBeNull();+ });+ it('does not substitute a local provider when the remote catalog no longer contains the source', async () => {+ const h = remoteFixture();+ h.remote.mockResolvedValueOnce(remoteCatalog('another-source'));+ await expect(h.scope.restore('task')).rejects.toThrow('unavailable');+ expect(h.applyModel).not.toHaveBeenCalled();+ expect(h.guard).not.toHaveBeenCalled();+ expect(h.state().baseline).not.toBeNull();+ });+ it('preserves the standard admission exception for a custom user-owned model group', async () => {+ const h = remoteFixture();+ const views = remoteCatalog('openai-shared');+ const model = 'gpt-4o-audio-preview';+ views[0].models.codex![0].id = model;+ views[0].models.codex![0].group = 'custom:openai-shared';+ h.save({ ...remoteChoice, model, scopeId: 'old-run' });+ h.remote.mockResolvedValueOnce(views);+ await h.scope.restore('task');+ expect(h.state().baseline).toBeNull();+ expect(h.state().current).toMatchObject({ ...remoteChoice, model });+ });+ it.each([{ status: 'retired' }, { availability: 'requires_payment' }, { mode: 'image' }])(+ 'rejects a remote catalog entry outside new-route admission: %j', async flags => {+ const h = remoteFixture();+ const before = h.state();+ const views = remoteCatalog('openai-shared');+ Object.assign(views[0].models.codex![0], flags);+ h.remote.mockResolvedValueOnce(views);+ await expect(h.scope.restore('task')).rejects.toThrow('unavailable');+ expect(h.state()).toEqual(before);+ expect(h.applyModel).not.toHaveBeenCalled();+ expect(h.switchHarness).not.toHaveBeenCalled();+ },+ );+ it.each(['provider', 'model'] as const)('preserves the baseline when the remote %s is disabled after restart', async disabled => {+ const h = remoteFixture();+ const before = h.state();+ const views = remoteCatalog('openai-shared');+ if (disabled === 'provider') views[0].suspended = true;+ else views[0].models.codex![0].disabled = true;+ h.remote.mockResolvedValueOnce(views);+ await expect(h.scope.restore('task')).rejects.toThrow('unavailable');+ expect(h.state()).toEqual(before);+ expect(h.applyModel).not.toHaveBeenCalled();+ expect(h.switchHarness).not.toHaveBeenCalled();+ expect(h.guard).not.toHaveBeenCalled();+ });+ // #6759: the model can remain in the catalog after its Harness route is+ // removed or disabled. Exercise the production resolver and persisted restore.+ it.each(['agent-removed', 'route-missing', 'route-disabled'] as const)(+ 'preserves the baseline when the remote Harness is unavailable: %s', async reason => {+ const h = remoteFixture();+ const before = h.state();+ const views = remoteCatalog('openai-shared');+ if (reason === 'agent-removed') views[0].agents = [];+ else if (reason === 'route-missing') views[0].routing = {};+ else views[0].routing.codex!.disabled = true;+ h.remote.mockResolvedValueOnce(views);+ await expect(createScheduledModelScope(h.deps).restore('task')).rejects.toThrow('unavailable');+ expect(h.state()).toEqual(before);+ expect(h.applyModel).not.toHaveBeenCalled();+ expect(h.switchHarness).not.toHaveBeenCalled();+ expect(h.guard).not.toHaveBeenCalled();+ },+ );- it.each(['archived', 'deleted', 'missing'])('resolves the replacement locally for a %s target', async status => {++ it.each(['archived', 'deleted', 'missing'])('defers a %s replacement to the runner without querying either catalog', async status => {+ const h = remoteFixture('share:test', status);+ const before = h.state();+ h.remote.mockRejectedValue(new Error('REMOTE_AGENT_SHARE_PAUSED'));+ const localChoice = { ...remoteChoice, providerId: 'openai' };+ await expect(h.apply('task', localChoice)).resolves.toEqual(localChoice);+ expect(h.remote).not.toHaveBeenCalled();- expect(h.guard).toHaveBeenCalledWith('codex', 'test-model', 'openai');++ expect(h.guard).not.toHaveBeenCalled();+ expect(h.applyModel).not.toHaveBeenCalled();+ expect(h.switchHarness).not.toHaveBeenCalled();+ expect(h.state()).toEqual(before);+ });- it.each(['archived', 'deleted'])('rejects a remote-only source for the local replacement of a %s target', async status => {++ it.each(['archived', 'deleted'])('preserves the saved remote source for runner recovery of a %s target', async status => {+ const h = remoteFixture('share:test', status);- await expect(h.apply('task', remoteChoice)).rejects.toThrow('provider unavailable');++ await expect(h.apply('task', remoteChoice)).resolves.toEqual(remoteChoice);+ expect(h.remote).not.toHaveBeenCalled();+ expect(h.applyModel).not.toHaveBeenCalled();+ expect(h.switchHarness).not.toHaveBeenCalled();+ });+ it('retains the scope and task when the sharing host rejects access', async () => {+ const h = remoteFixture();+ h.remote.mockRejectedValueOnce(new Error('REMOTE_AGENT_SHARE_PAUSED'));+ await expect(h.scope.restore('task')).rejects.toThrow('REMOTE_AGENT_SHARE_PAUSED');+ expect(h.state().baseline).not.toBeNull();+ expect(h.applyModel).not.toHaveBeenCalled();+ expect(h.guard).not.toHaveBeenCalled();+ });+ it('rejects a missing local provider without guessing a remote source', async () => {+ const h = remoteFixture(null);+ await expect(h.scope.restore('task')).rejects.toThrow('provider unavailable');+ expect(h.remote).not.toHaveBeenCalled();+ expect(h.state().baseline).not.toBeNull();+ });+});diff --cc apps/desktop/src/main/maker-ipc/botModelRouteReconciler.tsindex 70cf904e60,671aa68771..74a704443d--- a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts+++ b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts@@@ -1,3 -1,3 +1,4 @@@++import { parseScheduledModelBaseline } from '../../shared/scheduledModelBaseline';import { throwIpcError } from '../utils/ipcValidate.js';import type { AgentKind } from '@cindy/maker-core';import { normalizeBotModelChain, type BotModelRoute } from '../../shared/botModelChain.js';@@@ -15,6 -15,6 +16,7 @@@ interface BotRouteStatechain: BotModelRoute[];current: RuntimeRoute;hasRuntimeOverride: boolean;++ scheduledModelBaseline?: string | null;followsCindyDefault?: boolean;next?: RuntimeRoute;}@@@ -53,8 -53,6 +55,8 @@@ export function createBotModelRouteRecowithSessionLock?<T>(sessionId: string, run: () => Promise<T>): Promise<T>;read(sessionId: string, purpose: 'apply' | 'preview'): Promise<BotRouteState | null>;apply(sessionId: string, route: RuntimeRoute, current: RuntimeRoute): Promise<void>;+ /** An accepted permanent choice supersedes temporary preferences, even without a switch. */- onSelectionAccepted?(sessionId: string): Promise<void>;++ onSelectionAccepted?(sessionId: string, expectedBaseline?: string | null): Promise<void | boolean>;}) {let owner: string | undefined;const configured = new Map<string, string>();@@@ -91,28 -87,23 +93,30 @@@throwIpcError('PRECONDITION_FAILED', '请先选择已开启的伙伴模型');}const key = JSON.stringify(state.chain);- const previous = configured.get(sessionId);- const route = configuredRoute(state, configured.get(sessionId));++ const previous = parseScheduledModelBaseline(state.scheduledModelBaseline)?.pendingBotProfileVersion++ ? '' : configured.get(sessionId);+ const route = configuredRoute(state, previous);if (!route) {configured.set(sessionId, key);return;}const current = state.current;- if (!sameRoute(route, current) || (state.next && !sameRoute(route, state.next))) {- try {- await deps.apply(sessionId, route, state.current);- } catch (error) {- // A failed obsolete selection must not discard a newer explicit save.- // Re-read its route and runtime state; never retry the same failure- // indefinitely or continue applying after the account owner changes.- if (deps.ownerEpoch() !== epoch) throw new Error('Bot model route owner changed');- if ((revisions.get(sessionId) ?? 0) !== revision) continue;- throw error;+ const needsApply = !sameRoute(route, current) || !!(state.next && !sameRoute(route, state.next));+ try {+ if (needsApply) await deps.apply(sessionId, route, current);+ if (deps.ownerEpoch() !== epoch) throw new Error('Bot model route owner changed');+ if ((revisions.get(sessionId) ?? 0) !== revision) continue;- // Only profileChanged's explicit-save marker supersedes the saved scope.++ // Only a durable save or profileChanged's explicit marker supersedes the scope.+ // Ordinary IM preparation can switch routes before automation restore.+ if (previous === '') {- await deps.onSelectionAccepted?.(sessionId);++ const accepted = await deps.onSelectionAccepted?.(sessionId, state.scheduledModelBaseline);++ if (accepted === false) continue; // A newer durable save won the compare-and-set.}+ } catch (error) {+ // A failed obsolete selection must not discard a newer explicit save.+ if (deps.ownerEpoch() !== epoch) throw new Error('Bot model route owner changed');+ if ((revisions.get(sessionId) ?? 0) !== revision) continue;+ throw error;}if (deps.ownerEpoch() !== epoch) throw new Error('Bot model route owner changed');if ((revisions.get(sessionId) ?? 0) !== revision) continue;@@@ -150,7 -141,7 +154,8 @@@return (configuredRoute(state,-- configured.get(sessionId),++ parseScheduledModelBaseline(state.scheduledModelBaseline)?.pendingBotProfileVersion++ ? '' : configured.get(sessionId),draftChain ? normalizeBotModelChain(draftChain) : undefined,) ??state.next ??diff --cc apps/desktop/src/main/maker-ipc/register.tsindex 15e4af83a0,9b29645615..6385557636--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@@ -10953,16 -11019,16 +11017,21 @@@ export function registerMakerIpc(maker});const updateScheduledPreference = async (sessionId: string, patch: { effort?: ScheduledModelSelection['effort']; fastMode?: ScheduledModelSelection['fastMode'] } | null,++ expectedBaseline?: string | null,) => {const db = getDbClient().drizzle;const [row] = await db.select({ baseline: sessions.scheduledModelBaseline }).from(sessions).where(eq(sessions.id, sessionId)).limit(1);const baseline = parseScheduledModelBaseline(row?.baseline);-- if (!baseline) return;-- await db.update(sessions).set({++ if (expectedBaseline !== undefined && row?.baseline !== expectedBaseline) return false;++ if (!baseline) return true;++ const updated = await db.update(sessions).set({scheduledModelBaseline: patch ? JSON.stringify({ ...baseline, ...patch }) : null,-- }).where(eq(sessions.id, sessionId));++ }).where(and(eq(sessions.id, sessionId), eq(sessions.scheduledModelBaseline, row.baseline!)))++ .returning({ id: sessions.id });++ if (!updated.length) return false;await broadcastSessionRuntimeProjection(sessionId);++ return true;};const updateSavedScheduledAxis = async (sessionId: string,@@@ -15882,7 -15944,6 +15947,7 @@@const reconcileBotModelRoute = createBotModelRouteReconciler({ownerEpoch: captureSessionRuntimeControlOwnerEpoch,- onSelectionAccepted: (sessionId) => updateScheduledPreference(sessionId, null),++ onSelectionAccepted: (sessionId, expectedBaseline) => updateScheduledPreference(sessionId, null, expectedBaseline),withSessionLock: withSendToSessionLock,read: async (sessionId, purpose) => {const [row] = await getDbClient().drizzle.select({@@@ -15893,6 -15954,6 +15958,7 @@@providerId: sessions.providerId,effort: sessions.effort,fastMode: sessions.fastMode,++ scheduledModelBaseline: sessions.scheduledModelBaseline,}).from(botSessionLinks).innerJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId)).innerJoin(botProfileVersions, and(@@@ -15919,6 -15980,6 +15985,7 @@@const live = maker.getSession(sessionId);return {chain: selection.chain,++ scheduledModelBaseline: row.scheduledModelBaseline,followsCindyDefault: selection.followsCindyDefault,current: {agentDeviceId: row.agentDeviceId,diff --cc apps/desktop/src/main/maker-ipc/scheduledModelSelection.tsindex 1d17b6db79,a265cd0f24..4e08eb4055--- a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts@@@ -54,6 -53,6 +53,9 @@@ export function createScheduledModelScoassertOwner(owner);const baseline = parseScheduledModelBaseline(row?.baseline);if (!baseline || (expectedScopeId && baseline.scopeId !== expectedScopeId)) return;++ // A permanent save owns the next selection, including across restart.++ // Keep its old baseline for retries until reconciliation accepts the save.++ if (baseline.pendingBotProfileVersion) return;// Keep the saved choice on failure so the next input retries before dispatch.await deps.apply(sessionId, baseline);assertOwner(owner);@@@ -105,22 -101,6 +107,22 @@@ export function resolveScheduledModelSe};}- /** Resolve against the bound execution computer; inactive replacements use the local path. */++/** Resolve against the bound execution computer; the runner owns inactive-target recovery. */+export function createScheduledModelSelectionResolver(deps: {+ readRemoteProviders: (deviceId: string, agent: AgentKind, model: string, providerId: string | null) => Promise<ProviderView[]>;+ resolveLocalSelection: (selection: ScheduledModelSelection) => Promise<ScheduledModelSelection>;+}) {+ return async (selection: ScheduledModelSelection, target?: ScheduledModelTarget | null): Promise<ScheduledModelSelection> => {+ if (target?.agentDeviceId && !target.remoteHostId) {+ const providers = await deps.readRemoteProviders(+ target.agentDeviceId, selection.agentKind, selection.model, selection.providerId,+ );+ return resolveScheduledModelSelection(selection, providers);+ }+ return deps.resolveLocalSelection(selection);+ };+}+/** Reuse the ordinary history handoff; never stage an automation intent on a busy task. */export async function applyScheduledModelSelection(selection: ScheduledModelSelection,diff --cc apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.tsindex d28f29872f,1aa831252a..1829935a24--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts@@@ -476,6 -591,38 +591,38 @@@ describe('MakerScheduleRunner model selexpect(mocks.setSessionEffort).toHaveBeenLastCalledWith(h.session.id, null);expect(mocks.backfillSessionMeta.mock.calls.at(-1)?.[2].effort).toBeUndefined();});++ // 自动化选了另一台电脑上的供应商:新建任务必须带上运行位置,并按那台的目录解析;本机停用轴+ // 与默认路由不参与(修复前本机裁决把那台的来源判成不可用,且任务建在本机)。+ it.each(['resolved', 'unavailable'] as const)('creates a fresh remote-agent task on its computer (%s)', async (outcome) => {+ const h = createSessionHarness();+ const remoteProviders = [{- id: 'remote-sub', name: 'Remote', connected: true, agents: ['claude-code'],++ id: 'remote-sub', name: 'Remote', connected: true, agents: ['claude-code'], routing: { 'claude-code': {} },+ models: { 'claude-code': [{ id: 'claude-opus-5-5', name: 'Opus', efforts: ['high'], defaultEffort: 'high' }] },+ }] as unknown as ProviderView[];+ const resolveModelSelection = vi.fn(async (choice: Parameters<typeof resolveScheduledModelSelection>[0],+ location?: { agentDeviceId: string }) => {+ if (outcome === 'unavailable') throw new Error('[REMOTE_AGENT_UNAVAILABLE] Selected remote provider or model is unavailable.');+ expect(location).toEqual({ agentDeviceId: 'studio' });+ return resolveScheduledModelSelection(choice, remoteProviders);+ });+ const checkModelRoute = vi.fn(async () => ({ kind: 'reject' as const, reason: 'explicit-source-unavailable' as const }));+ const resolveDefaultModelRoute = vi.fn(async () => null);+ // 建好的任务行带运行位置,派发前复核按那台电脑处理(生产 isAgentOnOtherDevice 读 sessions 行)。+ const harness = createRunnerHarness(h, null, { resolveModelSelection, checkModelRoute, resolveDefaultModelRoute,+ isAgentOnOtherDevice: async () => true });+ const schedule = baseSchedule({ modelAgentKind: 'claude-code', model: 'claude-opus-5-5',+ providerId: 'remote-sub', agentDeviceId: 'studio' });+ if (outcome === 'unavailable') {+ await expect(harness.runner.fire(schedule, createFireContext())).rejects.toThrow('REMOTE_AGENT_UNAVAILABLE');+ expect(harness.createSession).not.toHaveBeenCalled();+ } else {+ const opts = await fireToCompletion(harness, h, schedule);+ expect(opts).toMatchObject({ agentDeviceId: 'studio', providerId: 'remote-sub', model: 'claude-opus-5-5', effort: 'high' });+ }+ expect(checkModelRoute).not.toHaveBeenCalled();+ expect(resolveDefaultModelRoute).not.toHaveBeenCalled();+ });});describe('effort reconcile —— fire 时按所选模型能力 clamp(issue #456)', () => {diff --cc apps/desktop/src/shared/botModelChain.tsindex 2347ceee7b,2347ceee7b..218db833a6--- a/apps/desktop/src/shared/botModelChain.ts+++ b/apps/desktop/src/shared/botModelChain.ts@@@ -114,3 -114,3 +114,9 @@@ export function nextBotModelRoute}return null;}++++/** A saved model selection supersedes an earlier runtime-only fallback. */++export function botProfileModelSelectionChanged(previous: Record<string, unknown>, next: Record<string, unknown>): boolean {++ return ['modelChainOverride', 'modelOverride', 'modelChain', 'harness', 'model', 'providerId', 'effort', 'fastMode']++ .some((key) => JSON.stringify(previous[key] ?? null) !== JSON.stringify(next[key] ?? null));++}diff --cc apps/desktop/src/shared/scheduledModelBaseline.tsindex d3d128c509,d3d128c509..c4cd363134--- a/apps/desktop/src/shared/scheduledModelBaseline.ts+++ b/apps/desktop/src/shared/scheduledModelBaseline.ts@@@ -3,6 -3,6 +3,8 @@@ import type { MakerAgentKindWire } fro/** Only model preferences; native checkpoints and permission settings keep their own lifecycle. */export interface ScheduledModelBaseline {scopeId: string;++ /** Permanent profile save not yet accepted by the runtime; survives pause/restart. */++ pendingBotProfileVersion?: number;agentKind: MakerAgentKindWire;model: string;providerId: string | null;diff --cc docs/product-rules/model-selector-unified.mdindex 4838cffc65,78f4ac32ff..7b74dee1ba--- a/docs/product-rules/model-selector-unified.md+++ b/docs/product-rules/model-selector-unified.md@@@ -207,8 -207,6 +207,8 @@@绑定已有任务的自动化在保存时只更新自动化配置,下次触发时才通过现有任务切换流程应用完整选择;目标正忙时顺延,不能抢占当前轮次。新增的 `modelAgentKind` 标识显式 Harness 选择;旧记录不补默认值,继续跟随绑定任务的 Harness。选择“跟随”会清除整套显式覆盖,切换新建/绑定模式往返时保留用户已选配置。- 自动化应用模型以及恢复之前的模型偏好时,都按活动任务当前的 Agent 执行位置校验来源与模型,并遵守现有新路由准入(含停用、退役、付费与对话能力限制);同账号远程电脑和分享来源使用对应电脑的目录,不能拿本机目录判定不可用,也不能静默换成本机来源。重启后遗留的恢复记录沿用同一规则,无需补字段。绑定任务已归档、删除或缺失时,替代任务按 runner 的本机新建位置解析,不沿用旧执行电脑。伙伴永久模型选择成功处理后(包括选择已与当前临时模型一致、无需切换的情况),清除被新选择取代的旧自动化恢复记录,避免下一条普通消息恢复旧来源;登记失败仍保留原记录。普通伙伴协调即使需要切换路由,也不清除自动化恢复记录;只有明确的永久保存成功接受后才使旧记录失效。++自动化应用模型以及恢复之前的模型偏好时,都按活动任务当前的 Agent 执行位置校验来源与模型,并遵守现有新路由准入(含停用、退役、付费与对话能力限制);同账号远程电脑和分享来源使用对应电脑的目录,不能拿本机目录判定不可用,也不能静默换成本机来源。重启后遗留的恢复记录沿用同一规则,无需补字段。失效绑定的恢复由 runner 负责:普通已归档目标先恢复,删除或缺失目标按自动化保存的位置重建,不能查询失效目标的旧目录。伙伴永久模型选择成功处理后(包括选择已与当前临时模型一致、无需切换的情况),清除被新选择取代的旧自动化恢复记录,避免下一条普通消息恢复旧来源;登记失败仍保留原记录。普通伙伴协调即使需要切换路由,也不清除自动化恢复记录;只有明确的永久保存成功接受后才使旧记录失效。暂停期间的永久保存与恢复记录在同一事务中记录待接受版本,重启或切账号后仍可继续接受;并发更新通过版本对应的恢复记录比较写入,旧选择不能清除新保存。+项目自动化的 `schedules.json` 同样保存可选的 `modelAgentKind`,导出、加载与配置同步均保留该标记;删除标记时清除数据库中的覆盖,已有绑定任务不丢失。旧版 `version: 1` 文件无需补字段。自动触发前按实际来源、Harness 和模型的当前目录拷贝补齐或收敛 effort,并清除已不受支持的 Fast;仍有效的用户选择保持不变。---