Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bots): 避免失效的模型恢复记录持续阻塞消息 (#7471)

xuzini-xzn8488be3c24b7
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botBaselineRecovery.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botBaselineRecovery.test.ts
new file mode 100644
index 0000000000..e6ea8c9541
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botBaselineRecovery.test.ts
@@ -0,0 +1,400 @@
+import { describe, expect, it, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
+import type { ProviderView } from '@cindy/model-providers';
+import { createIpcError } from '../../../shared/ipc-errors';
+import { checkDeviceRoute } from '../../remote-agent/controller/deviceRouteCheck';
+import { createBotModelRouteApplier, createBotModelRouteReconciler } from '../botModelRouteReconciler';
+import { applyScheduledModelSelection, createScheduledModelScope, createScheduledModelSelectionResolver, resolveScheduledModelSelection, type ScheduledModelSelection } from '../scheduledModelSelection';
+import { readSshCodexModelList } from '../../remote-ssh/codex-model-list';
+import type { BotModelRoute } from '../../../shared/botModelChain';
+import { projectSessionRuntimeControl } from '../sessionRuntimeControl';
+
+// Regression for #7177/#7428: an unavailable frozen selection used to reject
+// every input before dispatch, despite a usable saved companion configuration.
+// Exercise the real scope, reconciler and runtime applier together (unit tier).
+function fixture() {
+ const saved: ScheduledModelSelection = { agentKind: 'pi', model: 'saved', providerId: 'current', effort: null, fastMode: false };
+ const old = JSON.stringify({ ...saved, providerId: 'removed', scopeId: 'old' });
+ const state = { chain: [{ harness: 'pi' as const, model: saved.model, providerId: saved.providerId, effort: '' as const, fastMode: false }] as BotModelRoute[],
+ current: { ...saved }, hasRuntimeOverride: true, followsCindyDefault: false, scheduledModelBaseline: old as string | null };
+ let owner = 'one';
+ let activeBot = true;
+ let restoreError: Error | null = createIpcError('MODEL_SELECTION_UNAVAILABLE', 'old source unavailable');
+ const stage = vi.fn(async (_id: string, route: typeof state.current): Promise<typeof state.current | void> => { state.current = { ...route }; });
+ const clear = vi.fn(async (_id: string, expected?: string | null) => {
+ if (state.scheduledModelBaseline !== expected) return false;
+ state.scheduledModelBaseline = null;
+ return true;
+ });
+ const onApplied = vi.fn(async () => { state.scheduledModelBaseline = null; });
+ const applier = createBotModelRouteApplier({ stage, isIdle: () => true,
+ applyPendingSwitch: async () => {}, hasPendingSwitch: () => false, onApplied });
+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => owner,
+ read: async () => activeBot ? state : null, apply: applier, onSelectionAccepted: clear });
+ const write = vi.fn(async () => { throw new Error('normal restore must not write the old route after recovery'); });
+ const recover = vi.fn((id: string, baseline: string) => reconcile.recoverUnavailableBaseline(id, baseline));
+ const scope = createScheduledModelScope({ createId: () => 'new', ownerEpoch: () => owner, isBusy: () => false,
+ read: async () => ({ profile: state.current, baseline: state.scheduledModelBaseline }), write,
+ apply: async (_id, route) => { if (restoreError) throw restoreError; state.current = { ...route }; },
+ recoverUnavailableBaseline: recover });
+ return { old, state, saved, scope, reconcile, stage, clear, recover, write, onApplied,
+ setError: (error: Error | null) => { restoreError = error; },
+ changeOwner: () => { owner = 'two'; }, disableBot: () => { activeBot = false; } };
+}
+
+describe('automatic companion baseline recovery', () => {
+ it('accepts saved settings even when they equal the current route, then permits repeated input', async () => {
+ const h = fixture();
+ let dispatches = 0;
+ for (let i = 0; i < 3; i++) {
+ await h.scope.restore('bot');
+ await h.reconcile('bot', true);
+ dispatches++;
+ }
+ expect(dispatches).toBe(3);
+ expect(h.stage).toHaveBeenCalledTimes(1); // Must validate/apply even a no-op route.
+ expect(h.state.scheduledModelBaseline).toBeNull();
+ expect(h.state.current).toEqual(h.saved);
+ expect(h.clear).toHaveBeenCalledWith('bot', h.old);
+ expect(h.onApplied).not.toHaveBeenCalled(); // No unconditional early cleanup.
+ expect(h.write).not.toHaveBeenCalled(); // No old route persistence after fallback.
+ });
+ it('dispatches after the ordinary switch rebinds the saved provider', async () => {
+ const h = fixture();
+ h.stage.mockImplementation(async (_id, route) => {
+ const resolved = { ...route, providerId: 'xai' };
+ h.state.current = resolved;
+ return resolved;
+ });
+ await h.scope.restore('bot');
+ expect(h.state.current.providerId).toBe('xai');
+ expect(h.state.scheduledModelBaseline).toBeNull();
+ expect(h.clear).toHaveBeenCalledWith('bot', h.old);
+ });
+ // #7471 review: group membership is committed only by the pending switch.
+ // Unit: a valid member must unblock input; unrelated/stale bindings must not.
+ it.each(['local-group', 'remote-group', 'wrong-group', 'wrong-owner', 'stale-binding', 'wrong-model', 'wrong-harness'] as const)(
+ 'checks the committed group member before retiring a baseline: %s', async (outcome) => {
+ const h = fixture();
+ const groupDeviceId = outcome === 'local-group' ? null : 'group-owner';
+ const route = { ...h.saved, providerId: 'group-entry', agentDeviceId: groupDeviceId };
+ h.state.chain = [{ ...h.state.chain[0]!, providerId: route.providerId, agentDeviceId: groupDeviceId }];
+ let pending = false;
+ const applier = createBotModelRouteApplier({
+ stage: async () => { pending = true; return route; }, isIdle: () => true,
+ applyPendingSwitch: async () => {
+ h.state.current = { ...h.saved, providerId: 'member-provider', agentDeviceId: 'member-device',
+ ...(outcome === 'wrong-model' ? { model: 'unrelated' } : {}),
+ ...(outcome === 'wrong-harness' ? { agentKind: 'codex' as const } : {}) };
+ pending = false;
+ },
+ hasPendingSwitch: () => pending, onApplied: h.onApplied,
+ });
+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => 'one', read: async () => h.state,
+ apply: applier, onSelectionAccepted: h.clear,
+ readAppliedGroup: async () => outcome === 'stale-binding' ? null : ({
+ providerId: outcome === 'wrong-group' ? 'another-group' : route.providerId,
+ groupDeviceId: outcome === 'wrong-owner' ? 'another-owner' : groupDeviceId,
+ }),
+ });
+ if (outcome === 'local-group' || outcome === 'remote-group') {
+ await expect(reconcile.recoverUnavailableBaseline('bot', h.old)).resolves.toBe(true);
+ expect(h.state.scheduledModelBaseline).toBeNull();
+ expect(h.state.current.providerId).toBe('member-provider');
+ } else {
+ await expect(reconcile.recoverUnavailableBaseline('bot', h.old)).rejects.toThrow('did not become ready');
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ expect(h.clear).not.toHaveBeenCalled();
+ }
+ });
+ it.each([false, true])('preserves a later runtime fallback after recovery (default=%s)', async (followsCindyDefault) => {
+ const h = fixture();
+ h.state.followsCindyDefault = followsCindyDefault;
+ await h.scope.restore('bot');
+ h.state.current = { ...h.saved, model: 'working-fallback' };
+ await h.reconcile('bot', true);
+ await h.reconcile('bot', true);
+ expect(h.stage).toHaveBeenCalledTimes(1);
+ expect(h.state.current.model).toBe('working-fallback');
+ expect(await h.reconcile.preview('bot')).toEqual(h.state.current);
+ });
+ it('keeps recovery state when the configuration source changes during application', async () => {
+ const h = fixture();
+ h.stage.mockImplementation(async (_id, route) => {
+ h.state.current = { ...route };
+ h.state.followsCindyDefault = true;
+ });
+ await expect(h.scope.restore('bot')).rejects.toThrow('changed');
+ expect(h.clear).not.toHaveBeenCalled();
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ });
+ it('retains recovery state when the resolved provider does not land', async () => {
+ const h = fixture();
+ h.stage.mockImplementation(async (_id, route) => ({ ...route, providerId: 'xai' }));
+ await expect(h.scope.restore('bot')).rejects.toThrow('did not become ready');
+ expect(h.clear).not.toHaveBeenCalled();
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ });
+ it('keeps the old record if the saved route also fails', async () => {
+ const h = fixture();
+ h.stage.mockRejectedValue(new Error('saved route unavailable'));
+ await expect(h.scope.restore('bot')).rejects.toThrow('saved route unavailable');
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ expect(h.clear).not.toHaveBeenCalled();
+ });
+ it('does not consume state when the final compare-and-set loses', async () => {
+ const h = fixture();
+ h.clear.mockResolvedValue(false);
+ await expect(h.scope.restore('bot')).rejects.toThrow('changed');
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ });
+ it('keeps recovery state when a switch returns without landing the saved route', async () => {
+ const h = fixture();
+ h.state.current = { ...h.saved, model: 'temporary-automation' };
+ h.stage.mockResolvedValue(undefined);
+ await expect(h.scope.restore('bot')).rejects.toThrow('did not become ready');
+ expect(h.clear).not.toHaveBeenCalled();
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ });
+ it.each(['REMOTE_AGENT_DEVICE_UNREACHABLE', 'REMOTE_AGENT_SHARE_UNAVAILABLE', 'PRECONDITION_FAILED', 'INVALID_PARAMS', 'HARNESS_SWITCH_NOT_READY'] as const)(
+ 'does not replace a choice after %s', async (code) => {
+ const h = fixture();
+ const error = createIpcError(code, 'temporary or unrelated failure');
+ h.setError(error);
+ await expect(h.scope.restore('bot')).rejects.toBe(error);
+ expect(h.recover).not.toHaveBeenCalled();
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ });
+ it('preserves the original error for an ordinary or inactive companion task', async () => {
+ const h = fixture();
+ h.disableBot();
+ await expect(h.scope.restore('ordinary')).rejects.toThrow('old source unavailable');
+ expect(h.stage).not.toHaveBeenCalled();
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ });
+ it('does not consume a newer scope created during validation', async () => {
+ const h = fixture();
+ const newer = h.old.replace('old', 'new');
+ h.stage.mockImplementation(async () => { h.state.scheduledModelBaseline = newer; });
+ await expect(h.scope.restore('bot')).rejects.toThrow('changed');
+ expect(h.state.scheduledModelBaseline).toBe(newer);
+ expect(h.clear).not.toHaveBeenCalled();
+ });
+ it('does not clear state after an account change', async () => {
+ const h = fixture();
+ h.stage.mockImplementation(async () => { h.changeOwner(); });
+ await expect(h.scope.restore('bot')).rejects.toThrow('owner changed');
+ expect(h.clear).not.toHaveBeenCalled();
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ });
+ it('does not consume a newer saved configuration during application', async () => {
+ const h = fixture();
+ h.stage.mockImplementation(async () => {
+ h.state.chain = [{ ...h.state.chain[0]!, model: 'newer' }];
+ h.reconcile.invalidate('bot');
+ });
+ await expect(h.scope.restore('bot')).rejects.toThrow('changed');
+ expect(h.clear).not.toHaveBeenCalled();
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ });
+ it('retains a record while the saved runtime switch is still pending', async () => {
+ const h = fixture();
+ const pendingApply = createBotModelRouteApplier({ stage: h.stage, isIdle: () => false,
+ hasPendingSwitch: () => true, applyPendingSwitch: async () => {}, onApplied: h.onApplied });
+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => 'one', read: async () => h.state,
+ apply: pendingApply, onSelectionAccepted: h.clear });
+ await expect(reconcile.recoverUnavailableBaseline('bot', h.old)).rejects.toThrow('pending');
+ expect(h.state.scheduledModelBaseline).toBe(h.old);
+ expect(h.clear).not.toHaveBeenCalled();
+ });
+ it('leaves explicit saves and mismatched scheduled cleanup to their existing paths', async () => {
+ const h = fixture();
+ await h.scope.restore('bot', 'other-scope');
+ h.state.scheduledModelBaseline = JSON.stringify({ ...JSON.parse(h.old), pendingBotProfileVersion: 'v2' });
+ await h.scope.restore('bot');
+ expect(h.recover).not.toHaveBeenCalled();
+ expect(h.stage).not.toHaveBeenCalled();
+ });
+});
+
+// Run the actual register.ts validation functions: restoration must recognize
+// deterministic rejection without treating offline/payment failures as obsolete
+// preferences. Ordinary picker and cross-device IPC error codes stay unchanged.
+const register = ts.createSourceFile('register.ts', readFileSync(new URL('../register.ts', import.meta.url), 'utf8'), ts.ScriptTarget.Latest, true);
+function registeredFunction(name: string, deps: Record<string, unknown>) {
+ let declaration: ts.FunctionDeclaration | ts.ArrowFunction | undefined;
+ const visit = (node: ts.Node) => {
+ if (ts.isFunctionDeclaration(node) && node.name?.text === name) declaration = node;
+ if (ts.isVariableDeclaration(node) && node.name.getText(register) === name && node.initializer && ts.isArrowFunction(node.initializer)) declaration = node.initializer;
+ ts.forEachChild(node, visit);
+ };
+ visit(register);
+ if (!declaration) throw new Error('Production function missing: ' + name);
+ const js = ts.transpileModule('return (' + declaration.getText(register) + ');', { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ return new Function(...Object.keys(deps), js)(...Object.values(deps));
+}
+it.each(['same-harness', 'same-harness-staged', 'cross-harness', 'back-to-task-device'] as const)('returns the validated provider from %s production staging', async (path) => {
+ const route = { agentDeviceId: null, agentKind: 'pi', model: 'saved', providerId: 'gateway', effort: null, fastMode: false };
+ const apply = vi.fn(async () => path === 'same-harness-staged'
+ ? { deferred: true, superseded: false, pendingUntilSend: true } : { effectiveProviderId: 'xai' });
+ const switchAgent = vi.fn(async () => {});
+ const stage = registeredFunction('stageSessionRouteSelection', {
+ readSessionAgentDeviceId: async () => path === 'back-to-task-device' ? 'other-device' : null,
+ performSessionAgentSwitch: switchAgent, agentSwitchDeps: {},
+ agentSwitchPending: { get: () => ({ targetAgentKind: 'pi', model: 'saved', providerId: 'xai' }) },
+ applyWithVerifiedModelWindow: (run: () => unknown) => run(), applySessionRuntimeSelection: apply,
+ });
+ const sameHarness = path === 'same-harness' || path === 'same-harness-staged';
+ await expect(stage('bot', route, sameHarness ? 'pi' : 'codex')).resolves.toMatchObject({
+ agentKind: 'pi', model: 'saved', providerId: 'xai',
+ });
+ expect(apply).toHaveBeenCalledTimes(sameHarness ? 1 : 0);
+ if (path === 'back-to-task-device') {
+ expect(switchAgent).toHaveBeenCalledWith({}, expect.objectContaining({ agentDeviceId: null }));
+ }
+});
+it.each(['claude-code', 'codex', 'pi'] as const)('restores all projected axes after recovering a legacy baseline to %s', (agentKind) => {
+ const project = registeredFunction('projectScheduledPreferences', {
+ projectSessionRuntimeControl, makerToDbAgentKind: (kind: string) => kind,
+ });
+ const baseline = { agentKind: 'codex' as const, model: 'old', providerId: 'removed', effort: null, fastMode: false };
+ const legacy = project('projection-test', baseline);
+ expect(legacy.runtimeBaselineRecoveryPending).toBe(true);
+ expect(legacy.runtimeEffective).toEqual(baseline); // Does not assert a different/available source.
+ expect(project('projection-test', { ...baseline, pendingBotProfileVersion: 2 }).runtimeBaselineRecoveryPending).toBe(false);
+ const recovered = { ...baseline, agentKind, model: 'saved-model', providerId: 'saved' };
+ const cleared = { ...legacy, ...projectSessionRuntimeControl('projection-test', recovered) };
+ expect(cleared.runtimeBaselineRecoveryPending).toBe(false); // Shallow-merged patches cannot retain the offer.
+ expect(cleared.agentKind).toBe(agentKind === 'claude-code' ? 'cc' : agentKind);
+ expect(cleared.runtimeEffective).toEqual(recovered);
+});
+describe('SSH baseline restoration through production profile application', () => {
+ it.each(['valid-remote-only', 'absent-on-host', 'host-offline', 'payment-required'] as const)('%s uses the SSH catalog before deciding recovery', async (outcome) => {
+ const saved: ScheduledModelSelection = { agentKind: 'codex', model: 'profile-model', providerId: 'openai', effort: 'low', fastMode: false };
+ const frozen = { ...saved, model: 'remote-override', effort: 'high' as const, fastMode: true };
+ const original = JSON.stringify({ ...frozen, scopeId: 'ssh-run' });
+ let baseline: string | null = original;
+ let applied: ScheduledModelSelection | undefined;
+ const views = [{ id: 'openai', connected: true, agents: ['codex'], source: 'user', routing: { codex: {} }, models: { codex: [{
+ id: outcome === 'absent-on-host' ? 'profile-model' : frozen.model,
+ efforts: ['low', 'high'], defaultEffort: 'low', supportsFastMode: true,
+ ...(outcome === 'payment-required' ? { availability: 'requires_payment' as const } : {}),
+ }] } }] as ProviderView[];
+ const ssh = vi.fn(async () => {
+ if (outcome === 'host-offline') throw new Error('SSH connection closed');
+ return views;
+ });
+ const local = vi.fn(async () => { throw createIpcError('MODEL_SELECTION_UNAVAILABLE', 'not in local catalog'); });
+ const apply = registeredFunction('applyScheduledProfile', {
+ applyScheduledModelSelection, createScheduledModelSelectionResolver, resolveScheduledModelSelection,
+ readSshCodexModelList, listSshCodexProviders: ssh,
+ agentSwitchDeps: { getSessionRow: async () => ({ agentKind: 'codex', status: 'active', remoteHostId: 'ssh-builder', agentDeviceId: 'stale-device' }) },
+ dbToMakerAgentKind: (kind: string) => kind,
+ isSessionInTurn: () => false, maker: { getSession: () => undefined },
+ readUsableAgentDeviceProviders: vi.fn(() => { throw new Error('must not query another computer'); }),
+ assertModelRouteUsable: local, resolveScheduledModelSelectionLive: local,
+ applySessionRuntimeSelection: async (_id: string, model: string, providerId: string, axes: Pick<ScheduledModelSelection, 'effort' | 'fastMode'>) => {
+ applied = { ...frozen, model, providerId, ...axes };
+ return {};
+ },
+ runtimeSelectionRequiresModelWindowConfirmation: () => false,
+ });
+ const recover = vi.fn(async () => { applied = saved; baseline = null; return true; });
+ const scope = createScheduledModelScope({
+ createId: () => 'new', isBusy: () => false,
+ read: async () => ({ profile: saved, baseline }),
+ write: async () => { baseline = null; },
+ apply: async (id, route) => { await apply(id, route); },
+ recoverUnavailableBaseline: recover,
+ });
+ if (outcome === 'payment-required') {
+ await expect(scope.restore('ssh-bot')).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(baseline).toBe(original);
+ expect(applied).toBeUndefined();
+ expect(recover).not.toHaveBeenCalled();
+ } else if (outcome === 'host-offline') {
+ await expect(scope.restore('ssh-bot')).rejects.toMatchObject({ code: 'SSH_EXEC_FAILED' });
+ expect(baseline).toBe(original);
+ expect(applied).toBeUndefined();
+ expect(recover).not.toHaveBeenCalled();
+ } else {
+ await scope.restore('ssh-bot');
+ expect(baseline).toBeNull();
+ if (outcome === 'valid-remote-only') {
+ expect(applied).toEqual(frozen);
+ expect(recover).not.toHaveBeenCalled();
+ } else {
+ expect(recover).toHaveBeenCalledWith('ssh-bot', original);
+ }
+ }
+ expect(ssh).toHaveBeenCalledWith('ssh-builder');
+ expect(local).not.toHaveBeenCalled();
+ });
+});
+// #7471 review: entry existence in checkDeviceRoute does not establish payment
+// admission. Exercise the remote catalog resolver inside the real restore scope.
+it.each([
+ ['requires_payment', 'source'], ['requires_payment', null], ['retired', 'source'],
+] as const)('keeps remote payment failures distinct from obsolete models: %s / %s', async (reason, providerId) => {
+ const saved: ScheduledModelSelection = { agentKind: 'pi', model: 'old-model', providerId, effort: null, fastMode: false };
+ const original = JSON.stringify({ ...saved, agentDeviceId: 'execution-pc', scopeId: 'run' });
+ let baseline: string | null = original;
+ const views = [{ id: 'source', connected: true, source: 'user', agents: ['pi'], routing: { pi: {} },
+ models: { pi: [{ id: saved.model, ...(reason === 'requires_payment'
+ ? { availability: reason } : { status: reason }) }] } }] as ProviderView[];
+ const recover = vi.fn(async () => { baseline = null; return true; });
+ const applyModel = vi.fn();
+ const resolve = createScheduledModelSelectionResolver({
+ readRemoteProviders: async () => {
+ expect(await checkDeviceRoute(async () => views, 'pi', saved.providerId, saved.model)).toBeNull();
+ return views;
+ },
+ readSshCodexProviders: async () => { throw new Error('unexpected SSH read'); },
+ resolveLocalSelection: async () => { throw new Error('unexpected local read'); },
+ });
+ const scope = createScheduledModelScope({ createId: () => 'new', isBusy: () => false,
+ read: async () => ({ profile: saved, baseline }), write: async () => { baseline = null; },
+ apply: async (_id, selection) => { await applyScheduledModelSelection(selection, {
+ getTarget: async () => ({ agentKind: 'pi', status: 'active', agentDeviceId: 'execution-pc' }),
+ isBusy: () => false, resolveSelection: resolve, applyModel,
+ switchHarness: async () => { throw new Error('unexpected switch'); },
+ }); }, recoverUnavailableBaseline: recover,
+ });
+ if (reason === 'requires_payment') {
+ await expect(scope.restore('bot')).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(baseline).toBe(original);
+ expect(recover).not.toHaveBeenCalled();
+ } else {
+ await scope.restore('bot');
+ expect(recover).toHaveBeenCalledWith('bot', original);
+ expect(baseline).toBeNull();
+ }
+ expect(applyModel).not.toHaveBeenCalled();
+});
+describe('production restoration rejection classification', () => {
+ const throwIpcError = (code: Parameters<typeof createIpcError>[0], message: string): never => { throw createIpcError(code, message); };
+ it.each(['explicit-source-unavailable', 'explicit-source-disabled', 'model-retired', 'payment-required'])('%s retains ordinary semantics and marks only recoverable restoration failures', async (reason) => {
+ const guard = registeredFunction('assertModelRouteUsable', { throwIpcError,
+ verdictForModelRoute: async () => ({ kind: 'reject', reason }), describeModelRouteRejection: () => reason });
+ await expect(guard('pi', 'saved', 'old')).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ await expect(guard('pi', 'saved', 'old', undefined, 'MODEL_SELECTION_UNAVAILABLE')).rejects.toMatchObject({
+ code: reason === 'payment-required' ? 'INVALID_PARAMS' : 'MODEL_SELECTION_UNAVAILABLE',
+ });
+ });
+ it.each(['not-offered', 'REMOTE_AGENT_SHARE_REMOVED', 'REMOTE_AGENT_SHARE_PAUSED', 'unreachable', 'REMOTE_AGENT_SHARE_UNAVAILABLE'])(
+ 'classifies remote %s before IPC downgrade, retaining transient errors', async (rejection) => {
+ const read = registeredFunction('readUsableAgentDeviceProviders', { throwIpcError, checkDeviceRoute,
+ remoteBackgroundInvoke: vi.fn(), isProviderShareAgentDeviceId: () => false,
+ isDeviceLinkInvoke: () => true, log: { warn: vi.fn() },
+ readDeviceProviderViews: async () => {
+ if (rejection === 'not-offered') return [];
+ throw new Error(rejection === 'unreachable' ? 'offline' : '[' + rejection + ']');
+ } });
+ await expect(read('device', 'pi', 'model', 'old')).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ await expect(read('device', 'pi', 'model', 'old', 'MODEL_SELECTION_UNAVAILABLE')).rejects.toMatchObject({
+ code: rejection === 'not-offered' || rejection === 'REMOTE_AGENT_SHARE_REMOVED'
+ ? 'MODEL_SELECTION_UNAVAILABLE' : 'PRECONDITION_FAILED',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts
index af40a5df49..eadb76bdbd 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts
@@ -298,7 +298,8 @@ describe('saved automation model selection at dispatch', () => {
resolveSelection: async (value: ScheduledModelSelection) =>
resolveScheduledModelSelection(value, [selected, provider('other')]),
};
- await expect(applyScheduledModelSelection(selection, deps)).rejects.toThrow('MODEL_SELECTION_UNAVAILABLE');
+ await expect(applyScheduledModelSelection(selection, deps)).rejects.toThrow(
+ model.availability === 'requires_payment' ? 'INVALID_PARAMS' : 'MODEL_SELECTION_UNAVAILABLE');
expect(deps.switchHarness).not.toHaveBeenCalled();
expect(deps.applyModel).not.toHaveBeenCalled();
});
@@ -507,6 +508,7 @@ function remoteFixture(device: string | null = 'share:test', status = 'active')
isBusy: () => false,
resolveSelection: createScheduledModelSelectionResolver({
readRemoteProviders: remote,
+ readSshCodexProviders: async () => { throw new Error('non-SSH tasks must not read the SSH catalog'); },
resolveLocalSelection: async route => {
await guard(route.agentKind, route.model, route.providerId);
return resolveScheduledModelSelection(route, local);
@@ -597,7 +599,8 @@ describe('automation restore uses the execution computer', () => {
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');
+ await expect(h.scope.restore('task')).rejects.toThrow(
+ flags.availability === 'requires_payment' ? 'INVALID_PARAMS' : 'MODEL_SELECTION_UNAVAILABLE');
expect(h.state()).toEqual(before);
expect(h.applyModel).not.toHaveBeenCalled();
expect(h.switchHarness).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts
index 6c16b83f00..34e451a33a 100644
--- a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts
+++ b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts
@@ -23,6 +23,10 @@ interface BotRouteState {
next?: RuntimeRoute;
}
+interface RouteApplyOptions {
+ preserveScheduledBaseline: boolean;
+}
+
function configuredKey(state: BotRouteState, chain = state.chain): string {
// Restore defaults is a configuration change even when its routes are equal.
return JSON.stringify([chain, state.followsCindyDefault === true]);
@@ -69,21 +73,22 @@ function sameRoute(a: RuntimeRoute, b: RuntimeRoute): boolean {
/** Apply through both runtime switch paths before retiring recovery state. */
export function createBotModelRouteApplier(deps: {
- stage(sessionId: string, route: RuntimeRoute, current: RuntimeRoute): Promise<void>;
+ stage(sessionId: string, route: RuntimeRoute, current: RuntimeRoute): Promise<RuntimeRoute | void>;
isIdle(sessionId: string): boolean;
applyPendingSwitch(sessionId: string): Promise<void>;
hasPendingSwitch(sessionId: string): boolean;
onApplied(sessionId: string): Promise<void>;
}) {
- return async (sessionId: string, route: RuntimeRoute, current: RuntimeRoute): Promise<void> => {
- await deps.stage(sessionId, route, current);
+ return async (sessionId: string, route: RuntimeRoute, current: RuntimeRoute, options?: RouteApplyOptions): Promise<RuntimeRoute> => {
+ const resolved = await deps.stage(sessionId, route, current) ?? route;
if (deps.isIdle(sessionId)) await deps.applyPendingSwitch(sessionId);
// Same-Harness choices wait in runtime control, not the Harness registry.
// Staging alone must not retire the durable recovery marker.
if (deps.hasPendingSwitch(sessionId) || getSessionRuntimeControlSnapshot(sessionId).pending) {
throw new ScheduledModelSelectionBusyError('Saved companion route is still pending');
}
- await deps.onApplied(sessionId);
+ if (!options?.preserveScheduledBaseline) await deps.onApplied(sessionId);
+ return resolved;
};
}
@@ -95,7 +100,9 @@ export function createBotModelRouteReconciler(deps: {
ownerEpoch(): string;
withSessionLock?<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>;
+ apply(sessionId: string, route: RuntimeRoute, current: RuntimeRoute, options?: RouteApplyOptions): Promise<RuntimeRoute | void>;
+ /** Returns a group only when its committed member matches the actual session route. */
+ readAppliedGroup?(sessionId: string): Promise<{ providerId: string; groupDeviceId: string | null } | null>;
/** An accepted permanent choice supersedes temporary preferences, even without a switch. */
onSelectionAccepted?(sessionId: string, expectedBaseline?: string | null): Promise<void | boolean>;
}) {
@@ -182,6 +189,56 @@ export function createBotModelRouteReconciler(deps: {
};
return Object.assign(reconcile, {
invalidate,
+ /** Called under the send lock only after the frozen route is unavailable.
+ * Resolve the real saved profile (including routine/location choices), never
+ * the session row that may still contain the automation's temporary route. */
+ async recoverUnavailableBaseline(sessionId: string, expectedBaseline: string): Promise<boolean> {
+ const epoch = syncOwner();
+ const revision = revisions.get(sessionId) ?? 0;
+ const assertCurrent = () => {
+ if (deps.ownerEpoch() !== epoch) throw new Error('Bot model route owner changed');
+ if ((revisions.get(sessionId) ?? 0) !== revision) {
+ throw new ScheduledModelSelectionBusyError('Companion profile changed during baseline recovery');
+ }
+ };
+ const state = await deps.read(sessionId, 'apply');
+ assertCurrent();
+ if (!state) return false;
+ const baseline = parseScheduledModelBaseline(state.scheduledModelBaseline);
+ if (state.scheduledModelBaseline !== expectedBaseline || !baseline || baseline.pendingBotProfileVersion) {
+ throw new ScheduledModelSelectionBusyError('Scheduled model selection changed before recovery');
+ }
+ const route = configuredRoute(state, '');
+ if (!route || !deps.onSelectionAccepted) return false;
+ const key = configuredKey(state);
+ // Even an equal route must pass validation and the runtime switch boundary.
+ // Unconditional onApplied cleanup would race a newer durable recovery record.
+ const resolved = await deps.apply(sessionId, route, state.current, { preserveScheduledBaseline: true }) ?? route;
+ assertCurrent();
+ const latest = await deps.read(sessionId, 'apply');
+ assertCurrent();
+ if (!latest || latest.scheduledModelBaseline !== expectedBaseline || configuredKey(latest) !== key) {
+ throw new ScheduledModelSelectionBusyError('Companion selection changed during baseline recovery');
+ }
+ const directRouteReady = (resolved.providerId === null || latest.current.providerId === resolved.providerId)
+ && (latest.current.agentDeviceId ?? null) === (resolved.agentDeviceId ?? null);
+ // applyNow may select a group member after staging returned the group entry.
+ // Accept only a binding verified against the actual member, for this saved group.
+ const group = !directRouteReady ? await deps.readAppliedGroup?.(sessionId) : null;
+ assertCurrent();
+ const groupRouteReady = group != null && group.providerId === route.providerId
+ && group.groupDeviceId === (route.agentDeviceId ?? null);
+ if (latest.current.agentKind !== resolved.agentKind || latest.current.model !== resolved.model ||
+ (!directRouteReady && !groupRouteReady)) {
+ throw new ScheduledModelSelectionBusyError('Saved companion route did not become ready');
+ }
+ if (await deps.onSelectionAccepted(sessionId, expectedBaseline) === false) {
+ throw new ScheduledModelSelectionBusyError('Scheduled model selection changed before recovery cleanup');
+ }
+ assertCurrent();
+ configured.set(sessionId, key);
+ return true;
+ },
/** Explicit saves invalidate fallback even before the first send. A newer
* save during an in-flight switch is reread before this promise settles. */
profileChanged(sessionId: string): Promise<void> {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 5dff75f0e0..99b0952550 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -227,7 +227,7 @@ import {
} from '@cindy/device-link';
import { and, asc, desc, eq, gte, inArray, isNull, like, lt, or, sql } from 'drizzle-orm';
import { applyScheduledModelSelection, createScheduledModelScope, createScheduledModelSelectionResolver, writeScheduledModelBaselineIfProfileCurrent, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';
-import { parseScheduledModelBaseline } from '../../shared/scheduledModelBaseline';
+import { parseScheduledModelBaseline, type ScheduledModelBaseline } from '../../shared/scheduledModelBaseline';
import { recordTurnModelChange, type TurnModelIdentity } from './turnModelChange';
import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';
import { accessChatDisplayCache } from './chatDisplayCache.js';
@@ -6769,7 +6769,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
projectSessionRuntimeControl(sessionId, baseline) as Record<string, unknown>,
);
};
- const projectScheduledPreferences = (sessionId: string, saved: ScheduledModelSelection) => {
+ const projectScheduledPreferences = (sessionId: string, saved: ScheduledModelBaseline) => {
const baseline: ScheduledModelSelection = {
agentKind: saved.agentKind, model: saved.model, providerId: saved.providerId,
...(saved.agentDeviceId !== undefined ? { agentDeviceId: saved.agentDeviceId } : {}),
@@ -6786,6 +6786,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
runtimeBaseline: baseline,
runtimeEffective: baseline,
runtimePending: null,
+ runtimeBaselineRecoveryPending: !saved.pendingBotProfileVersion,
};
};
setSessionRuntimeProjector((session) => {
@@ -8647,6 +8648,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
agent: AgentKind,
model: string,
providerId: string | null,
+ unavailableCode?: 'MODEL_SELECTION_UNAVAILABLE',
): Promise<ProviderView[]> {
let views: ProviderView[] = [];
const checked = await checkDeviceRoute(
@@ -8664,6 +8666,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const rejection = checked === 'unreachable' && isProviderShareAgentDeviceId(deviceId)
? 'REMOTE_AGENT_SHARE_UNAVAILABLE'
: checked;
+ // Restoration can recover a removed source/model from the saved companion
+ // profile. Preserve transient offline/paused errors and their retry behavior.
+ if (unavailableCode && (rejection === 'not-offered' || rejection === 'REMOTE_AGENT_SHARE_REMOVED')) {
+ throwIpcError(unavailableCode, 'the saved model is no longer offered by its execution computer');
+ }
log.warn('remote agent selection rejected', { agent, model, providerId, rejection });
if (rejection.startsWith('REMOTE_AGENT_SHARE_')) {
// 分享来的供应商:给出分享专属原因(device-link 控制端同样降级为 PRECONDITION_FAILED)。
@@ -8791,6 +8798,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
model: string,
providerId: string | null,
remoteHostId?: string | null,
+ unavailableCode?: 'MODEL_SELECTION_UNAVAILABLE',
): Promise<string | undefined> {
if (agent === 'codex' && remoteHostId) {
assertSshCodexModel(await readSshCodexModelList({ id: remoteHostId }, listSshCodexProviders), model, providerId);
@@ -8799,7 +8807,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const verdict = await verdictForModelRoute(agent, model, providerId);
if (verdict.kind === 'reject') {
throwIpcError(
- 'INVALID_PARAMS',
+ verdict.reason === 'payment-required' ? 'INVALID_PARAMS' : unavailableCode ?? 'INVALID_PARAMS',
describeModelRouteRejection(verdict.reason, model, providerId),
);
}
@@ -11471,9 +11479,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
isBusy: () => isSessionInTurn(sessionId) || !!maker.getSession(sessionId)?.isTurnRunning(),
resolveSelection: createScheduledModelSelectionResolver({
- readRemoteProviders: readUsableAgentDeviceProviders,
+ readRemoteProviders: (deviceId, agent, model, providerId) =>
+ readUsableAgentDeviceProviders(deviceId, agent, model, providerId, 'MODEL_SELECTION_UNAVAILABLE'),
+ readSshCodexProviders: (hostId) => readSshCodexModelList({ id: hostId }, listSshCodexProviders),
resolveLocalSelection: async (route) => {
- const reroute = await assertModelRouteUsable(route.agentKind, route.model, route.providerId);
+ const reroute = await assertModelRouteUsable(route.agentKind, route.model, route.providerId, undefined, 'MODEL_SELECTION_UNAVAILABLE');
return resolveScheduledModelSelectionLive({ ...route,
providerId: reroute && shouldApplyExclusiveProviderRerouteLive(route.providerId)
? reroute : route.providerId,
@@ -11574,6 +11584,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
isBusy: (sessionId) => isSessionInTurn(sessionId) || !!maker.getSession(sessionId)?.isTurnRunning() ||
isUserPendingAgentSwitchIntent(agentSwitchPending.get(sessionId)),
apply: async (sessionId, profile) => { await applyScheduledProfile(sessionId, profile); },
+ recoverUnavailableBaseline: (sessionId, expectedBaseline) =>
+ reconcileBotModelRoute.recoverUnavailableBaseline(sessionId, expectedBaseline),
});
const updateScheduledPreference = async (
sessionId: string, patch: { effort?: ScheduledModelSelection['effort']; fastMode?: ScheduledModelSelection['fastMode'] } | null,
@@ -16663,7 +16675,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
sessionId: string,
route: SessionRouteSelection,
currentAgentKind: AgentKind,
- ): Promise<void> => {
+ ): Promise<SessionRouteSelection | void> => {
// Legacy callers without a location must not move a remote session implicitly.
const currentDeviceId = await readSessionAgentDeviceId(sessionId);
if (route.agentDeviceId === undefined && currentDeviceId) return;
@@ -16674,12 +16686,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
...(route.agentDeviceId !== undefined ? { agentDeviceId: route.agentDeviceId } : {}),
configStaged: true,
});
+ const intent = agentSwitchPending.get(sessionId);
+ return intent ? {
+ ...route, agentKind: intent.targetAgentKind, model: intent.model,
+ providerId: intent.providerId ?? null,
+ agentDeviceId: intent.targetAgentDeviceId === undefined ? currentDeviceId : intent.targetAgentDeviceId,
+ } : route;
} else {
- await applyWithVerifiedModelWindow((confirmedContextWindow) =>
+ const result = await applyWithVerifiedModelWindow((confirmedContextWindow) =>
applySessionRuntimeSelection(sessionId, route.model, route.providerId,
{ effort: route.effort as SessionRuntimeProfile['effort'], fastMode: route.fastMode,
...(confirmedContextWindow === undefined ? {} : { confirmedContextWindow }) },
{ source: 'user', deferWhileRunning: true, sessionLockHeld: true, configStaged: true }));
+ // SET_MODEL stages local user selections without returning their provider.
+ // The pending intent already contains the validated/rebound connection.
+ const intent = result.deferred ? agentSwitchPending.get(sessionId) : undefined;
+ return { ...route, providerId: result.effectiveProviderId === undefined
+ ? (intent ? intent.providerId ?? null : route.providerId) : result.effectiveProviderId };
}
};
followMovedCindyAutoRoutesNow = async () => {
@@ -16836,6 +16859,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
: control.pending?.profile ?? control.effectiveOverride ?? undefined,
};
},
+ readAppliedGroup: (sessionId) => providerGroupService?.sessionGroup(sessionId) ?? Promise.resolve(null),
apply: createBotModelRouteApplier({
stage: (sessionId, route, current) => stageSessionRouteSelection(
sessionId, { ...route, agentDeviceId: route.agentDeviceId ?? null }, current.agentKind),
diff --git a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
index 98294c83a5..0a338f9e05 100644
--- a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
@@ -1,8 +1,9 @@
import type { AgentKind, Effort } from '@cindy/maker-core';
-import { connectedProvidersForAgent, effectiveSourceIdForModel, findCatalogModel, isModelSelectableForNewRoute, type ProviderView } from '@cindy/model-providers';
+import { actualSourceIdForModel, connectedProvidersForAgent, effectiveSourceIdForModel, findCatalogModel, isModelSelectableForNewRoute, type ProviderView } from '@cindy/model-providers';
import { resolveCompatibleSessionRuntimeEffort } from './sessionRuntimeControl';
import { parseScheduledModelBaseline, type ScheduledModelBaseline } from '../../shared/scheduledModelBaseline';
import { throwIpcError } from '../utils/ipcValidate';
+import { isIpcError } from '../../shared/ipc-errors';
/** A saved automation choice, applied only while its target's send lock is held. */
export interface ScheduledModelSelection {
@@ -35,6 +36,9 @@ export function createScheduledModelScope(deps: {
createId: () => string;
ownerEpoch?: () => string;
prepareBaseline?: (sessionId: string) => Promise<void>;
+ /** Caller holds the send lock; true means the saved companion route was
+ * applied and the exact failed baseline was retired without restoring it. */
+ recoverUnavailableBaseline?: (sessionId: string, expectedBaseline: string) => Promise<boolean>;
}) {
const assertOwner = (owner: string | undefined) => {
if (owner !== deps.ownerEpoch?.()) throw new Error('Account changed during scheduled model selection');
@@ -95,8 +99,19 @@ export function createScheduledModelScope(deps: {
// 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);
+ try {
+ await deps.apply(sessionId, baseline);
+ } catch (error) {
+ assertOwner(owner);
+ // Only catalog/route validation marks a selection unavailable. Network,
+ // permission and runtime-switch failures must retain the saved choice.
+ if (isIpcError(error) && error.code === 'MODEL_SELECTION_UNAVAILABLE' &&
+ await deps.recoverUnavailableBaseline?.(sessionId, row!.baseline!)) {
+ assertOwner(owner);
+ return;
+ }
+ throw error;
+ }
assertOwner(owner);
const written = await deps.write(sessionId, null, row!.profileRevision, row!.baseline);
assertOwner(owner);
@@ -159,10 +174,18 @@ export function resolveScheduledModelSelection(
providers: ProviderView[],
): ScheduledModelSelection {
const providerId = selection.providerId ??
- effectiveSourceIdForModel(providers, null, selection.model, selection.agentKind);
+ // If admission removed every implicit source, retain the existing source only
+ // for rejection classification; the selectable-model check below still applies.
+ effectiveSourceIdForModel(providers, null, selection.model, selection.agentKind) ??
+ actualSourceIdForModel(providers, null, selection.model, selection.agentKind);
const provider = connectedProvidersForAgent(providers, selection.agentKind)
.find((candidate) => candidate.id === providerId);
const model = findCatalogModel(provider, selection.model, selection.agentKind, { exact: true });
+ // Payment admission is not evidence that a saved model has been removed.
+ // Preserve the local guard's error class so restoration cannot replace it.
+ if (model?.availability === 'requires_payment') {
+ throwIpcError('INVALID_PARAMS', `Scheduled model "${selection.model}" requires payment from provider "${providerId ?? 'default'}"`);
+ }
if (!provider || !model ||
!isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' })) {
throwIpcError('MODEL_SELECTION_UNAVAILABLE', `Scheduled model "${selection.model}" is unavailable from provider "${providerId ?? 'default'}"`);
@@ -178,9 +201,15 @@ export function resolveScheduledModelSelection(
/** 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[]>;
+ readSshCodexProviders: (hostId: string) => Promise<ProviderView[]>;
resolveLocalSelection: (selection: ScheduledModelSelection) => Promise<ScheduledModelSelection>;
}) {
return async (selection: ScheduledModelSelection, target?: ScheduledModelTarget | null): Promise<ScheduledModelSelection> => {
+ // SSH Codex discovers native models on its host. A controller's catalog
+ // cannot establish that a frozen remote choice is obsolete.
+ if (target?.remoteHostId && selection.agentKind === 'codex') {
+ return resolveScheduledModelSelection(selection, await deps.readSshCodexProviders(target.remoteHostId));
+ }
const agentDeviceId = selection.agentDeviceId === undefined
? target?.agentDeviceId : selection.agentDeviceId;
if (agentDeviceId && !target?.remoteHostId) {
diff --git a/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts b/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts
index a0689532c1..3efe800a6e 100644
--- a/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts
@@ -1,6 +1,7 @@
import { modelRouteLocationKey } from '@cindy/maker-shared/model-route';
import type { AgentKind, Effort } from '@cindy/maker-core';
import type { Session as RendererSession } from '../../renderer/lib/ccAgent.types';
+import { makerToDbAgentKind } from '../../shared/agentKindConversion.js';
import {
connectedProvidersForAgent,
isModelSelectableForNewRoute,
@@ -47,6 +48,7 @@ export function projectSessionRuntimeControl(
const control = getSessionRuntimeControlSnapshot(sessionId);
const effective = control.effectiveOverride ?? baseline;
return {
+ agentKind: makerToDbAgentKind(effective.agentKind),
model: effective.model,
providerId: effective.providerId,
// The legacy wire axis is string-compatible; the profile preserves null.
@@ -56,6 +58,7 @@ export function projectSessionRuntimeControl(
runtimeBaseline: baseline,
runtimeEffective: effective,
runtimePending: control.pending,
+ runtimeBaselineRecoveryPending: false,
};
}
diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
index 3a90a95637..ee2dec3d22 100644
--- a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
@@ -88,7 +88,7 @@ describe('CCAgentSessionView 接线不变式', () => {
);
expect(sessionViewSrc).not.toContain('if (remoteSessionUnavailable) return false');
expect(sessionViewSrc).not.toContain('remoteSessionUnavailableRef');
- expect(sessionViewSrc).toContain('if (!remoteDeviceId) {');
+ expect(sessionViewSrc).toContain('if (!remoteDeviceId && !recoveringBaseline) {');
expect(sessionViewSrc).not.toContain('beforeEnqueue: checkVendorReady');
// device-link 远程交接期间仍要禁用(见 remoteHandoffPreparing):那几段 await
// 可能数十秒,不禁用的话用户补发的消息会插到草稿提交的首条之前。
@@ -121,7 +121,7 @@ describe('CCAgentSessionView 接线不变式', () => {
/const noConnectedSource =\s*enforceConnectedSourceGate &&\s*!!currentModelAgentKind/,
);
expect(chatInputSrc).toMatch(
- /if\s*\(\s*enforceConnectedSourceGate\s*&&\s*currentModelAgentKind\s*&&[\s\S]*?\)\s*\{/,
+ /if\s*\(\s*enforceConnectedSourceGate\s*&&\s*!canAttemptBaselineRecovery\s*&&\s*currentModelAgentKind\s*&&[\s\S]*?\)\s*\{/,
);
});
it('断线缓存的远程 session 可查看,但生命周期/元数据写操作必须走统一 gate', () => {
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 150e5bd7af..57296755bb 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -507,6 +507,7 @@ interface ChatInputProps {
deliveryMode?: MessageDeliveryMode;
builtInSkillIntent?: BuiltInSkillDraftIntent;
providerId?: string | null;
+ baselineRecovery?: boolean;
/** chat-text-quote:message 开头的 blockquote 为引用功能拼接产出。 */
quotesEncoded?: boolean;
/** Ordered semantic projection metadata for session/project/message chips. */
@@ -550,6 +551,8 @@ interface ChatInputProps {
runtimeAgentKind?: AgentKind | null;
runtimeEffective?: SessionRuntimeProfileProjection;
runtimePending?: SessionRuntimePendingProjection | null;
+ /** Host offers a baseline restoration attempt for this companion, not a connected source. */
+ allowBaselineRecovery?: boolean;
/**
* 会话的 Orca 角色(lead / worker;null = 已确认非协同;undefined = 元数据未加载)。
* Orca Lead/Worker 复用统一的延迟交接切换事务;该字段仍用于协同面板与身份展示。
@@ -1247,6 +1250,7 @@ export function ChatInput({
runtimeAgentKind,
runtimeEffective,
runtimePending,
+ allowBaselineRecovery = false,
sessionOrcaRole,
sessionOrcaRemoteWorker,
initialWorkingDir,
@@ -2180,6 +2184,13 @@ export function ChatInput({
providersLoading,
});
+ // Only the unchanged host-projected selection may enter recovery. A new user
+ // selection must pass the normal source checks, including optimistic switches.
+ const canAttemptBaselineRecovery = !!sessionId && allowBaselineRecovery &&
+ !!runtimeEffective && !composerSelection.pending && !agentSwitchIntent && !pendingRemoteSwitch &&
+ activeModel === runtimeEffective.model && currentModelAgentKind === runtimeEffective.agentKind &&
+ (activeProviderId ?? null) === (runtimeEffective.providerId ?? null);
+
// 当前**生效来源 id**(= ModelSelector 高亮的 activeSourceId 同口径):显式选中且仍可连、
// 且提供当前模型 → 用它;否则只在“提供当前模型”的来源里取原生默认。providerModelMemory
// 按 (agent, 来源) 分槽记 (model, effort),写入 / 恢复都以这个 id 为 key,保证对称。
@@ -5776,7 +5787,7 @@ export function ChatInput({
// 直接 LAZY_CREATE_FAILED(renderer 的 sendProviderId=null 救不了已建会话),所以这里
// 弹窗给出明确原因 + 去设置入口,而不是让请求出去撞一个原始错误码。
// Send 按钮已被 selectedSourceDisconnected 禁用,此 guard 兜底覆盖间接派发路径。
- if (selectedSourceDisconnected) {
+ if (selectedSourceDisconnected && !canAttemptBaselineRecovery) {
const goConnect = await confirmDialog({
title: t('newChat.sourceDisconnected.title'),
description: t('newChat.sourceDisconnected.description'),
@@ -5798,7 +5809,7 @@ export function ChatInput({
// 处理,不误伤。用 chatEligibleSourcesForModel 而非裸 sourcesForModel:
// 非聊天来源不该被当成"可以发"放行(issue #882 第 3 点,2026-07 review)。
if (
- enforceConnectedSourceGate &&
+ enforceConnectedSourceGate && !canAttemptBaselineRecovery &&
currentModelAgentKind &&
// 旧被控端明确不支持 provider:list 时,控制端没有可检查的来源镜像;
// 与模型列表一致交给 capabilities + 被控端发送链路做兼容回退。
@@ -6273,6 +6284,7 @@ export function ChatInput({
{
deliveryMode,
providerId: sendProviderId,
+ ...(canAttemptBaselineRecovery ? { baselineRecovery: true } : {}),
...(builtInSkillIntent
? {
builtInSkillIntent: {
@@ -6326,6 +6338,7 @@ export function ChatInput({
activePermissionMode,
sendProviderId,
selectedSourceDisconnected,
+ canAttemptBaselineRecovery,
fastMode,
hasAttachments,
attachments,
@@ -9138,9 +9151,9 @@ export function ChatInput({
: Boolean(
disabled || sessionModelLoading || waitingForFolders ||
// 空態:当前 agent 无已连接来源 → Send 禁用(设计 Q7NYAD「send 置灰」),引导用户先去连接来源。
- (!makeNeedsNoModel && noConnectedSource) ||
+ (!makeNeedsNoModel && !canAttemptBaselineRecovery && noConnectedSource) ||
// 会话显式选中的来源已断开 → Send 禁用(trigger 同步显示「已断开」错误态说明原因)。
- (!makeNeedsNoModel && selectedSourceDisconnected) ||
+ (!makeNeedsNoModel && !canAttemptBaselineRecovery && selectedSourceDisconnected) ||
// device-link 模型目录仍在读取或真实失败 → 禁止旧快照继续发送;旧端明确
// unsupported 已由 remoteModelListStatus 归并为 ready,不会误伤兼容回退。
remoteModelListBlocked ||
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputModelLoading.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputModelLoading.test.tsx
index c55f855f26..8a28e82312 100644
--- a/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputModelLoading.test.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputModelLoading.test.tsx
@@ -111,6 +111,50 @@ const props = {
hideRuntimeControls: true, showFolderPicker: false, disableAutofocus: true,
};
+it.each(['removed-source', 'removed-model'])('sends the first message through host baseline recovery (%s)', async (reason) => {
+ h.localProviders = reason === 'removed-model'
+ ? [sshNativeCodexProvider([sshModel('different-model')])] : [];
+ const onSend = vi.fn().mockResolvedValue(true);
+ const route = { agentKind: 'codex' as const, model: 'retired-model', providerId: 'removed', effort: null, fastMode: false };
+ render(<ChatInput {...props} sessionId={'recovery-' + reason} deviceLinkDeviceId={null}
+ initialModel={route.model} initialProviderId={route.providerId} runtimeEffective={route}
+ allowBaselineRecovery onSend={onSend} />);
+ await waitFor(() => expect(h.editor).not.toBeNull());
+ await act(async () => { h.editor!.commands.setContent('<p>Retry companion</p>'); });
+ const send = screen.getByRole('button', { name: 'newChat.sendButton.send' });
+ expect((send as HTMLButtonElement).disabled).toBe(false);
+ await act(async () => { fireEvent.click(send); });
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ expect(onSend.mock.calls[0][0]).toBe('Retry companion');
+ expect(onSend.mock.calls[0][6]).toMatchObject({ baselineRecovery: true, providerId: route.providerId });
+ expect(h.confirm).not.toHaveBeenCalled();
+});
+
+it.each([false, undefined])('keeps disconnected ordinary sessions blocked without a host recovery offer (%s)', async (allowBaselineRecovery) => {
+ const onSend = vi.fn();
+ const route = { agentKind: 'codex' as const, model: 'retired-model', providerId: 'removed', effort: null, fastMode: false };
+ render(<ChatInput {...props} deviceLinkDeviceId={null} initialModel={route.model}
+ initialProviderId={route.providerId} runtimeEffective={route}
+ allowBaselineRecovery={allowBaselineRecovery} onSend={onSend} />);
+ await act(async () => { h.editor!.commands.setContent('<p>Must stay blocked</p>'); });
+ const send = screen.getByRole('button', { name: 'newChat.sendButton.send' });
+ expect((send as HTMLButtonElement).disabled).toBe(true);
+ fireEvent.click(send);
+ expect(onSend).not.toHaveBeenCalled();
+});
+
+it('does not use baseline recovery to bypass a pending selection source check', async () => {
+ const onSend = vi.fn();
+ const route = { agentKind: 'codex' as const, model: 'retired-model', providerId: 'removed', effort: null, fastMode: false };
+ render(<ChatInput {...props} deviceLinkDeviceId={null} initialModel={route.model}
+ initialProviderId={route.providerId} runtimeEffective={route} allowBaselineRecovery
+ runtimePending={{ generation: 1, source: 'agent', profile: { ...route, providerId: 'new-disconnected-choice' } }}
+ onSend={onSend} />);
+ await act(async () => { h.editor!.commands.setContent('<p>Do not bypass the new choice</p>'); });
+ expect((screen.getByRole('button', { name: 'newChat.sendButton.send' }) as HTMLButtonElement).disabled).toBe(true);
+ expect(onSend).not.toHaveBeenCalled();
+});
+
it.each([null, 'test-host'])('preserves no-effort after creation when sending the second message (%s)', async (deviceLinkDeviceId) => {
h.localProviders = [sshNativeCodexProvider([sshModel('qwen3:14b', { efforts: [], defaultEffort: null })])];
const onSend = vi.fn().mockResolvedValue(true);
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index db98316ec1..3e9a36f287 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -3979,6 +3979,8 @@ function CCAgentSessionContent({
mentions?: MentionedResource[],
opts?: {
deliveryMode?: MessageDeliveryMode;
+ providerId?: string | null;
+ baselineRecovery?: boolean;
literalText?: boolean;
independent?: boolean;
beforeEnqueue?: () => Promise<boolean>;
@@ -4135,7 +4137,13 @@ function CCAgentSessionContent({
// 的认证弹窗/导航闭包塞进 outbox:弱网时先建立稳定 clientId 的本地乐观消息,
// 重连后由被控端 enqueue / steer 路径做权威校验。这样离开任务后旧 outbox 也不会
// 再弹出旧页面的认证对话框或导航回旧路由。
- if (!remoteDeviceId) {
+ // The old Harness may no longer be authenticated. Only the unchanged
+ // host-offered route may defer this UI precheck to main's recovery.
+ const recoveringBaseline = opts?.baselineRecovery === true && session?.source === 'bot' &&
+ session.runtimeBaselineRecoveryPending === true && !session.runtimePending && !agentSwitchIntent &&
+ model === session.runtimeEffective?.model && displayAgentKind === session.runtimeEffective.agentKind &&
+ (opts.providerId ?? null) === (session.runtimeEffective.providerId ?? null);
+ if (!remoteDeviceId && !recoveringBaseline) {
const authVendor = displayAgentKind === 'pi' ? 'pi' : isCodex ? 'codex' : 'cc';
const { proceed } = await vendorAuthGate.checkAndConfirm(authVendor, {
// 已建会话:suspended 来源计入(停用不打断运行中会话,门禁只看凭证连接态,
@@ -4344,6 +4352,8 @@ function CCAgentSessionContent({
readOnly,
t,
vendorAuthGate,
+ displayAgentKind,
+ agentSwitchIntent,
confirmWithCheckbox,
remoteDeviceId,
sessionHandoffPreparing,
@@ -6094,6 +6104,7 @@ function CCAgentSessionContent({
// 让 ChatInput 暂不显示 Agent 身份,不能跟随 displayAgentKind 的 cc 回退。
runtimeAgentKind={session ? dbToMakerAgentKind(session.agentKind) : null}
runtimeEffective={session?.runtimeEffective}
+ allowBaselineRecovery={session?.source === 'bot' && session.runtimeBaselineRecoveryPending === true}
baselineEffort={session?.runtimeBaseline?.effort ?? null}
runtimePending={session?.runtimePending}
// session 未加载时保留 undefined 未知态;Orca 原地切换与换电脑分别门控。
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/sessionBaselineRecovery.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/sessionBaselineRecovery.test.ts
new file mode 100644
index 0000000000..298a88c854
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/sessionBaselineRecovery.test.ts
@@ -0,0 +1,63 @@
+import { readFileSync } from 'node:fs';
+import { runInNewContext } from 'node:vm';
+import ts from 'typescript';
+import { expect, it, vi } from 'vitest';
+import { projectSessionRuntimeControl } from '../../../../main/maker-ipc/sessionRuntimeControl';
+import { dbToMakerAgentKind } from '../../../../shared/agentKindConversion';
+
+// Execute the actual SessionView send callback up to its before-enqueue boundary.
+// A disconnected old Harness must not prevent main from restoring the saved one.
+const source = ts.createSourceFile('CCAgentSessionView.tsx', readFileSync(
+ new URL('../CCAgentSessionView.tsx', import.meta.url), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+let callback: ts.Expression | undefined;
+function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'handleSend' &&
+ node.initializer && ts.isCallExpression(node.initializer)) callback = node.initializer.arguments[0];
+ ts.forEachChild(node, visit);
+}
+visit(source);
+if (!callback) throw new Error('SessionView send callback missing');
+const code = ts.transpileModule('(' + callback.getText(source) + ')', {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+}).outputText;
+
+it.each(['recovery', 'ordinary', 'missing-offer', 'pending', 'new-provider', 'new-model', 'new-intent', 'no-composer-offer'])(
+ 'defers old-Harness authentication only for the unchanged recovery route (%s)', async (scenario) => {
+ const auth = vi.fn(async () => ({ proceed: false }));
+ const beforeEnqueue = vi.fn(async () => false); // Stop before unrelated persistence/workdir work.
+ const route = { agentKind: 'codex', model: 'retired', providerId: 'removed' };
+ const session = { source: scenario === 'ordinary' ? 'user' : 'bot',
+ runtimeBaselineRecoveryPending: scenario !== 'missing-offer',
+ runtimePending: scenario === 'pending' ? route : null, runtimeEffective: route };
+ const send = runInNewContext(code, { readOnly: false, cindyMakeInputLocked: false,
+ invalidateHistoryRecoveryNavigation: vi.fn(), getDataOwnerGeneration: () => 1,
+ remoteDeviceId: null, displayAgentKind: 'codex', isCodex: true, session,
+ agentSwitchIntent: scenario === 'new-intent' ? { target: 'pi' } : null,
+ vendorAuthGate: { checkAndConfirm: auth },
+ });
+ await send('hello', scenario === 'new-model' ? 'new' : 'retired', '', 'ask', undefined, undefined, {
+ literalText: true, baselineRecovery: scenario !== 'no-composer-offer',
+ providerId: scenario === 'new-provider' ? 'new' : 'removed', beforeEnqueue,
+ });
+ expect(auth).toHaveBeenCalledTimes(scenario === 'recovery' ? 0 : 1);
+ expect(beforeEnqueue).toHaveBeenCalledTimes(scenario === 'recovery' ? 1 : 0);
+ });
+
+it('authenticates the recovered Harness on subsequent sends after a legacy projection patch', async () => {
+ const recovered = { agentKind: 'pi' as const, model: 'saved', providerId: 'connected', effort: null, fastMode: false };
+ const session = { source: 'bot', agentKind: 'codex', runtimeBaselineRecoveryPending: true,
+ ...projectSessionRuntimeControl('recovered-companion', recovered) };
+ const auth = vi.fn(async (vendor: string) => ({ proceed: vendor === 'pi' }));
+ const beforeEnqueue = vi.fn(async () => false);
+ const displayAgentKind = dbToMakerAgentKind(session.agentKind);
+ const send = runInNewContext(code, { readOnly: false, cindyMakeInputLocked: false,
+ invalidateHistoryRecoveryNavigation: vi.fn(), getDataOwnerGeneration: () => 1,
+ remoteDeviceId: null, displayAgentKind, isCodex: displayAgentKind === 'codex', session,
+ agentSwitchIntent: null, vendorAuthGate: { checkAndConfirm: auth },
+ });
+ await send('hello again', recovered.model, '', 'ask', undefined, undefined, {
+ literalText: true, providerId: recovered.providerId, beforeEnqueue,
+ });
+ expect(auth).toHaveBeenCalledWith('pi', expect.anything());
+ expect(beforeEnqueue).toHaveBeenCalledOnce();
+});
diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.ts
index 221f005846..b0045cb89a 100644
--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts
+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts
@@ -367,6 +367,8 @@ export interface Session {
runtimeBaseline?: SessionRuntimeProfileProjection;
runtimeEffective?: SessionRuntimeProfileProjection;
runtimePending?: SessionRuntimePendingProjection | null;
+ /** Allows a companion input to reach host baseline recovery; does not assert model availability. */
+ runtimeBaselineRecoveryPending?: boolean;
/**
* 计划模式一级开关(与 permissionMode 正交):开启时 agent 先产出计划、经审批后再执行。
* 计划批准后 agent 自动退出并经 plan_mode_changed → sessions:patched 回流为 false。