Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(providers): respect the user's last default-provider change

Salman Qureshib1627694b7b3
diff --git a/src/core/agent.ts b/src/core/agent.ts
index db286b72..040e2c22 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -1353,6 +1353,8 @@ export class Agent {
}
private channelProviderOverrides = new Map<string, { providerName: string; modelName: string; provider: BaseProvider }>();
+ /** Dedupes the "served by a fallback provider" notice — one per (default → served) pair per runtime. */
+ private lastFallbackNoticeKey: string | null = null;
async listChatModelOptions(): Promise<Array<{ provider: string; label: string; model: string; models: string[]; selected: boolean }>> {
const active = getActiveProviders(this.config);
@@ -1438,9 +1440,13 @@ export class Agent {
const selected = this.providers.getDefault();
const model = selected.getModel();
+ // Persist: `/models use` is an explicit default change — it must survive
+ // restart. It used to mutate only the in-memory config, so the switch was
+ // silently lost (or half-persisted by an unrelated saveConfig) on restart.
+ saveConfig(this.config);
updateCliProviderStatus(this.channels.get('cli'), providerName, model);
- return { ok: true, message: `Session model switched to **${providerName}** · **${model}**.` };
+ return { ok: true, message: `Default model switched to **${providerName}** · **${model}**. Saved for future sessions.` };
}
/** Returns the currently active provider name and model. */
@@ -2962,6 +2968,24 @@ export class Agent {
}
if (!channelOverride) {
this.providers.markSuccess(provider.name);
+ // Respect the configured default: when a fallback provider served
+ // the turn instead of it, SAY SO. The fallback used to be silent —
+ // combined with markSuccess stickiness the user's doctor choice
+ // was invisibly overridden for the rest of the session. One
+ // notice per (default → served) pair per runtime keeps it visible
+ // without spamming every turn.
+ if (provider.name !== this.config.providers.default && msg.channelType !== 'internal') {
+ const noticeKey = `${this.config.providers.default}→${provider.name}`;
+ if (this.lastFallbackNoticeKey !== noticeKey) {
+ this.lastFallbackNoticeKey = noticeKey;
+ const failureReason = providerFailures.get(this.config.providers.default)
+ ?? 'not registered — run `mercury doctor`';
+ await channel?.send(
+ `⚠ Configured default \`${this.config.providers.default}\` unavailable (${failureReason}) — served by \`${provider.name}\` this time.`,
+ msg.channelId,
+ ).catch((e) => logger.warn({ e }, 'channel send failed'));
+ }
+ }
}
break;
} catch (err: any) {
@@ -4850,7 +4874,7 @@ Is this productive iteration or a stuck loop?`,
return `• ${p.name} · ${p.model}${marker}`;
}),
'',
- 'Use `/models use <provider>` to switch for this session.',
+ 'Use `/models use <provider>` to switch the default (saved across restarts).',
'Use `mercury doctor` to add/configure models.',
];
await channel.send(lines.join('\n'), channelId);
diff --git a/src/core/provider-default.test.ts b/src/core/provider-default.test.ts
new file mode 100644
index 00000000..583f8b39
--- /dev/null
+++ b/src/core/provider-default.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+const src = (p: string) => readFileSync(join(dirname(fileURLToPath(import.meta.url)), p), 'utf8');
+
+/**
+ * "Respect the last default change" contract. Three defects used to conspire
+ * into silently overriding the provider the user chose in `mercury doctor`:
+ *
+ * 1. `/models use` mutated the in-memory config only — the switch was lost
+ * on restart (or half-persisted by an unrelated saveConfig).
+ * 2. The fallback chain tried Mercury Cloud FIRST (registration order) and
+ * markSuccess then stuck to it for every following turn — silently.
+ * 3. The doctor's Connection Mode selector always highlighted 'cloud', so
+ * pressing Enter re-paired the cloud and reset the default to mercuryCloud.
+ *
+ * The runtime fixes live in agent.ts / registry.ts (unit-tested there); these
+ * source assertions pin the wiring so a refactor can't quietly drop them.
+ */
+describe('default provider is respected', () => {
+ it('agent: /models use persists the switch via saveConfig', () => {
+ const agent = src('agent.ts');
+ // The persisted message must say so — no silent session-only mutation.
+ expect(agent).toContain('Default model switched to');
+ expect(agent).toContain('Saved for future sessions');
+ // switchSessionProvider saves after rebuilding the registry.
+ expect(agent).toMatch(/saveConfig\(this\.config\);\s*\n\s*updateCliProviderStatus\(this\.channels\.get\('cli'\), providerName, model\);/);
+ });
+
+ it('agent: fallback to a non-default provider is surfaced to the user, not silent', () => {
+ const agent = src('agent.ts');
+ expect(agent).toContain('lastFallbackNoticeKey');
+ expect(agent).toContain('Configured default');
+ });
+
+ it('doctor: Connection Mode highlights the current mode, Enter keeps the current default', () => {
+ const index = src('../index.ts');
+ expect(index).toContain('const inCloudMode');
+ expect(index).toContain("configured.includes(config.providers.default)");
+ });
+});
\ No newline at end of file
diff --git a/src/index.ts b/src/index.ts
index b87d41d9..d11e3145 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -236,7 +236,14 @@ async function chooseDefaultProvider(config: MercuryConfig): Promise<void> {
return;
}
- const suggested = configured.includes('deepseek') ? 'deepseek' : configured[0];
+ // Suggest the CURRENT default when it's still configured — on reconfig,
+ // pressing Enter (the universal "keep current" convention in this wizard)
+ // must keep it, not jump to the hard-coded suggestion.
+ const suggested = configured.includes(config.providers.default)
+ ? config.providers.default
+ : configured.includes('deepseek')
+ ? 'deepseek'
+ : configured[0];
console.log('');
console.log(chalk.bold.white(' Default Provider'));
@@ -1130,12 +1137,17 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {
console.log('');
}
+ // Reconfig respects the current mode: the CURRENT connection mode is
+ // listed first (and therefore highlighted), so pressing Enter to "keep
+ // current" can't accidentally re-pair Mercury Cloud and reset the default
+ // provider — which used to silently override the user's last choice.
+ const inCloudMode = config.providers.default === 'mercuryCloud' || config.cloud.enabled === true;
+ const cloudOption = { value: 'cloud', label: 'Mercury Cloud (hosted — no API keys needed)' };
+ const offlineOption = { value: 'offline', label: 'Offline / BYOK (bring your own keys)' };
+ const modeOptions = isReconfig && !inCloudMode ? [offlineOption, cloudOption] : [cloudOption, offlineOption];
const cloudChoice = await selectWithArrowKeys(
isReconfig ? 'Connection Mode' : 'Choose your mode',
- [
- { value: 'cloud', label: 'Mercury Cloud (hosted — no API keys needed)' },
- { value: 'offline', label: 'Offline / BYOK (bring your own keys)' },
- ],
+ modeOptions,
);
let llmConfiguredByCloud = false;
diff --git a/src/providers/registry.test.ts b/src/providers/registry.test.ts
index 30986aed..551b1890 100644
--- a/src/providers/registry.test.ts
+++ b/src/providers/registry.test.ts
@@ -22,3 +22,52 @@ describe('ProviderRegistry live default', () => {
expect(registry.getDefault().getModel()).toBe('model-b');
});
});
+
+/**
+ * Fallback order must respect the user's chosen default. Registration order
+ * puts Mercury Cloud first in the map, so a failed attempt on a BYOK default
+ * used to promote Mercury Cloud immediately — and markSuccess then stuck to
+ * it for every following turn, silently overriding the doctor's choice.
+ */
+describe('ProviderRegistry fallback order', () => {
+ function registryWithDefault(defaultName: string): ProviderRegistry {
+ const registry = new (ProviderRegistry as any)(defaultName) as ProviderRegistry;
+ // Registration order mirrors the real one: Mercury Cloud first.
+ registry.set('mercuryCloud', provider('mercuryCloud', 'cloud-model'));
+ registry.set('deepseek', provider('deepseek', 'deepseek-model'));
+ registry.set('chatgptWeb', provider('chatgptWeb', 'gpt-web'));
+ return registry;
+ }
+
+ const order = (registry: ProviderRegistry, preferred?: string): string[] => {
+ const iterator = registry.getFallbackIterator(preferred);
+ return [...iterator].map((p) => p.name);
+ };
+
+ it('puts Mercury Cloud LAST in the fallback chain when the default is a BYOK provider', () => {
+ const registry = registryWithDefault('chatgptWeb');
+ const names = order(registry);
+ expect(names[0]).toBe('chatgptWeb');
+ expect(names[names.length - 1]).toBe('mercuryCloud');
+ expect(names).toContain('deepseek');
+ });
+
+ it('keeps Mercury Cloud first when it IS the chosen default', () => {
+ const registry = registryWithDefault('mercuryCloud');
+ expect(order(registry)[0]).toBe('mercuryCloud');
+ });
+
+ it('respects an explicit preferred provider (channel override) the same way', () => {
+ const registry = registryWithDefault('mercuryCloud');
+ const names = order(registry, 'deepseek');
+ expect(names[0]).toBe('deepseek');
+ expect(names[names.length - 1]).toBe('mercuryCloud');
+ });
+
+ it('never drops or duplicates the default provider', () => {
+ const registry = registryWithDefault('chatgptWeb');
+ const names = order(registry);
+ expect(names.filter((n) => n === 'chatgptWeb')).toHaveLength(1);
+ expect(new Set(names).size).toBe(names.length);
+ });
+});
diff --git a/src/providers/registry.ts b/src/providers/registry.ts
index a000d339..047fa6d0 100644
--- a/src/providers/registry.ts
+++ b/src/providers/registry.ts
@@ -135,11 +135,26 @@ export class ProviderRegistry {
const preferredProvider = preferredName ? this.providers.get(preferredName) : undefined;
const defaultProvider = preferredProvider || this.getDefault();
ordered.push(defaultProvider);
+ const rest: BaseProvider[] = [];
for (const [, provider] of this.providers) {
if (provider !== defaultProvider) {
- ordered.push(provider);
+ rest.push(provider);
}
}
+ // Respect the user's chosen default: Mercury Cloud is the vendor-hosted
+ // safety net, not the first hijacker. Registration order puts it first in
+ // the map, so any failed attempt on a BYOK default used to promote
+ // Mercury Cloud immediately — and markSuccess then stuck to it for every
+ // following turn, silently overriding the configured default. When the
+ // user's default is NOT Mercury Cloud, it goes LAST in the fallback chain.
+ if (defaultProvider.name !== 'mercuryCloud') {
+ const cloudIndex = rest.findIndex((p) => p.name === 'mercuryCloud');
+ if (cloudIndex >= 0) {
+ const [cloud] = rest.splice(cloudIndex, 1);
+ rest.push(cloud);
+ }
+ }
+ ordered.push(...rest);
return ordered[Symbol.iterator]();
}