Skip to content

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

retry AI provider runs with configured fallback before queuing investigation task (#429)

[._.]/ Adam Eivy82f637f91e55
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 543bcb2a81..1472afd95f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -29,6 +29,7 @@
## Fixed
+- **AI provider failures fall back to a configured backup model instead of queuing "Investigate AI provider failure" tasks.** When a CLI or API run failed (LM Studio unreachable, Claude Code CLI exit 1, network blip), the auto-fixer used to queue a plan task immediately even when `fallbackProvider` was configured. The runner now retries once with the fallback when a primary fails — if the fallback succeeds the deferred investigation task is cancelled and the call returns transparently (`usedFallback: true` for callers that care). The failed primary is also marked unavailable for a category-appropriate cooldown (5 min for rate-limit, 2 min for network errors, etc.) so subsequent calls within that window skip it proactively instead of repeating the same fail-and-retry round-trip. Investigation tasks still fire when no fallback exists or when the fallback also fails. `providerStatus.markUnavailable()` is now the generic primitive; the existing `markUsageLimit` / `markRateLimited` are thin wrappers on it.
- **[universebuilder-collection-hook-flaky-batch-enrich] Universe Builder batch-enrich test no longer flakes under full-suite load** — internal test stability fix; production behavior unchanged.
- **[feeds-ssrf-ipv6-bracket-hostname-gap] RSS feed subscriptions now reliably reject IPv6 loopback, link-local, and unique-local addresses** — previously the loopback `http://[::1]/feed` case was blocked only incidentally by DNS errors; subscribing to feeds at literal private IPv6 addresses is now refused outright, including IPv4-mapped variants like `[::ffff:192.168.1.1]`.
- **[feeds-ssrf-aaaa-record-blindness] RSS feed subscriptions now check the IPv6 address family too** — a hostname that pointed to a public IPv4 address but a private IPv6 one used to slip past the SSRF guard because only the IPv4 records were checked; now both families are resolved together, any private address in either family rejects the feed, and IPv6-only hostnames (which used to fail outright) are accepted when they resolve to a public address.
diff --git a/PLAN.md b/PLAN.md
index 50d0bd6c76..a4d1cebb70 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -4,6 +4,8 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
## Next Up
+- [ ] [ai-fallback-coalesce-concurrent-failures] **Coalesce concurrent AI provider failures so N simultaneous calls don't all re-read `providers.json` and re-mark the same provider.** Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22). When a stuck provider has N simultaneous in-flight calls, each failure independently runs `pickFallbackProvider` → `getAllProviders()` → `loadProviders()` (which reads `providers.json` from disk every time — no in-memory cache) → `markUnavailable` (writing `provider-status.json`). Two fixes that compound: (a) add a tiny TTL cache (~1s) to `aiToolkit/providers.js#loadProviders` so the read cost is amortized; (b) coalesce per-provider failure handling in `promptRunner.js` with a `Map<providerId, Promise>` so subsequent failures for the same provider await the first's mark-and-pick result and skip the duplicate work. Together they cut N-way failure storms to one disk-write + one mark. Acceptance: under a simulated 10-concurrent-failure load, providers.json is read at most twice and provider-status.json is written once.
+- [ ] [propagate-runner-errorAnalysis-into-onRunFailed-context] **Propagate `metadata.errorAnalysis` into the `onRunFailed` event context** so `promptRunner.js#markProviderUnavailableFromError` doesn't re-run `analyzeError` on the same text the runner already analyzed. The runner writes `errorAnalysis` to `metadata` (`server/lib/aiToolkit/runner.js:245`, 343, 433) but `server/index.js:202` only forwards a subset to the error event, so the analysis pass is duplicated on every failure. Either add `errorAnalysis` to the event context AND to the rejected error thrown to promptRunner, or attach it to the metadata object that the rejection carries. Microsecond-class perf, but cleaner. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22).
- [ ] [extract-compare-helpers-once-eight-callers] **Extract `equalByKeys` / `equalListByKeys` once `useAutoRefetch`'s `compare` reaches ~8 widget callers.** With the dashboard rollout (PR #421) there are now 5 widget callers (Backup, Chief of Staff, Decision Log, Goal Progress, Proactive Alerts) on top of EpisodeVideoStage / Brain / Digital Twin from PR #425, using two emerging shapes — (a) scalar-object key equality (BackupWidget status, DecisionLogWidget last24Hours, ProactiveAlertsWidget counts) and (b) array equality by length + per-item key tuple (BackupWidget snapshots, GoalProgressWidget goals, ProactiveAlertsWidget alerts list, DecisionLogWidget impactfulDecisions). Inline forms are noisy but each has an explanatory comment that an `equalByKeys(prev, next, ['status', 'lastRun', …])` would lose. Defer until enough more callers appear that the abstraction pays for itself, then add helpers to `client/src/lib/compareHelpers.js` (register in `index.js` + `README.md`) and migrate the flat callers — leave CosDashboardWidget's nested-optional-chain shape inline. Surfaced by /simplify reuse review during `[useautorefetch-compare-caller-rollout-widgets]` claim 2026-05-21.
- [ ] [codex5-onboarding-capability-map] **[P2][ONBOARDING]** Capability map of connected systems. One page showing each integration's status: Providers (per-provider configured/available/throttled), Calendar, Brain/memory embeddings, Voice (mic + TTS), Tailscale + HTTPS, Genome/health imports, Telegram/messages, App registry/PM2. Each row links to the relevant settings page. Doubles as a setup checklist and a runtime health overview.
- [ ] [dedupe-hhmm-time-window-helpers] **Dedupe HH:MM time-window helpers across server.** `server/services/voice/proactiveSpeech.js` exports `HHMM_RE` + `parseHHMM` + `isWithinQuietHours` (lines 26–57). `server/services/dashboardLayouts.js#sanitizeActivateWindow` + the inlined `isInTimeWindow` logic (post `[codex5-dashboard-intent-layouts]`) duplicate the same predicate (~25 LOC). Lift the three primitives to `server/lib/timezone.js` (where `getLocalParts` already lives) and have both `proactiveSpeech.js` and `dashboardLayouts.js` import from there. The dashboard route's Zod schema (`TIME_STRING_RE`) can keep aliasing the shared regex. Also evaluate whether `client/src/utils/timeWindow.js` (intentional client mirror) needs a parity test against the server primitive — surfaced by /simplify reuse review during `[codex5-dashboard-intent-layouts]` claim 2026-05-20.
diff --git a/server/lib/aiToolkit/providerStatus.js b/server/lib/aiToolkit/providerStatus.js
index 8d7f586fb8..fdafb0e32e 100644
--- a/server/lib/aiToolkit/providerStatus.js
+++ b/server/lib/aiToolkit/providerStatus.js
@@ -163,9 +163,25 @@ export function createProviderStatusService(config = {}) {
return status.available;
},
- async markUsageLimit(providerId, errorInfo = {}) {
+ // Generic unavailability marker. Each specific marker below (usage-limit,
+ // rate-limit) is now a thin wrapper that supplies its own cooldown +
+ // message defaults — keeps the persistence path in one place and lets
+ // ad-hoc callers (e.g. promptRunner.js on a failed run) mark a provider
+ // unavailable with a custom reason like 'network-error' without
+ // proliferating wrapper methods for every error category.
+ //
+ // `extras` is an optional object of category-specific fields to splat
+ // onto the persisted record (e.g. `waitTime: '5 hours'` for usage-limit
+ // displays). Splatting in this single write keeps `status:changed`
+ // listeners from observing a half-built record on the first emit.
+ async markUnavailable(providerId, options = {}) {
+ const {
+ reason = 'unknown',
+ message = 'Provider unavailable',
+ waitTimeMs = defaultRateLimitWait,
+ extras = null
+ } = options;
const now = new Date();
- const waitTimeMs = parseWaitTime(errorInfo.waitTime) || defaultUsageLimitWait;
const estimatedRecovery = new Date(now.getTime() + waitTimeMs).toISOString();
const previousStatus = statusCache.providers[providerId];
@@ -173,42 +189,39 @@ export function createProviderStatusService(config = {}) {
statusCache.providers[providerId] = {
available: false,
- reason: 'usage-limit',
- message: errorInfo.message || 'Usage limit exceeded',
- waitTime: errorInfo.waitTime || null,
+ reason,
+ message,
unavailableSince: now.toISOString(),
estimatedRecovery,
failureCount,
- lastChecked: now.toISOString()
+ lastChecked: now.toISOString(),
+ ...(extras && typeof extras === 'object' ? extras : {})
};
await saveStatus(statusCache);
- emitStatusChange(providerId, statusCache.providers[providerId], 'usage-limit');
+ emitStatusChange(providerId, statusCache.providers[providerId], reason);
return statusCache.providers[providerId];
},
- async markRateLimited(providerId) {
- const now = new Date();
- const estimatedRecovery = new Date(now.getTime() + defaultRateLimitWait).toISOString();
-
- const previousStatus = statusCache.providers[providerId];
- const failureCount = (previousStatus?.failureCount || 0) + 1;
+ async markUsageLimit(providerId, errorInfo = {}) {
+ return this.markUnavailable(providerId, {
+ reason: 'usage-limit',
+ message: errorInfo.message || 'Usage limit exceeded',
+ waitTimeMs: parseWaitTime(errorInfo.waitTime) || defaultUsageLimitWait,
+ // `waitTime` is a usage-limit-only display string ("resets 5pm") —
+ // pass via extras so it's part of the SAME persisted record and
+ // status:changed event, not a follow-up second write.
+ extras: errorInfo.waitTime ? { waitTime: errorInfo.waitTime } : null
+ });
+ },
- statusCache.providers[providerId] = {
- available: false,
+ async markRateLimited(providerId) {
+ return this.markUnavailable(providerId, {
reason: 'rate-limit',
message: 'Rate limit exceeded - temporary',
- unavailableSince: now.toISOString(),
- estimatedRecovery,
- failureCount,
- lastChecked: now.toISOString()
- };
-
- await saveStatus(statusCache);
- emitStatusChange(providerId, statusCache.providers[providerId], 'rate-limit');
-
- return statusCache.providers[providerId];
+ waitTimeMs: defaultRateLimitWait
+ });
},
async markAvailable(providerId) {
@@ -235,7 +248,11 @@ export function createProviderStatusService(config = {}) {
}
const primaryProvider = providers[primaryProviderId];
- if (primaryProvider?.fallbackProvider) {
+ // Guard against `fallbackProvider === self` — a misconfigured provider
+ // would otherwise loop back to itself and silently retry the same
+ // broken endpoint. The system priority loop already excludes
+ // primaryProviderId; the configured-fallback path needs its own check.
+ if (primaryProvider?.fallbackProvider && primaryProvider.fallbackProvider !== primaryProviderId) {
const configuredFallback = providers[primaryProvider.fallbackProvider];
if (configuredFallback?.enabled && this.isAvailable(configuredFallback.id)) {
return { provider: configuredFallback, source: 'provider' };
diff --git a/server/lib/aiToolkit/providerStatus.test.js b/server/lib/aiToolkit/providerStatus.test.js
index 72e5119d66..5d57896794 100644
--- a/server/lib/aiToolkit/providerStatus.test.js
+++ b/server/lib/aiToolkit/providerStatus.test.js
@@ -87,6 +87,77 @@ describe('Provider Status Service', () => {
});
});
+ describe('markUnavailable (generic)', () => {
+ it('marks a provider unavailable with an arbitrary reason and explicit waitTimeMs', async () => {
+ const status = await statusService.markUnavailable('test-provider', {
+ reason: 'network-error',
+ message: 'ECONNREFUSED to upstream',
+ waitTimeMs: 120000,
+ });
+
+ expect(status.available).toBe(false);
+ expect(status.reason).toBe('network-error');
+ expect(status.message).toBe('ECONNREFUSED to upstream');
+ const recoveryMs = new Date(status.estimatedRecovery).getTime() - Date.now();
+ // Cooldown ~= 120s (allow a small jitter for clock drift in CI).
+ expect(recoveryMs).toBeGreaterThan(110000);
+ expect(recoveryMs).toBeLessThanOrEqual(120000);
+ });
+
+ it('uses defaultRateLimitWait when no cooldown is supplied', async () => {
+ const status = await statusService.markUnavailable('test-provider', {
+ reason: 'unknown',
+ message: 'mystery failure',
+ });
+
+ const recoveryMs = new Date(status.estimatedRecovery).getTime() - Date.now();
+ // Test setup configures defaultRateLimitWait=500ms — within tolerance.
+ expect(recoveryMs).toBeGreaterThan(0);
+ expect(recoveryMs).toBeLessThanOrEqual(500);
+ });
+
+ it('emits status:changed with the reason as the event type', async () => {
+ const handler = vi.fn();
+ statusService.events.on('status:changed', handler);
+ await statusService.markUnavailable('test-provider', {
+ reason: 'network-error',
+ message: 'down',
+ waitTimeMs: 30000,
+ });
+ expect(handler).toHaveBeenCalledWith({
+ providerId: 'test-provider',
+ status: expect.objectContaining({ available: false, reason: 'network-error' }),
+ type: 'network-error',
+ });
+ });
+ });
+
+ describe('markUsageLimit — single emit with extras', () => {
+ it('includes waitTime in the status:changed event payload on the first emit', async () => {
+ // Regression: previously markUsageLimit did a second saveStatus after
+ // markUnavailable to stamp waitTime, so status:changed fired without
+ // the waitTime field — leaving Socket.IO clients with an incomplete
+ // usage-limit record until the second write landed.
+ const handler = vi.fn();
+ statusService.events.on('status:changed', handler);
+
+ await statusService.markUsageLimit('test-provider', {
+ message: 'Usage limit exceeded',
+ waitTime: '5 hours'
+ });
+
+ // Exactly one status:changed for the markUsageLimit call, and it
+ // already carries waitTime — no second emit needed.
+ const usageLimitCalls = handler.mock.calls.filter(c => c[0].type === 'usage-limit');
+ expect(usageLimitCalls).toHaveLength(1);
+ expect(usageLimitCalls[0][0].status).toMatchObject({
+ available: false,
+ reason: 'usage-limit',
+ waitTime: '5 hours',
+ });
+ });
+ });
+
describe('markRateLimited', () => {
it('should mark provider as rate limited', async () => {
const status = await statusService.markRateLimited('test-provider');
@@ -202,6 +273,20 @@ describe('Provider Status Service', () => {
expect(result.source).toBe('system');
});
+ it('should NOT loop back to the same provider when fallbackProvider points at self (misconfig guard)', () => {
+ const selfFallback = {
+ 'self-pointer': { id: 'self-pointer', enabled: true, fallbackProvider: 'self-pointer' },
+ 'fallback-provider-1': { id: 'fallback-provider-1', enabled: true },
+ };
+
+ const result = statusService.getFallbackProvider('self-pointer', selfFallback);
+
+ // Must fall through to the system priority list (which excludes the
+ // primary by id) rather than returning self.
+ expect(result?.provider.id).toBe('fallback-provider-1');
+ expect(result?.source).toBe('system');
+ });
+
it('should return null if no fallback available', async () => {
await statusService.markUsageLimit('configured-fallback', { message: 'Limit hit' });
await statusService.markUsageLimit('fallback-provider-1', { message: 'Limit hit' });
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index b561813fe1..fb4f64d52e 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -27,14 +27,49 @@
*/
import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag, stopRun, patchRunMetadata } from '../services/runner.js';
-import { getActiveProvider, getProviderById } from '../services/providers.js';
+import { getActiveProvider, getProviderById, getAllProviders } from '../services/providers.js';
import { executeTuiRun } from './tuiPromptRunner.js';
import { ServerError } from './errorHandler.js';
import { PROVIDER_TYPES } from './aiToolkit/constants.js';
+import { analyzeError, ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';
+import { getAIToolkitInstance } from './aiToolkitState.js';
+
+// noteFallbackHandled lives in services/autoFixer.js, which transitively
+// pulls in services/cos.js (PM2 + fs + sockets). Importing it lazily on
+// the failure path keeps anything that imports promptRunner.js from
+// dragging the CoS stack along on the happy path. Node caches the module
+// after the first dynamic import, so the cost is one-time.
+async function loadNoteFallbackHandled() {
+ const mod = await import('../services/autoFixer.js');
+ return mod.noteFallbackHandled;
+}
export const DEFAULT_TIMEOUT_MS = 300000;
const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));
+// Cooldown per error category — how long the failed provider is marked
+// unavailable so subsequent calls skip it and proactively use the fallback.
+// USAGE_LIMIT is absent because `markUsageLimit` parses the wait time
+// from the error body (e.g. "resets 5pm"). Values target the timescale
+// the user can plausibly recover the underlying cause:
+// RATE_LIMIT — 5m: provider-side counter typically clears in minutes
+// AUTH_ERROR — 15m: usually a config issue that needs human action
+// MODEL_NOT_FOUND — 30m: also config; longer because retry is unlikely
+// QUOTA_EXCEEDED — 60m: billing/credits; retry sooner is futile
+// NETWORK_ERROR — 2m: usually a transient hiccup
+// TIMEOUT/UNKNOWN — 1m: short enough to retry, long enough to skip
+// while the immediate workload retries via fallback
+const COOLDOWN_MS_BY_CATEGORY = {
+ [ERROR_CATEGORIES.RATE_LIMIT]: 5 * 60 * 1000,
+ [ERROR_CATEGORIES.AUTH_ERROR]: 15 * 60 * 1000,
+ [ERROR_CATEGORIES.MODEL_NOT_FOUND]: 30 * 60 * 1000,
+ [ERROR_CATEGORIES.QUOTA_EXCEEDED]: 60 * 60 * 1000,
+ [ERROR_CATEGORIES.NETWORK_ERROR]: 2 * 60 * 1000,
+ [ERROR_CATEGORIES.TIMEOUT]: 60 * 1000,
+ [ERROR_CATEGORIES.UNKNOWN]: 60 * 1000,
+};
+const DEFAULT_COOLDOWN_MS = 60 * 1000;
+
/**
* Returns true when the runner+provider pair will actually honor a
* per-call `model` override. For API providers the model is a
@@ -161,31 +196,199 @@ export function assertProvider(provider, { message, code, status = 503 } = {}) {
* must pass this — without it, the CLI/TUI spawn lands in PortOS's own
* cwd and the analysis runs against the wrong files. No-op for API
* providers (no spawn).
- * @returns {Promise<{ text: string, runId: string, model: string|null }>}
+ * @returns {Promise<{ text: string, runId: string, model: string|null, usedFallback?: boolean, fallbackFrom?: { id: string, name: string } }>}
* — `model` is the resolved model that actually executed (null when
- * neither override nor provider.defaultModel applies).
+ * neither override nor provider.defaultModel applies). `usedFallback`
+ * and `fallbackFrom` are present only when the primary failed and the
+ * retry path recovered via a configured fallback; callers that care
+ * about provider attribution should branch on `usedFallback` to know
+ * whether `model` belongs to the requested primary or the fallback.
*/
-export async function runPromptThroughProvider({ provider, prompt, source, model, runId: callerRunId, onData: onDataCallback, timeout: timeoutOverride, cwd: cwdOverride }) {
+export async function runPromptThroughProvider(args) {
// Validate inputs up front so an accidentally-null `provider` (or one
// missing `id`/`type`) surfaces a clear error here instead of throwing
// a downstream TypeError on `provider.id` inside createRun or on the
// provider.type dispatch below.
- if (!provider || typeof provider !== 'object') {
+ if (!args?.provider || typeof args.provider !== 'object') {
throw new Error('runPromptThroughProvider: provider is required');
}
- if (typeof provider.id !== 'string' || !provider.id) {
+ if (typeof args.provider.id !== 'string' || !args.provider.id) {
throw new Error('runPromptThroughProvider: provider.id must be a non-empty string');
}
- if (provider.type !== PROVIDER_TYPES.CLI && provider.type !== PROVIDER_TYPES.API && provider.type !== PROVIDER_TYPES.TUI) {
- throw new Error(`Unsupported provider type: ${provider.type}`);
+ if (args.provider.type !== PROVIDER_TYPES.CLI && args.provider.type !== PROVIDER_TYPES.API && args.provider.type !== PROVIDER_TYPES.TUI) {
+ throw new Error(`Unsupported provider type: ${args.provider.type}`);
}
- if (typeof prompt !== 'string' || !prompt.length) {
+ if (typeof args.prompt !== 'string' || !args.prompt.length) {
throw new Error('runPromptThroughProvider: prompt must be a non-empty string');
}
- if (typeof source !== 'string' || !source.length) {
+ if (typeof args.source !== 'string' || !args.source.length) {
throw new Error('runPromptThroughProvider: source must be a non-empty string');
}
+ try {
+ return await executeProviderRunOnce(args);
+ } catch (firstError) {
+ // Only retry when the failure came from the execution layer (annotated
+ // by safeReject with effectiveProvider). Pre-execution throws —
+ // createRun rejecting on a disk error / disabled provider / unsupported
+ // type — never fire the AI_PROVIDER_EXECUTION_FAILED hook, so there's
+ // no deferred investigation task to suppress and marking the provider
+ // unavailable would punish it for a disk/config problem. Rethrow
+ // those as-is so the caller sees the original error.
+ if (!firstError?.effectiveProvider) {
+ throw stripFallbackContext(firstError);
+ }
+
+ // The runner already wrote a failed metadata.json and the onRunFailed
+ // hook in server/index.js queued a deferred investigation task. If a
+ // fallback is configured + available, mark the failed provider
+ // unavailable so subsequent calls skip it, then retry once. No
+ // fallback ⇒ let the queued investigation task fire.
+ //
+ // `failed` is the provider that ACTUALLY ran — usually equals
+ // args.provider, but createRun may have proactively swapped to a
+ // different fallback if the requested primary was already marked
+ // unavailable. Always dedupe against what actually ran so
+ // `noteFallbackHandled` cancels the right queued task.
+ const failed = firstError.effectiveProvider;
+ const failedModel = firstError.effectiveModel || resolveEffectiveModel(failed, args.model);
+ const fallback = await pickFallbackProvider(failed);
+ if (!fallback) {
+ throw stripFallbackContext(firstError);
+ }
+
+ await markProviderUnavailableFromError(failed, firstError.message).catch(err => {
+ console.error(`❌ markUnavailable failed for ${failed.id}: ${err.message}`);
+ });
+
+ console.log(`⚡ Retrying ${args.source} with fallback ${fallback.name} (primary ${failed.name} failed: ${firstError.message})`);
+
+ // Run the fallback as a fresh attempt — explicit `model: undefined`
+ // so the fallback picks its own default rather than inheriting the
+ // primary's model id (which usually doesn't exist on the fallback).
+ let fallbackResult;
+ try {
+ fallbackResult = await executeProviderRunOnce({
+ ...args,
+ provider: fallback,
+ model: undefined,
+ runId: undefined, // fresh runId so the failed primary's record stays intact
+ });
+ } catch (fallbackError) {
+ // Both failed — let both deferred tasks fire and rethrow.
+ throw stripFallbackContext(fallbackError);
+ }
+
+ // Fallback succeeded — cancel the queued investigation task that fired
+ // for the provider that actually failed, so the user doesn't see a
+ // noisy "investigate" entry in their plan for a failure that was
+ // auto-recovered. Keys must match what server/index.js's onRunFailed
+ // hook published (metadata.providerName + metadata.model).
+ //
+ // Best-effort: a failure to load the autoFixer module or in the
+ // suppress call itself must not turn a successful fallback run into
+ // a user-visible error. The worst case is a stale investigation
+ // task in the user's plan — the actual result still flows through.
+ try {
+ const noteFallbackHandled = await loadNoteFallbackHandled();
+ noteFallbackHandled({
+ provider: failed.name || failed.id,
+ model: failedModel,
+ });
+ } catch (suppressErr) {
+ console.error(`❌ noteFallbackHandled failed (investigation task not suppressed): ${suppressErr.message}`);
+ }
+
+ return {
+ ...fallbackResult,
+ usedFallback: true,
+ fallbackFrom: { id: failed.id, name: failed.name },
+ };
+ }
+}
+
+/**
+ * Pick a fallback provider for `failed`. Honors the failed provider's
+ * `fallbackProvider` field first, then the toolkit's system priority
+ * list. Returns null when no usable fallback exists.
+ *
+ * The toolkit's `getFallbackProvider` reads `providers[failed.id]` to
+ * look up the `fallbackProvider` field, so the primary MUST stay in the
+ * map. Self-loop protection (`fallbackProvider === self`) lives in
+ * `getFallbackProvider`; the system priority loop already excludes
+ * `failed.id` by construction.
+ */
+async function pickFallbackProvider(failed) {
+ const toolkit = getAIToolkitInstance();
+ const providerStatus = toolkit?.services?.providerStatus;
+ if (!providerStatus) return null;
+
+ const all = await getAllProviders().catch(() => null);
+ if (!all?.providers) return null;
+ const providersMap = {};
+ for (const p of all.providers) providersMap[p.id] = p;
+
+ const picked = providerStatus.getFallbackProvider(failed.id, providersMap);
+ return picked?.provider || null;
+}
+
+/**
+ * Translate the runner's failure into an availability marker on the
+ * failed provider. Uses analyzeError to categorize and pick a cooldown;
+ * usage-limit failures route through `markUsageLimit` so the parsed
+ * wait time (e.g. "reset 5pm") is honored.
+ *
+ * Skips the mark when the toolkit's `executeApiRun` has already marked
+ * the provider unavailable inline (it does this for RATE_LIMIT and
+ * USAGE_LIMIT before firing onComplete) — re-marking would double-
+ * increment `failureCount` and re-write the status file for no gain.
+ */
+async function markProviderUnavailableFromError(failed, errorMessage) {
+ const toolkit = getAIToolkitInstance();
+ const providerStatus = toolkit?.services?.providerStatus;
+ if (!providerStatus) return;
+ if (!providerStatus.isAvailable(failed.id)) return;
+
+ const analysis = analyzeError(errorMessage || '');
+ const category = analysis?.category || ERROR_CATEGORIES.UNKNOWN;
+
+ if (category === ERROR_CATEGORIES.USAGE_LIMIT) {
+ await providerStatus.markUsageLimit(failed.id, {
+ message: analysis.message || errorMessage,
+ waitTime: analysis.waitTime,
+ });
+ return;
+ }
+
+ const waitTimeMs = COOLDOWN_MS_BY_CATEGORY[category] ?? DEFAULT_COOLDOWN_MS;
+ await providerStatus.markUnavailable(failed.id, {
+ reason: category,
+ message: analysis?.message || errorMessage || `Provider ${failed.name || failed.id} failed`,
+ waitTimeMs,
+ });
+}
+
+// Strip the fallback-context fields off an error before rethrowing so
+// callers don't see internal metadata they didn't ask for. The
+// `.effectiveProvider`/`.effectiveModel` annotations exist solely for
+// runPromptThroughProvider's retry path.
+function stripFallbackContext(err) {
+ if (err && typeof err === 'object') {
+ delete err.effectiveProvider;
+ delete err.effectiveModel;
+ }
+ return err;
+}
+
+/**
+ * Inner helper: execute one attempt against `args.provider`. Returns
+ * { text, runId, model } on success. On failure, throws an Error with
+ * `effectiveProvider` and `effectiveModel` attached so the retry path
+ * knows which provider actually ran (createRun may have proactively
+ * swapped to a fallback when the requested provider was already marked
+ * unavailable).
+ */
+async function executeProviderRunOnce({ provider, prompt, source, model, runId: callerRunId, onData: onDataCallback, timeout: timeoutOverride, cwd: cwdOverride }) {
// Resolve the model that'll actually run BEFORE creating the run record
// so the record reflects reality. resolveEffectiveModel handles both
// the override-honored fallback chain AND the args-baked-CLI case
@@ -227,9 +430,11 @@ export async function runPromptThroughProvider({ provider, prompt, source, model
// createRun persisted `metadata.model = effectiveModel || provider.defaultModel`
// using the ORIGINAL provider's resolved value — so /runs would
// attribute a model that doesn't belong to the fallback (e.g. an
- // API model id recorded on a CLI fallback). Patch the record so
- // attribution matches what actually executes.
- patchRunMetadata(runId, {
+ // API model id recorded on a CLI fallback). Await the patch so a
+ // fast-failing run can't fire onRunFailed with stale model/provider
+ // info — `noteFallbackHandled` keys on metadata.providerName +
+ // metadata.model and would miss if the patch hadn't landed yet.
+ await patchRunMetadata(runId, {
model: effectiveModel,
providerId: effectiveProvider.id,
providerName: effectiveProvider.name,
@@ -251,7 +456,20 @@ export async function runPromptThroughProvider({ provider, prompt, source, model
let apiTimeoutHandle = null;
const safeResolve = (value) => { if (!settled) { settled = true; if (apiTimeoutHandle) clearTimeout(apiTimeoutHandle); resolve(value); } };
- const safeReject = (err) => { if (!settled) { settled = true; if (apiTimeoutHandle) clearTimeout(apiTimeoutHandle); reject(err); } };
+ const safeReject = (err) => {
+ if (settled) return;
+ settled = true;
+ if (apiTimeoutHandle) clearTimeout(apiTimeoutHandle);
+ // Annotate so runPromptThroughProvider's retry path knows which
+ // provider actually ran (createRun may have swapped to a fallback
+ // before this attempt) and which model is the dedupe key for
+ // suppressing the queued investigation task on a successful retry.
+ if (err && typeof err === 'object') {
+ err.effectiveProvider = effectiveProvider;
+ err.effectiveModel = effectiveModel;
+ }
+ reject(err);
+ };
// TUI runs discard `text` and use `result.text` from executeTuiRun (see
// onComplete below), so the per-chunk APPEND_CHUNK concat is pure waste —
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index 3555ad585e..fd5344b8c5 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -10,6 +10,11 @@ vi.mock('../services/runner.js', () => ({
// without this mock, the timer firing would TypeError on `stopRun is
// not a function` and crash any test that triggers the API timeout.
stopRun: vi.fn().mockResolvedValue(undefined),
+ // Called best-effort by promptRunner.js when createRun proactively
+ // swapped to a fallback provider — the metadata patch updates the
+ // run record's providerId/model so /runs attribution matches what
+ // actually ran. Mocked as a no-op resolve.
+ patchRunMetadata: vi.fn().mockResolvedValue(undefined),
}));
// TUI runner is in lib (different module from services/runner.js) — mock it
@@ -24,15 +29,36 @@ vi.mock('./tuiPromptRunner.js', () => ({
// providers.js is a compatibility shim that throws when the toolkit hasn't
// been initialized via setAIToolkit(). Mock it so the resolveProviderAndModel
-// tests can drive the active/by-id lookups directly.
+// tests can drive the active/by-id lookups directly. `getAllProviders` is
+// mocked too so the retry-with-fallback path (which enumerates providers to
+// look up the configured fallback) can be driven directly from tests.
vi.mock('../services/providers.js', () => ({
getActiveProvider: vi.fn(),
getProviderById: vi.fn(),
+ getAllProviders: vi.fn().mockResolvedValue({ activeProvider: null, providers: [] }),
+}));
+
+// autoFixer.js is called from runPromptThroughProvider on a successful
+// fallback retry to cancel the deferred investigation task. Mock the export
+// to a spy so tests can assert it was/wasn't invoked without wiring up the
+// full task system.
+vi.mock('../services/autoFixer.js', () => ({
+ noteFallbackHandled: vi.fn(),
+}));
+
+// aiToolkitState lookups gate the retry path on a real providerStatus
+// service being present. By default the mock returns null so the retry
+// short-circuits and the original error is rethrown — individual tests
+// override the return value to enable the retry branch.
+vi.mock('./aiToolkitState.js', () => ({
+ getAIToolkitInstance: vi.fn().mockReturnValue(null),
}));
const runner = await import('../services/runner.js');
const tuiRunner = await import('./tuiPromptRunner.js');
const providers = await import('../services/providers.js');
+const autoFixer = await import('../services/autoFixer.js');
+const toolkitState = await import('./aiToolkitState.js');
const { runPromptThroughProvider, resolveProviderAndModel } = await import('./promptRunner.js');
const apiProvider = (extra = {}) => ({
@@ -55,6 +81,9 @@ beforeEach(() => {
// the next test's resolveEffectiveModel run.
runner.hasModelFlag.mockReturnValue(false);
runner.extractBakedModel.mockReturnValue(null);
+ // Defaults reset for fallback-path mocks too — same staleness concern.
+ providers.getAllProviders.mockResolvedValue({ activeProvider: null, providers: [] });
+ toolkitState.getAIToolkitInstance.mockReturnValue(null);
});
describe('promptRunner — happy paths', () => {
@@ -549,6 +578,350 @@ describe('promptRunner — API timeout enforcement', () => {
});
});
+// =============================================================================
+// Retry-with-fallback — when a run fails and a fallback provider is
+// available, swap to it transparently instead of letting the failure
+// queue an "Investigate AI provider failure" task. Regression guard for
+// the issue where LM Studio / Claude Code CLI failures used to create
+// noisy plan tasks even with a configured fallback.
+// =============================================================================
+
+describe('promptRunner — retry-with-fallback', () => {
+ // Reuse the top-level factories so the retry tests pick up future
+ // changes to the canonical provider shapes — only overriding fields
+ // these tests assert on (id + name, since noteFallbackHandled keys on
+ // the display name).
+ const fallbackApi = apiProvider({ id: 'fallback-api', name: 'Fallback API', defaultModel: 'fb-model' });
+ const primaryCli = cliProvider({ id: 'primary-cli', name: 'Primary CLI', defaultModel: 'primary-model' });
+ const primaryApi = apiProvider({ id: 'primary-api', name: 'Primary API', defaultModel: 'primary-model' });
+
+ function mockToolkitWithFallback(fallback = fallbackApi) {
+ // isAvailable returns true so promptRunner's "skip if toolkit already
+ // marked it" gate doesn't short-circuit the mark in these tests.
+ const isAvailable = vi.fn().mockReturnValue(true);
+ const markUnavailable = vi.fn().mockResolvedValue(undefined);
+ const markUsageLimit = vi.fn().mockResolvedValue(undefined);
+ const getFallbackProvider = vi.fn().mockReturnValue(
+ fallback ? { provider: fallback, source: 'provider' } : null
+ );
+ toolkitState.getAIToolkitInstance.mockReturnValue({
+ services: { providerStatus: { isAvailable, markUnavailable, markUsageLimit, getFallbackProvider } },
+ });
+ providers.getAllProviders.mockResolvedValue({
+ activeProvider: null,
+ providers: fallback ? [primaryCli, primaryApi, fallback] : [primaryCli, primaryApi],
+ });
+ return { isAvailable, markUnavailable, markUsageLimit, getFallbackProvider };
+ }
+
+ it('retries with the configured fallback and resolves with usedFallback flag when primary CLI fails', async () => {
+ const status = mockToolkitWithFallback();
+
+ // First call: primary CLI fails. Second call: fallback API succeeds.
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: 'Process exited with code 1' });
+ });
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('fallback content');
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ });
+
+ expect(out.text).toBe('fallback content');
+ expect(out.usedFallback).toBe(true);
+ expect(out.fallbackFrom).toEqual({ id: 'primary-cli', name: 'Primary CLI' });
+
+ // Primary was marked unavailable before retry; fallback was looked up
+ // and used; the deferred autoFixer task was cancelled.
+ expect(status.markUnavailable).toHaveBeenCalledWith('primary-cli', expect.objectContaining({
+ reason: expect.any(String),
+ }));
+ expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-cli', expect.any(Object));
+ expect(autoFixer.noteFallbackHandled).toHaveBeenCalledWith({
+ provider: 'Primary CLI',
+ model: 'primary-model',
+ });
+ });
+
+ it('retries with fallback when primary API fails', async () => {
+ mockToolkitWithFallback();
+
+ let calls = 0;
+ runner.executeApiRun.mockImplementation(async (id, providerArg, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ calls += 1;
+ if (providerArg.id === 'primary-api') {
+ onComplete({ success: false, error: 'upstream 500' });
+ } else {
+ onData('recovered');
+ onComplete({ success: true });
+ }
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: primaryApi,
+ prompt: 'p',
+ source: 'test',
+ });
+
+ expect(calls).toBe(2);
+ expect(out.text).toBe('recovered');
+ expect(out.usedFallback).toBe(true);
+ expect(autoFixer.noteFallbackHandled).toHaveBeenCalledTimes(1);
+ });
+
+ it('does NOT suppress the investigation task when the fallback ALSO fails (both errors must surface)', async () => {
+ mockToolkitWithFallback();
+
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: 'primary boom' });
+ });
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, _onData, onComplete) => {
+ onComplete({ success: false, error: 'fallback also boom' });
+ });
+
+ await expect(runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ })).rejects.toThrow(/fallback also boom/);
+
+ // noteFallbackHandled is reserved for SUCCESSFUL fallback — when both
+ // fail the user must see both deferred investigation tasks fire.
+ expect(autoFixer.noteFallbackHandled).not.toHaveBeenCalled();
+ });
+
+ it('rethrows the original error when no fallback is available', async () => {
+ mockToolkitWithFallback(null);
+
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: 'no recovery path' });
+ });
+
+ await expect(runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ })).rejects.toThrow(/no recovery path/);
+
+ expect(runner.executeApiRun).not.toHaveBeenCalled();
+ expect(autoFixer.noteFallbackHandled).not.toHaveBeenCalled();
+ });
+
+ it('rethrows when toolkit/providerStatus is not initialized (no retry path possible)', async () => {
+ // Default mock returns null toolkit — no retry attempted.
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: 'init not ready' });
+ });
+
+ await expect(runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ })).rejects.toThrow(/init not ready/);
+
+ expect(autoFixer.noteFallbackHandled).not.toHaveBeenCalled();
+ });
+
+ it('strips internal effectiveProvider/effectiveModel annotations from rethrown errors', async () => {
+ // No fallback → original error rethrown. The annotation fields are
+ // implementation-detail-only and should never leak to callers.
+ mockToolkitWithFallback(null);
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: 'plain failure' });
+ });
+
+ try {
+ await runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ });
+ throw new Error('should have rejected');
+ } catch (err) {
+ expect(err.message).toMatch(/plain failure/);
+ expect(err.effectiveProvider).toBeUndefined();
+ expect(err.effectiveModel).toBeUndefined();
+ }
+ });
+
+ it('skips re-marking when the toolkit already marked the provider unavailable (prevents double failureCount)', async () => {
+ const status = mockToolkitWithFallback();
+ // Simulate the toolkit's executeApiRun having already called markUsageLimit
+ // before onComplete fired — providerStatus.isAvailable now returns false.
+ status.isAvailable.mockReturnValue(false);
+
+ runner.executeApiRun.mockImplementation(async (id, providerArg, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ if (providerArg.id === 'primary-api') {
+ onComplete({ success: false, error: 'rate limit hit' });
+ } else {
+ onData('recovered');
+ onComplete({ success: true });
+ }
+ });
+
+ await runPromptThroughProvider({
+ provider: primaryApi,
+ prompt: 'p',
+ source: 'test',
+ });
+
+ // Fallback still ran; investigation task still suppressed; but neither
+ // markUnavailable nor markUsageLimit was called from promptRunner
+ // because the toolkit's runner already marked it.
+ expect(status.markUnavailable).not.toHaveBeenCalled();
+ expect(status.markUsageLimit).not.toHaveBeenCalled();
+ expect(autoFixer.noteFallbackHandled).toHaveBeenCalledTimes(1);
+ });
+
+ it('keys noteFallbackHandled to the provider that actually ran (not the caller-intended one) when createRun proactively swapped', async () => {
+ // Setup: caller asks for primary-cli, but createRun has proactively
+ // swapped to a different intermediate fallback (mockedFallback in
+ // runResult.provider) because primary-cli was already marked unavailable.
+ // That intermediate then fails; promptRunner's catch retries with yet
+ // another fallback. The cancelled-task key MUST match the intermediate
+ // (what server's onRunFailed actually published) — not the caller's
+ // original primary-cli.
+ const intermediate = cliProvider({ id: 'intermediate-cli', name: 'Intermediate CLI', defaultModel: 'intermediate-model' });
+ const finalFallback = apiProvider({ id: 'final-api', name: 'Final API', defaultModel: 'final-model' });
+
+ const status = mockToolkitWithFallback(finalFallback);
+ // Simulate createRun's proactive swap: runner.createRun returns the
+ // intermediate provider rather than the caller-passed primary.
+ runner.createRun.mockResolvedValueOnce({
+ runId: 'run-via-intermediate',
+ provider: intermediate,
+ });
+
+ runner.executeCliRun.mockImplementation(async (id, providerArg, _p, _cwd, _onData, onComplete, _t) => {
+ // Intermediate fails on first attempt.
+ onComplete({ success: false, error: `intermediate boom (${providerArg.id})` });
+ });
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('recovered via final');
+ onComplete({ success: true });
+ });
+
+ await runPromptThroughProvider({
+ provider: primaryCli, // caller-intended primary
+ prompt: 'p',
+ source: 'test',
+ });
+
+ // The deferred task in autoFixer is keyed off the provider that
+ // ACTUALLY failed (intermediate), so noteFallbackHandled must use that
+ // — not the caller-intended primary-cli.
+ expect(autoFixer.noteFallbackHandled).toHaveBeenCalledWith({
+ provider: 'Intermediate CLI',
+ model: 'intermediate-model',
+ });
+ // markUnavailable likewise applies to the failed intermediate, not
+ // the primary the caller asked for.
+ expect(status.markUnavailable).toHaveBeenCalledWith('intermediate-cli', expect.any(Object));
+ });
+
+ it('rethrows pre-execution failures (e.g. createRun throwing) without retry — there is no investigation task to suppress', async () => {
+ const status = mockToolkitWithFallback();
+ // createRun throws before any execution happens (disk error, disabled
+ // provider, etc.). No onRunFailed event will fire, so no deferred
+ // investigation task exists. The retry path must NOT engage.
+ runner.createRun.mockRejectedValueOnce(new Error('Provider is disabled'));
+
+ await expect(runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ })).rejects.toThrow(/Provider is disabled/);
+
+ expect(runner.executeCliRun).not.toHaveBeenCalled();
+ expect(runner.executeApiRun).not.toHaveBeenCalled();
+ expect(status.markUnavailable).not.toHaveBeenCalled();
+ expect(status.markUsageLimit).not.toHaveBeenCalled();
+ expect(autoFixer.noteFallbackHandled).not.toHaveBeenCalled();
+ });
+
+ it('keeps the failed primary in the providersMap so provider-level fallbackProvider can be looked up', async () => {
+ // Regression: an earlier attempt at the self-fallback guard removed
+ // the primary from the providersMap, which broke provider-level
+ // fallback selection — getFallbackProvider needs the primary entry
+ // to read its `fallbackProvider` field. The guard against
+ // `fallbackProvider === self` now lives in getFallbackProvider; this
+ // test pins the call-site contract that the primary stays in the map.
+ const status = mockToolkitWithFallback();
+
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: 'primary boom' });
+ });
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('recovered');
+ onComplete({ success: true });
+ });
+
+ await runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ });
+
+ // The map passed to getFallbackProvider must contain the failed
+ // primary so provider-level fallbackProvider can be read from it.
+ const mapPassed = status.getFallbackProvider.mock.calls[0][1];
+ expect(mapPassed).toHaveProperty('primary-cli');
+ });
+
+ it('does not turn a successful fallback into a failure when noteFallbackHandled itself throws (best-effort suppression)', async () => {
+ mockToolkitWithFallback();
+ autoFixer.noteFallbackHandled.mockImplementation(() => {
+ throw new Error('autoFixer is offline');
+ });
+
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: 'primary boom' });
+ });
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('still works');
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ });
+
+ // Fallback ran and returned its result — the suppression failure was
+ // logged but did not surface as a rejection.
+ expect(out.text).toBe('still works');
+ expect(out.usedFallback).toBe(true);
+ });
+
+ it('routes USAGE_LIMIT failures through markUsageLimit (parses wait time)', async () => {
+ const status = mockToolkitWithFallback();
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: "You've hit your usage limit. Try again in 5 hours" });
+ });
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('recovered');
+ onComplete({ success: true });
+ });
+
+ await runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ });
+
+ expect(status.markUsageLimit).toHaveBeenCalledWith('primary-cli', expect.objectContaining({
+ waitTime: expect.any(String),
+ }));
+ expect(status.markUnavailable).not.toHaveBeenCalled();
+ });
+});
+
describe('resolveProviderAndModel', () => {
beforeEach(() => {
providers.getActiveProvider.mockReset();
diff --git a/server/services/autoFixer.js b/server/services/autoFixer.js
index 43ff8d2e31..be696a0c2f 100644
--- a/server/services/autoFixer.js
+++ b/server/services/autoFixer.js
@@ -12,9 +12,58 @@ import { errorEvents } from '../lib/errorHandler.js';
const recentErrors = new Map();
const ERROR_DEDUPE_WINDOW = 60000; // 1 minute
+// Defer task creation so an in-flight fallback retry (driven by
+// promptRunner.js) has a chance to handle the failure first. If
+// `noteFallbackHandled(provider, model)` fires within the window we cancel
+// the task — the user got a result via fallback and shouldn't see noise in
+// their plan. 5s covers the common case where the fallback is a fast API
+// (claude-code, codex) responding within seconds; a slower fallback whose
+// retry exceeds this window will produce both a result AND an investigation
+// task, which is acceptable (the user sees what failed and what recovered).
+const TASK_DEFER_MS = 5000;
+// Invariant: every path that removes a timer here MUST also delete the
+// matching map entry (the setTimeout callback, noteFallbackHandled, and
+// _resetAutoFixerForTests all uphold this) — otherwise the map grows
+// unbounded across the lifetime of the process.
+const deferredTasks = new Map(); // errorKey -> { timer }
+
// Store pending tasks when CoS is not running (for later pickup)
const pendingAutoFixTasks = [];
+function aiProviderErrorKey(providerName, model) {
+ // NUL separator: provider names ("Claude Code CLI") and model ids
+ // ("gpt-4o-mini") both commonly contain `-`, so a `-`-joined key would
+ // collide for pairs like ("gpt-4o", "mini") vs ("gpt", "4o-mini") and
+ // silently dedupe distinct failures together. NUL never appears in
+ // legitimate provider/model identifiers, so the key is unambiguous.
+ return `AI_PROVIDER_EXECUTION_FAILED\x00${providerName}\x00${model}`;
+}
+
+/**
+ * Cancel a deferred investigation task for `provider`/`model` because a
+ * fallback retry succeeded. Called from `runPromptThroughProvider` after
+ * a successful fallback — the user got their result, so the queued task
+ * would be noise. Also clears the dedupe entry so a *future* failure of
+ * the same provider can still raise a task (otherwise the dedupe window
+ * would silently suppress real failures for up to 60s).
+ *
+ * `provider` matches `ctx.provider` (the provider's display name, not id)
+ * because that's what the failure event payload uses — see the
+ * `onRunFailed` hook in server/index.js.
+ */
+export function noteFallbackHandled({ provider, model }) {
+ const errorKey = aiProviderErrorKey(provider, model);
+ const pending = deferredTasks.get(errorKey);
+ if (pending) {
+ clearTimeout(pending.timer);
+ deferredTasks.delete(errorKey);
+ recentErrors.delete(errorKey);
+ console.log(`✅ Suppressed investigation task: fallback handled failure for ${provider} (${model})`);
+ return true;
+ }
+ return false;
+}
+
/**
* Check if an error is a duplicate within the dedupe window
* Also cleans up expired entries
@@ -80,22 +129,53 @@ export function clearPendingAutoFixTasks() {
}
/**
- * Handle AI provider execution failures specifically
- * These are always tracked and can create tasks even if CoS is not running
+ * Test-only: drop all deferred timers + dedupe entries so the next call
+ * starts from a clean slate. Production code paths never call this.
+ */
+export function _resetAutoFixerForTests() {
+ for (const { timer } of deferredTasks.values()) clearTimeout(timer);
+ deferredTasks.clear();
+ recentErrors.clear();
+ pendingAutoFixTasks.length = 0;
+}
+
+/**
+ * Defer task creation by TASK_DEFER_MS. If `noteFallbackHandled` is called
+ * for the same provider/model within the window, the timer is cancelled
+ * and no task is created. Otherwise, the deferred handler runs and
+ * creates the investigation task.
*/
async function handleAIProviderError(error) {
const ctx = error.context || {};
- // Use stable key based on provider + model to prevent duplicates from different runIds
- // This ensures we only create one task per unique provider/model combination
- const errorKey = `${error.code}-${ctx.provider}-${ctx.model}`;
+ const errorKey = aiProviderErrorKey(ctx.provider, ctx.model);
if (isDuplicateError(errorKey)) {
console.log(`⏭️ Skipping duplicate AI provider error: ${ctx.provider} (${ctx.model})`);
return;
}
+ if (deferredTasks.has(errorKey)) {
+ return;
+ }
- console.log(`🤖 AI provider error detected: ${ctx.provider} - run ${ctx.runId}`);
+ console.log(`🤖 AI provider error detected: ${ctx.provider} - run ${ctx.runId} (deferring ${TASK_DEFER_MS}ms for possible fallback retry)`);
+
+ const timer = setTimeout(() => {
+ deferredTasks.delete(errorKey);
+ createAIProviderInvestigationTask(error).catch(err => {
+ console.error(`❌ Deferred AI provider task creation failed: ${err.message}`);
+ // Clear the dedupe entry so the next identical failure isn't
+ // silently suppressed for up to 60s — without this, an addTask
+ // failure here would block legitimate retries that might succeed.
+ recentErrors.delete(errorKey);
+ });
+ }, TASK_DEFER_MS);
+ // Keep the timer from preventing process exit (e.g. in tests / shutdown).
+ timer.unref?.();
+ deferredTasks.set(errorKey, { timer });
+}
+async function createAIProviderInvestigationTask(error) {
+ const ctx = error.context || {};
// Build specialized context for AI provider errors
const context = buildAIProviderErrorContext(error);
diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.js
new file mode 100644
index 0000000000..313759fb23
--- /dev/null
+++ b/server/services/autoFixer.test.js
@@ -0,0 +1,177 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// cos.js drags in a giant dependency graph (PM2, fs, sockets…) — mock it
+// so autoFixer's defer/cancel behavior can be tested in isolation. Both
+// exports the SUT touches are stubbed: `addTask` records what would be
+// queued, `isRunning` toggles the running/not-running branches.
+vi.mock('./cos.js', () => ({
+ addTask: vi.fn().mockResolvedValue({ id: 'task-1' }),
+ isRunning: vi.fn().mockReturnValue(true),
+}));
+
+const cos = await import('./cos.js');
+const {
+ noteFallbackHandled,
+ initAutoFixer,
+ getPendingAutoFixTasks,
+ clearPendingAutoFixTasks,
+ _resetAutoFixerForTests,
+} = await import('./autoFixer.js');
+const { errorEvents } = await import('../lib/errorHandler.js');
+
+// initAutoFixer is idempotent — it must run once for the error-event
+// listener to be attached, regardless of which test file boots first.
+initAutoFixer();
+
+function emitProviderFailure({ provider = 'Primary CLI', model = 'm-1', runId = 'run-1' } = {}) {
+ errorEvents.emit('error', {
+ code: 'AI_PROVIDER_EXECUTION_FAILED',
+ message: `AI provider ${provider} execution failed: boom`,
+ severity: 'error',
+ canAutoFix: true,
+ timestamp: Date.now(),
+ context: {
+ runId,
+ provider,
+ providerId: provider.toLowerCase().replace(/\s+/g, '-'),
+ model,
+ exitCode: 1,
+ },
+ });
+}
+
+describe('autoFixer — defer + noteFallbackHandled', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ cos.addTask.mockClear();
+ cos.isRunning.mockReturnValue(true);
+ _resetAutoFixerForTests();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ _resetAutoFixerForTests();
+ });
+
+ it('defers task creation by ~5s instead of creating it immediately', async () => {
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1' });
+ // Allow the synchronous emit + the IIFE's microtask queue to drain so
+ // the deferred timer is set before we assert on it.
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Task is NOT created right away — it's deferred.
+ expect(cos.addTask).not.toHaveBeenCalled();
+
+ // After the defer window elapses, the task is created.
+ await vi.advanceTimersByTimeAsync(5500);
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ expect(cos.addTask.mock.calls[0][0]).toMatchObject({
+ description: 'Investigate AI provider failure: Primary CLI (m-1)',
+ });
+ });
+
+ it('cancels the deferred task when noteFallbackHandled fires within the window', async () => {
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1' });
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Fallback succeeded — call noteFallbackHandled BEFORE the defer elapses.
+ const handled = noteFallbackHandled({ provider: 'Primary CLI', model: 'm-1' });
+ expect(handled).toBe(true);
+
+ // Advancing past the defer window must NOT trigger task creation.
+ await vi.advanceTimersByTimeAsync(10000);
+ expect(cos.addTask).not.toHaveBeenCalled();
+ });
+
+ it('returns false when noteFallbackHandled has no matching deferred task', async () => {
+ const handled = noteFallbackHandled({ provider: 'Unknown', model: 'nope' });
+ expect(handled).toBe(false);
+ });
+
+ it('matches the deferred task by exact provider+model (mismatched key does not cancel)', async () => {
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1' });
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Wrong model — should not cancel.
+ expect(noteFallbackHandled({ provider: 'Primary CLI', model: 'wrong-model' })).toBe(false);
+ // Wrong provider name — should not cancel.
+ expect(noteFallbackHandled({ provider: 'Other CLI', model: 'm-1' })).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(5500);
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('allows a future failure of the same provider to raise a new task after suppression (no 60s dedupe lockout)', async () => {
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'r-1' });
+ await vi.advanceTimersByTimeAsync(0);
+ noteFallbackHandled({ provider: 'Primary CLI', model: 'm-1' });
+ await vi.advanceTimersByTimeAsync(10000);
+ expect(cos.addTask).not.toHaveBeenCalled();
+
+ // Same provider fails again later — must NOT be suppressed by the
+ // dedupe map (which would otherwise hold the key for 60s).
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'r-2' });
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(5500);
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('queues to pendingAutoFixTasks when CoS is not running', async () => {
+ clearPendingAutoFixTasks();
+ cos.isRunning.mockReturnValue(false);
+
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1' });
+ await vi.advanceTimersByTimeAsync(5500);
+
+ expect(cos.addTask).not.toHaveBeenCalled();
+ const pending = getPendingAutoFixTasks();
+ expect(pending).toHaveLength(1);
+ expect(pending[0].description).toBe('Investigate AI provider failure: Primary CLI (m-1)');
+ clearPendingAutoFixTasks();
+ });
+
+ it('clears the dedupe entry when deferred task creation fails so future failures can still raise tasks', async () => {
+ // Simulate addTask rejecting (e.g. PLAN.md write error). Without the
+ // dedupe-clear in the catch arm, the next identical failure would be
+ // suppressed for 60s even though no investigation task ever landed.
+ cos.addTask.mockRejectedValueOnce(new Error('plan write failed'));
+
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'r-1' });
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(5500);
+ // Drain the rejected addTask's microtask + the .catch's recentErrors.delete.
+ await vi.advanceTimersByTimeAsync(0);
+
+ // First attempt: addTask threw, so no task was created.
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+
+ // Second identical failure within the 60s dedupe window must NOT be
+ // suppressed — the stale dedupe entry should have been cleared.
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'r-2' });
+ await vi.advanceTimersByTimeAsync(5500);
+ expect(cos.addTask).toHaveBeenCalledTimes(2);
+ });
+
+ it('does NOT collide on hyphenated provider/model pairs (uses an unambiguous separator)', async () => {
+ // Regression: a `-`-joined dedupe key would treat
+ // ("gpt-4o", "mini") and ("gpt", "4o-mini") as the same failure,
+ // silently suppressing one with the other's deferred task.
+ emitProviderFailure({ provider: 'gpt-4o', model: 'mini', runId: 'r-1' });
+ emitProviderFailure({ provider: 'gpt', model: '4o-mini', runId: 'r-2' });
+ await vi.advanceTimersByTimeAsync(5500);
+
+ // Both distinct failures must schedule their own investigation task.
+ expect(cos.addTask).toHaveBeenCalledTimes(2);
+ });
+
+ it('dedupes within the defer window — a second identical failure does not double-schedule', async () => {
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'r-1' });
+ await vi.advanceTimersByTimeAsync(0);
+ emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'r-2' });
+ await vi.advanceTimersByTimeAsync(5500);
+
+ // Only the first failure schedules a task; the second is dropped by
+ // either isDuplicateError or the deferredTasks.has guard.
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ });
+});