Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop spending a fallbackModel pin the fallback provider no longer serves
[._.]/ Adam Eivy769dddf34744
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 29a4ad18b1..fb670eee4c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -113,6 +113,8 @@- **A successful agent run is no longer failed just because someone pulled `main` while it worked.** The branch-jack detector — which watches whether a worktree-isolated agent committed into the primary checkout instead of its own worktree — treated *any* movement of the primary as a branch-jack. So an ordinary `git pull` landing an already-merged PR flipped a run that had shipped its own PR into a failure, and told the user to consider `git reset --hard origin/main` over commits that already *were* `origin/main`. The guard now reports what a branch-jack actually leaves behind: commits the branch's upstream does not have, or the checkout parked on a different branch than it started on. A pure fast-forward onto upstream commits is logged as movement and nothing more. When damage is real, the recovery advice is sharper too — it quotes the number of *stranded* commits rather than how far HEAD travelled, and a checkout merely left on the wrong branch with nothing stranded is told to `git checkout` back instead of being pointed at a `--hard` reset that would discard nothing. A branch with no upstream to compare against still reports, since an unpushed commit is unreviewed by definition.+- **A provider's fallback model no longer goes stale when the fallback provider's model list moves on.** `Fallback model` is the one AI-provider setting that names a model belonging to a *different* provider — you set it on, say, Codex, but it is spent against Codex's configured fallback. So every release that retired a Claude model id and rewrote that provider's own tiers left the pins aimed at it dangling, and nothing downstream noticed: the dead id went straight into the fallback's `--model` flag at exactly the moment the primary had already failed and the retry was the last one available. A pin the fallback provider no longer lists is now dropped at run time in favour of that provider's own default — the same thing an unpinned fallback already does, and strictly better than a model known to be absent — and a migration repairs the pins already saved on disk. The repair is deliberately self-validating: it rewrites a pin only when the fallback provider genuinely no longer serves it *and* does serve the mapped replacement, so a curated older model you chose on purpose is left exactly as it is, and a Bedrock long-context pin maps to its long-context successor rather than silently dropping to standard context.+- **Recovering an AI provider now affects the very next routed run.** PortOS accidentally kept two in-memory provider-status services over the same JSON file: the Providers UI updated one while the AI Toolkit's runner consulted the other. A manual “Recover now” therefore looked successful and persisted correctly, yet a run started moments later could still bypass the recovered primary and spend time on a fallback. All legacy callers and the PortOS status routes now delegate to the Toolkit-owned singleton, and provider status socket events have one broadcast path instead of being emitted twice.- **A timed-out creative stage no longer benches its provider as “quota exceeded.”** TUI finalization previously classified a hard timeout by scanning the whole terminal response, which includes the story prompt; ordinary narrative words such as “credit,” “payment,” or “billing” could therefore override exit 124 and sideline a healthy provider for an hour. The host's timeout signal is now authoritative, while non-timeout failures continue to use provider-output analysis for real usage, auth, model, and network banners.diff --git a/scripts/migrations/240-fallback-model-retired-claude-ids.js b/scripts/migrations/240-fallback-model-retired-claude-ids.jsnew file mode 100644index 0000000000..79c0453b37--- /dev/null+++ b/scripts/migrations/240-fallback-model-retired-claude-ids.js@@ -0,0 +1,128 @@+/**+ * Repair `fallbackModel` pins that still name a retired Claude model id.+ *+ * Migrations 058 / 153 / 206 each bumped the seeded Claude model tier and+ * remapped the four tier pointers (`defaultModel`, `lightModel`,+ * `mediumModel`, `heavyModel`) on the four Claude providers. None of them+ * touched `fallbackModel` — and `fallbackModel` is the one pointer that lives+ * on a DIFFERENT provider than the models it names: it is set on the primary+ * (e.g. `codex-tui`) but resolved against that primary's `fallbackProvider`+ * (e.g. `claude-code-tui-bedrock`). So a bump that rewrote the Claude+ * provider's own list left every pin aimed at it dangling:+ *+ * codex → claude-code-tui / claude-opus-4-8 (retired by 206)+ * codex-tui → claude-code-tui-bedrock / global.anthropic.claude-opus-4-8+ *+ * A dangling pin is not inert. It is spent at exactly the moment the primary+ * has already failed and the cascade is down to its last deterministic retry+ * (promptRunner Tier 3), where it is baked into the spawned `--model` flag —+ * so the recovery attempt is issued against a model the fallback provider no+ * longer serves.+ *+ * Repair rule — deliberately self-validating, so this can run over a curated+ * config without second-guessing the user. A pin is rewritten only when BOTH:+ * 1. the fallback provider does NOT list the pinned id (it's genuinely dead+ * there — a pin that still resolves is left exactly as-is, even if it+ * names an older generation the user chose on purpose), AND+ * 2. the mapped replacement IS listed by that provider (we can name a+ * concrete working substitute rather than guessing).+ * Anything else is left alone for `usableFallbackModel` to handle at runtime+ * (it drops an unresolvable pin to the provider's own default).+ *+ * Providers with no enumerable `models` list (local backends that discover+ * models at runtime) are skipped by rule 2 — there is nothing to validate+ * against.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++const PROVIDERS_REL_PATH = 'data/providers.json';++// Retired id → current replacement, across every Claude tier bump that shipped+// without a `fallbackModel` remap. Chains are pre-resolved to their CURRENT+// endpoint (opus-4-7 → opus-4-8 → opus-5 collapses to opus-4-7 → opus-5) so a+// pin left behind by an older bump lands on today's id in one pass.+const RETIRED_MODEL_MAP = {+ // 058 → 206 (opus tier, bare ids)+ 'claude-opus-4-7': 'claude-opus-5',+ 'claude-opus-4-8': 'claude-opus-5',+ // 206 (opus tier, Bedrock inference profiles — `[1m]` maps like-for-like so+ // a long-context pin never silently drops to standard context)+ 'global.anthropic.claude-opus-4-7': 'global.anthropic.claude-opus-5',+ 'global.anthropic.claude-opus-4-7[1m]': 'global.anthropic.claude-opus-5[1m]',+ 'global.anthropic.claude-opus-4-8': 'global.anthropic.claude-opus-5',+ 'global.anthropic.claude-opus-4-8[1m]': 'global.anthropic.claude-opus-5[1m]',+ // 153 (sonnet tier)+ 'claude-sonnet-4-6': 'claude-sonnet-5',+ 'us.anthropic.claude-sonnet-4-6': 'us.anthropic.claude-sonnet-5',+ 'global.anthropic.claude-sonnet-4-6': 'global.anthropic.claude-sonnet-5',+};++// `Object.hasOwn` before the lookup so a pin literally named `constructor` /+// `toString` can't inherit an Object.prototype member as its "replacement".+const replacementFor = (modelId) => (+ Object.hasOwn(RETIRED_MODEL_MAP, modelId) ? RETIRED_MODEL_MAP[modelId] : null+);++const lists = (provider, modelId) => (+ Array.isArray(provider?.models) && provider.models.includes(modelId)+);++export default {+ async up({ rootDir }) {+ const providersPath = join(rootDir, PROVIDERS_REL_PATH);+ const raw = await readFile(providersPath, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh installs seed no fallbackModel pins)`);+ return;+ }++ let config;+ try {+ config = JSON.parse(raw);+ } catch (err) {+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);+ return;+ }++ const providers = config?.providers;+ if (!providers || typeof providers !== 'object') {+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: no providers map — skipping`);+ return;+ }++ const touched = [];++ for (const [id, provider] of Object.entries(providers)) {+ if (!provider || typeof provider !== 'object') continue;+ const pinned = provider.fallbackModel;+ if (!pinned || typeof pinned !== 'string') continue;++ // The pin is resolved against the fallback PROVIDER, not this one — so+ // that is the model list it has to survive.+ const target = providers[provider.fallbackProvider];+ if (!target) continue;++ if (lists(target, pinned)) continue; // still resolves — leave it alone++ const replacement = replacementFor(pinned);+ if (!replacement || !lists(target, replacement)) continue;++ provider.fallbackModel = replacement;+ touched.push({ id, target: provider.fallbackProvider, from: pinned, to: replacement });+ }++ if (touched.length === 0) {+ console.log(`✅ ${PROVIDERS_REL_PATH}: no stale fallbackModel pins`);+ return;+ }++ await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);+ const summary = touched.map((t) => `${t.id} → ${t.target}: ${t.from} → ${t.to}`).join(', ');+ console.log(`📝 ${PROVIDERS_REL_PATH}: repaired ${touched.length} stale fallbackModel pin(s) — ${summary}`);+ },+};diff --git a/scripts/migrations/240-fallback-model-retired-claude-ids.test.js b/scripts/migrations/240-fallback-model-retired-claude-ids.test.jsnew file mode 100644index 0000000000..d4395c9731--- /dev/null+++ b/scripts/migrations/240-fallback-model-retired-claude-ids.test.js@@ -0,0 +1,163 @@+/**+ * Test for migration 240 — repair `fallbackModel` pins left dangling by the+ * Claude tier bumps (058 / 153 / 206), which remapped the four tier pointers+ * but never `fallbackModel`. Picked up by server/vitest.config.js's+ * `../scripts/**\/*.test.js` glob.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './240-fallback-model-retired-claude-ids.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const CLAUDE_TUI_MODELS = ['claude-haiku-4-5', 'claude-sonnet-5', 'claude-opus-5'];+const BEDROCK_TUI_MODELS = [+ 'us.anthropic.claude-sonnet-5',+ 'global.anthropic.claude-opus-5',+ 'global.anthropic.claude-opus-5[1m]',+];++// The exact shape this install was found in: codex/codex-tui each pin a Claude+// fallback model that migration 206 retired out from under them.+const staleConfig = () => ({+ activeProvider: 'codex-tui',+ providers: {+ codex: {+ id: 'codex',+ models: ['gpt-5.6-terra'],+ fallbackProvider: 'claude-code-tui',+ fallbackModel: 'claude-opus-4-8',+ },+ 'codex-tui': {+ id: 'codex-tui',+ models: ['gpt-5.6-terra'],+ fallbackProvider: 'claude-code-tui-bedrock',+ fallbackModel: 'global.anthropic.claude-opus-4-8',+ },+ 'claude-code-tui': { id: 'claude-code-tui', models: [...CLAUDE_TUI_MODELS] },+ 'claude-code-tui-bedrock': { id: 'claude-code-tui-bedrock', models: [...BEDROCK_TUI_MODELS] },+ },+});++describe('migration 240 — repair retired fallbackModel pins', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-240-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('remaps a retired pin to the replacement the fallback provider lists', async () => {+ writeJson(providersPath, staleConfig());++ await migration.up({ rootDir });++ const out = readJson(providersPath).providers;+ expect(out.codex.fallbackModel).toBe('claude-opus-5');+ expect(out['codex-tui'].fallbackModel).toBe('global.anthropic.claude-opus-5');+ });++ it('maps the Bedrock [1m] long-context pin like-for-like', async () => {+ const config = staleConfig();+ config.providers['codex-tui'].fallbackModel = 'global.anthropic.claude-opus-4-8[1m]';+ writeJson(providersPath, config);++ await migration.up({ rootDir });++ expect(readJson(providersPath).providers['codex-tui'].fallbackModel)+ .toBe('global.anthropic.claude-opus-5[1m]');+ });++ it('collapses an older chained id (opus-4-7) straight to the current one', async () => {+ const config = staleConfig();+ config.providers.codex.fallbackModel = 'claude-opus-4-7';+ writeJson(providersPath, config);++ await migration.up({ rootDir });++ expect(readJson(providersPath).providers.codex.fallbackModel).toBe('claude-opus-5');+ });++ it('leaves a pin the fallback provider still lists untouched', async () => {+ const config = staleConfig();+ // A user who curated `claude-code-tui` to keep sonnet-4-6 alive still has a+ // working pin — an older id is not automatically a dead one.+ config.providers['claude-code-tui'].models = ['claude-sonnet-4-6', 'claude-opus-5'];+ config.providers.codex.fallbackModel = 'claude-sonnet-4-6';+ writeJson(providersPath, config);++ await migration.up({ rootDir });++ expect(readJson(providersPath).providers.codex.fallbackModel).toBe('claude-sonnet-4-6');+ });++ it('leaves a dead pin alone when the replacement is not listed either', async () => {+ const config = staleConfig();+ config.providers['claude-code-tui'].models = ['claude-haiku-4-5'];+ writeJson(providersPath, config);++ await migration.up({ rootDir });++ // Nothing to safely swap to — runtime `usableFallbackModel` drops it to the+ // provider default instead of this migration guessing.+ expect(readJson(providersPath).providers.codex.fallbackModel).toBe('claude-opus-4-8');+ });++ it('skips a provider whose fallbackProvider does not exist', async () => {+ const config = staleConfig();+ config.providers.codex.fallbackProvider = 'deleted-provider';+ writeJson(providersPath, config);++ await migration.up({ rootDir });++ expect(readJson(providersPath).providers.codex.fallbackModel).toBe('claude-opus-4-8');+ });++ it('does not rewrite the file when nothing is stale', async () => {+ const config = staleConfig();+ config.providers.codex.fallbackModel = 'claude-opus-5';+ config.providers['codex-tui'].fallbackModel = 'global.anthropic.claude-opus-5';+ writeJson(providersPath, config);+ const before = readFileSync(providersPath, 'utf-8');++ await migration.up({ rootDir });++ expect(readFileSync(providersPath, 'utf-8')).toBe(before);+ });++ it('ignores a pin named after an Object.prototype member', async () => {+ const config = staleConfig();+ config.providers.codex.fallbackModel = 'constructor';+ writeJson(providersPath, config);++ await migration.up({ rootDir });++ expect(readJson(providersPath).providers.codex.fallbackModel).toBe('constructor');+ });++ it('is a no-op when providers.json is absent', async () => {+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ expect(existsSync(providersPath)).toBe(false);+ });++ it('is a no-op on invalid JSON', async () => {+ writeFileSync(providersPath, '{ not json');+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ expect(readFileSync(providersPath, 'utf-8')).toBe('{ not json');+ });++ it('is a no-op when there is no providers map', async () => {+ writeJson(providersPath, { activeProvider: 'codex' });+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ });+});diff --git a/server/lib/aiToolkit/providerStatus.js b/server/lib/aiToolkit/providerStatus.jsindex 9d14c76706..1ec4c13349 100644--- a/server/lib/aiToolkit/providerStatus.js+++ b/server/lib/aiToolkit/providerStatus.js@@ -11,6 +11,42 @@ import { existsSync } from 'fs';import { join, dirname } from 'path';import { atomicWrite } from './internal/atomicWrite.js';+/**+ * Gate a *configured* fallback-model pin against the fallback provider's own+ * model list.+ *+ * `fallbackModel` (provider-level) and a task's fallback model are pins the+ * user chose once and that then sit in `providers.json` / the task record+ * forever. When the fallback provider's `models` list later moves on — a model+ * bump migration retires an id, or the user curates the list by hand — the pin+ * is left naming a model that provider no longer serves, and nothing downstream+ * notices: `resolveEffectiveModel` only screens for empty/embedding ids, so the+ * dead id gets baked straight into the spawned `--model` flag. That turns the+ * one retry the cascade has left into a request against a model that isn't+ * there.+ *+ * So: keep the pin only when the fallback provider actually lists it. Dropping+ * it to `null` means "let the fallback resolve its own default", which is the+ * same thing an unpinned fallback already does — strictly better than a model+ * id known to be absent.+ *+ * Providers with no enumerable `models` (local backends that discover theirs at+ * runtime, hand-typed ids in the free-text picker) have nothing to check+ * against, so their pins pass through untouched.+ *+ * @param {object} provider — the chosen fallback provider+ * @param {string|null|undefined} pinnedModel — the configured pin+ * @returns {string|null}+ */+export function usableFallbackModel(provider, pinnedModel) {+ if (!pinnedModel) return null;+ const models = provider?.models;+ if (!Array.isArray(models) || models.length === 0) return pinnedModel;+ if (models.includes(pinnedModel)) return pinnedModel;+ console.log(`⚠️ Fallback ${provider?.id || 'provider'} no longer lists pinned model ${pinnedModel} — using its own default instead`);+ return null;+}+export function createProviderStatusService(config = {}) {const {dataDir = './data',@@ -268,7 +304,7 @@ export function createProviderStatusService(config = {}) {if (taskFallbackId && taskFallbackId !== primaryProviderId) {const taskFallback = providers[taskFallbackId];if (taskFallback?.enabled && this.isAvailable(taskFallback.id)) {- return { provider: taskFallback, source: 'task', model: taskFallbackModelId || null };+ return { provider: taskFallback, source: 'task', model: usableFallbackModel(taskFallback, taskFallbackModelId) };}}@@ -280,7 +316,7 @@ export function createProviderStatusService(config = {}) {if (primaryProvider?.fallbackProvider && primaryProvider.fallbackProvider !== primaryProviderId) {const configuredFallback = providers[primaryProvider.fallbackProvider];if (configuredFallback?.enabled && this.isAvailable(configuredFallback.id)) {- return { provider: configuredFallback, source: 'provider', model: primaryProvider.fallbackModel || null };+ return { provider: configuredFallback, source: 'provider', model: usableFallbackModel(configuredFallback, primaryProvider.fallbackModel) };}}diff --git a/server/lib/aiToolkit/providerStatus.test.js b/server/lib/aiToolkit/providerStatus.test.jsindex c0f68bad30..ab6168ec6d 100644--- a/server/lib/aiToolkit/providerStatus.test.js+++ b/server/lib/aiToolkit/providerStatus.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdir, rm } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';-import { createProviderStatusService } from './providerStatus.js';+import { createProviderStatusService, usableFallbackModel } from './providerStatus.js';const TEST_DATA_DIR = join(process.cwd(), 'test-data-status');@@ -361,6 +361,90 @@ describe('Provider Status Service', () => {});});+ describe('getFallbackProvider — stale model pins', () => {+ // A `fallbackModel` is set on the PRIMARY but resolved against the+ // fallback, so a model bump on the fallback leaves the pin naming an id+ // that provider no longer serves. Spending that pin sends the cascade's+ // last retry at a model that isn't there.+ const providersWithModels = (fallbackModel) => ({+ 'primary-provider': {+ id: 'primary-provider',+ enabled: true,+ fallbackProvider: 'configured-fallback',+ fallbackModel,+ },+ 'configured-fallback': {+ id: 'configured-fallback',+ enabled: true,+ models: ['claude-sonnet-5', 'claude-opus-5'],+ },+ });++ it('drops a pin the fallback provider no longer lists', () => {+ const result = statusService.getFallbackProvider(+ 'primary-provider',+ providersWithModels('claude-opus-4-8')+ );++ expect(result.provider.id).toBe('configured-fallback');+ // null ⇒ "let the fallback resolve its own default" — strictly better+ // than baking a known-absent id into the spawned --model flag.+ expect(result.model).toBeNull();+ });++ it('keeps a pin the fallback provider still lists', () => {+ const result = statusService.getFallbackProvider(+ 'primary-provider',+ providersWithModels('claude-opus-5')+ );++ expect(result.model).toBe('claude-opus-5');+ });++ it('drops a stale task-level pin too', () => {+ const providers = {+ 'primary-provider': { id: 'primary-provider', enabled: true },+ 'task-fallback': {+ id: 'task-fallback',+ enabled: true,+ models: ['claude-opus-5'],+ },+ };++ const result = statusService.getFallbackProvider(+ 'primary-provider',+ providers,+ 'task-fallback',+ 'claude-opus-4-8'+ );++ expect(result.source).toBe('task');+ expect(result.model).toBeNull();+ });+ });++ describe('usableFallbackModel', () => {+ it('returns null for an empty pin', () => {+ expect(usableFallbackModel({ id: 'p', models: ['a'] }, null)).toBeNull();+ expect(usableFallbackModel({ id: 'p', models: ['a'] }, '')).toBeNull();+ });++ it('passes the pin through when the provider lists no models', () => {+ // Local backends discover their models at runtime, and the UI offers a+ // free-text pin when there is no list — nothing to validate against.+ expect(usableFallbackModel({ id: 'ollama', models: [] }, 'llama3')).toBe('llama3');+ expect(usableFallbackModel({ id: 'ollama' }, 'llama3')).toBe('llama3');+ });++ it('passes a listed pin through', () => {+ expect(usableFallbackModel({ id: 'p', models: ['a', 'b'] }, 'b')).toBe('b');+ });++ it('drops an unlisted pin', () => {+ expect(usableFallbackModel({ id: 'p', models: ['a', 'b'] }, 'c')).toBeNull();+ });+ });+describe('getTimeUntilRecovery', () => {it('should return null for available provider', () => {const time = statusService.getTimeUntilRecovery('test-provider');