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

fix: gate persistent mind providers on readiness (#5155) (#5174)

[._.]/ Adam Eivy2ee3b6504aad
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index 04b6bb9b87..ff600a133e 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -75,7 +75,7 @@ export const providerSchema = z.object({
id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, 'id must be lowercase alphanumeric with hyphens').max(80).optional(),
name: z.string().min(1).max(100),
type: z.enum(['cli', 'api', 'tui']),
- command: z.string().optional(),
+ command: z.string().trim().optional(),
args: z.array(z.string()).optional(),
// CLI providers send `endpoint: ''` from the form; coerce empty/null to
// undefined so the URL check only runs for actual values (API providers).
diff --git a/server/lib/aiToolkit/validation.test.js b/server/lib/aiToolkit/validation.test.js
index 0bf7ea2b60..78a36aeb33 100644
--- a/server/lib/aiToolkit/validation.test.js
+++ b/server/lib/aiToolkit/validation.test.js
@@ -71,6 +71,12 @@ describe('providerSchema', () => {
expect(providerSchema.safeParse(minimalProvider).success).toBe(true);
});
+ it('normalizes surrounding command whitespace before persistence', () => {
+ const result = providerSchema.safeParse({ ...minimalProvider, command: ' codex ' });
+ expect(result.success).toBe(true);
+ expect(result.data.command).toBe('codex');
+ });
+
it('accepts the explicit MTPLX marker and rejects a non-boolean value', () => {
expect(providerSchema.safeParse({ ...minimalProvider, mtplxBacked: true }).success).toBe(true);
expect(providerSchema.safeParse({ ...minimalProvider, mtplxBacked: 'true' }).success).toBe(false);
diff --git a/server/services/persistentMindTaskCapability.js b/server/services/persistentMindTaskCapability.js
index a384cb795e..8f2112d29a 100644
--- a/server/services/persistentMindTaskCapability.js
+++ b/server/services/persistentMindTaskCapability.js
@@ -21,6 +21,7 @@ import { resolveAppWorkTracker } from '../lib/workTracker.js';
import { getActiveApps, getAppWorkTracker } from './apps.js';
import { loadState } from './cosState.js';
import { addTask, getTaskById } from './cosTaskStore.js';
+import { getProviderPrerequisiteReadinessMap } from './providerPrerequisites.js';
import { listProviders } from './providers.js';
const MAX_CATALOG_APPS = 50;
@@ -36,6 +37,35 @@ const isRunnableApp = (app) => typeof app?.repoPath === 'string' && app.repoPath
const isRunnableAgentProvider = (provider) => provider?.enabled !== false
&& (provider?.type === 'cli' || provider?.type === 'tui');
+const boundedProviderCandidates = (providers) => providers
+ .filter((provider) => isRunnableAgentProvider(provider)
+ && typeof provider?.id === 'string' && provider.id
+ && provider.id.length <= PERSISTENT_MIND_TASK_LIMITS.providerIdChars)
+ .slice(0, MAX_CATALOG_PROVIDERS);
+
+const providerReadinessSummary = (providers, readiness) => {
+ const summary = {
+ blockedCount: 0,
+ blockedReasonCodes: [],
+ unknownCount: 0,
+ unknownReasonCodes: [],
+ };
+ for (const provider of providers) {
+ const verdict = readiness[provider.id];
+ if (verdict?.status !== 'blocked' && verdict?.status !== 'unknown') continue;
+ const prefix = verdict.status;
+ summary[`${prefix}Count`] += 1;
+ summary[`${prefix}ReasonCodes`].push(...(verdict.reasonCodes || []));
+ }
+ summary.blockedReasonCodes = [...new Set(summary.blockedReasonCodes)].sort();
+ summary.unknownReasonCodes = [...new Set(summary.unknownReasonCodes)].sort();
+ return summary;
+};
+
+const boundedReadinessReasonCodes = (value) => (Array.isArray(value) ? value : [])
+ .filter((code) => typeof code === 'string' && /^[a-z][a-zA-Z0-9-]{0,49}$/.test(code))
+ .slice(0, 10);
+
const selectableModelIds = (provider) => {
const stored = filterSelectableModels(antigravityBaseModels(provider?.models))
.filter((model) => typeof model === 'string' && model.trim()
@@ -86,19 +116,35 @@ export async function readPersistentMindTaskCatalog() {
.filter((app) => isRunnableApp(app) && typeof app?.id === 'string' && app.id
&& app.id.length <= PERSISTENT_MIND_TASK_LIMITS.appIdChars)
.slice(0, MAX_CATALOG_APPS);
+ const candidates = boundedProviderCandidates(providers);
+ const readiness = await getProviderPrerequisiteReadinessMap(providers, {
+ candidates,
+ deferCwdDependent: true,
+ });
return {
apps: await Promise.all(runnableApps.map(appCatalogEntry)),
- providers: providers
- .filter((provider) => isRunnableAgentProvider(provider)
- && typeof provider?.id === 'string' && provider.id
- && provider.id.length <= PERSISTENT_MIND_TASK_LIMITS.providerIdChars)
- .slice(0, MAX_CATALOG_PROVIDERS)
+ providers: candidates
+ .filter((provider) => readiness[provider.id]?.status === 'ready')
.map(providerCatalogEntry),
+ providerReadiness: providerReadinessSummary(candidates, readiness),
};
}
const boundedPromptCatalog = (catalog) => {
- const bounded = { apps: [], providers: [] };
+ const bounded = {
+ apps: [],
+ providers: [],
+ providerReadiness: {
+ blockedCount: Number.isSafeInteger(catalog?.providerReadiness?.blockedCount)
+ ? Math.max(0, Math.min(MAX_CATALOG_PROVIDERS, catalog.providerReadiness.blockedCount))
+ : 0,
+ blockedReasonCodes: boundedReadinessReasonCodes(catalog?.providerReadiness?.blockedReasonCodes),
+ unknownCount: Number.isSafeInteger(catalog?.providerReadiness?.unknownCount)
+ ? Math.max(0, Math.min(MAX_CATALOG_PROVIDERS, catalog.providerReadiness.unknownCount))
+ : 0,
+ unknownReasonCodes: boundedReadinessReasonCodes(catalog?.providerReadiness?.unknownReasonCodes),
+ },
+ };
for (const app of Array.isArray(catalog?.apps) ? catalog.apps : []) {
bounded.apps.push(app);
if (JSON.stringify({ apps: bounded.apps }).length > MAX_CATALOG_APP_PROMPT_CHARS) {
@@ -161,6 +207,14 @@ const taskIdFor = (wakeId, fingerprint) => (
const boundedError = (error) => String(error?.message || error || 'Task creation failed').slice(0, 300);
+const readinessError = (providerId, verdict) => {
+ const reasonCodes = (verdict?.reasonCodes || []).slice(0, 5).join(', ') || 'prerequisites';
+ if (verdict?.status === 'unknown') {
+ return `Provider '${providerId}' readiness is still being checked (${reasonCodes}); retry shortly or check Settings > AI Providers`;
+ }
+ return `Provider '${providerId}' is not ready (${reasonCodes}); check Settings > AI Providers`;
+};
+
const validateChoice = async (request, apps, providers) => {
const app = apps.find((candidate) => candidate.id === request.appId && isRunnableApp(candidate));
if (!app) return { error: `App '${request.appId}' has no configured repository` };
@@ -168,6 +222,11 @@ const validateChoice = async (request, apps, providers) => {
candidate.id === request.providerId && isRunnableAgentProvider(candidate)
));
if (!provider) return { error: `Provider '${request.providerId}' is not an enabled CLI/TUI coding provider` };
+ const readiness = (await getProviderPrerequisiteReadinessMap(providers, {
+ candidates: [provider],
+ cwd: app.repoPath,
+ }))[provider.id];
+ if (readiness?.status !== 'ready') return { error: readinessError(provider.id, readiness) };
const models = selectableModelIds(provider);
if (request.model && !models.includes(request.model)) {
return { error: `Model '${request.model}' is not configured for provider '${request.providerId}'` };
@@ -185,9 +244,10 @@ const validateChoice = async (request, apps, providers) => {
return { app, provider };
};
-async function queueOneTask({ request, taskId, apps, providers }) {
+async function queueOneTask({ request, taskId, apps }) {
const existing = await getTaskById(taskId);
if (existing) return { success: true, duplicate: true, task: existing };
+ const providers = await listProviders();
const choice = await validateChoice(request, apps, providers);
if (choice.error) return { success: false, error: choice.error };
const planOnly = request.planOnly === true;
@@ -246,7 +306,7 @@ export async function executePersistentMindTaskRequests({
: [];
if (requests.length === 0) return [];
- const [root, apps, providers] = await Promise.all([loadState(), getActiveApps(), listProviders()]);
+ const [root, apps] = await Promise.all([loadState(), getActiveApps()]);
const enabled = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities).createTasks;
const record = typeof recordCapabilityEvent === 'function'
? recordCapabilityEvent
@@ -281,7 +341,7 @@ export async function executePersistentMindTaskRequests({
? { success: false, error: 'Persistent mind turn was interrupted before task creation' }
: enabled
? await Promise.resolve()
- .then(() => queueOneTask({ request, taskId, apps, providers }))
+ .then(() => queueOneTask({ request, taskId, apps }))
.then((value) => value, (error) => ({ success: false, error: boundedError(error) }))
: { success: false, error: 'Persistent mind task creation access is disabled' };
const displayText = outcome.success
diff --git a/server/services/persistentMindTaskCapability.test.js b/server/services/persistentMindTaskCapability.test.js
index fc5a26eba2..1d0eb52fa8 100644
--- a/server/services/persistentMindTaskCapability.test.js
+++ b/server/services/persistentMindTaskCapability.test.js
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
getTaskById: vi.fn(),
getAppWorkTracker: vi.fn(),
resolveAppWorkTracker: vi.fn(),
+ getProviderPrerequisiteReadinessMap: vi.fn(),
}));
vi.mock('./apps.js', () => ({
@@ -24,6 +25,9 @@ vi.mock('./cosTaskStore.js', () => ({
getTaskById: (...args) => mocks.getTaskById(...args),
}));
vi.mock('./providers.js', () => ({ listProviders: vi.fn(async () => mocks.providers) }));
+vi.mock('./providerPrerequisites.js', () => ({
+ getProviderPrerequisiteReadinessMap: (...args) => mocks.getProviderPrerequisiteReadinessMap(...args),
+}));
vi.mock('../lib/workTracker.js', () => ({
resolveAppWorkTracker: (...args) => mocks.resolveAppWorkTracker(...args),
}));
@@ -59,6 +63,9 @@ beforeEach(() => {
mocks.resolveAppWorkTracker.mockResolvedValue({ resolved: 'plan' });
mocks.getTaskById.mockImplementation(async () => mocks.existing);
mocks.addTask.mockResolvedValue({ id: 'sys-mind-stable', status: 'pending', autoApproved: true });
+ mocks.getProviderPrerequisiteReadinessMap.mockImplementation((providers) => Object.fromEntries(
+ providers.map((provider) => [provider.id, { status: 'ready', reasonCodes: [] }]),
+ ));
});
describe('persistent mind CoS-task capability', () => {
@@ -75,6 +82,12 @@ describe('persistent mind CoS-task capability', () => {
{ id: 'gpt-5-mini', efforts: expect.arrayContaining(['high']) },
],
}],
+ providerReadiness: {
+ blockedCount: 0,
+ blockedReasonCodes: [],
+ unknownCount: 0,
+ unknownReasonCodes: [],
+ },
});
const prompt = buildPersistentMindTaskCapabilityPrompt({ enabled: true, catalog });
expect(prompt).toContain('"review-then-merge"');
@@ -85,6 +98,31 @@ describe('persistent mind CoS-task capability', () => {
expect(prompt).not.toContain('command');
});
+ it('omits blocked and unknown providers while publishing bounded reason-code aggregates', async () => {
+ mocks.providers.push(
+ { id: 'claude', name: 'Claude', type: 'cli', enabled: true, command: 'claude' },
+ { id: 'grok', name: 'Grok', type: 'cli', enabled: true, command: 'grok' },
+ );
+ mocks.getProviderPrerequisiteReadinessMap.mockReturnValue({
+ codex: { status: 'ready', reasonCodes: [] },
+ claude: { status: 'blocked', reasonCodes: ['runtime', 'inheritedApiKey'] },
+ grok: { status: 'unknown', reasonCodes: ['runtime-unprobed'] },
+ });
+
+ const catalog = await readPersistentMindTaskCatalog();
+ expect(catalog.providers.map((provider) => provider.id)).toEqual(['codex']);
+ expect(catalog.providerReadiness).toEqual({
+ blockedCount: 1,
+ blockedReasonCodes: ['inheritedApiKey', 'runtime'],
+ unknownCount: 1,
+ unknownReasonCodes: ['runtime-unprobed'],
+ });
+ const prompt = buildPersistentMindTaskCapabilityPrompt({ enabled: true, catalog });
+ expect(prompt).toContain('"blockedCount":1');
+ expect(prompt).toContain('"runtime-unprobed"');
+ expect(prompt).not.toContain('command');
+ });
+
it('bounds a large configured catalog before it enters the reasoning prompt', () => {
const catalog = {
apps: Array.from({ length: 100 }, (_, index) => ({ id: `app-${index}`, name: 'A'.repeat(100) })),
@@ -206,6 +244,37 @@ describe('persistent mind CoS-task capability', () => {
expect(mocks.addTask).not.toHaveBeenCalled();
});
+ it('revalidates readiness immediately before queueing and rejects a mid-turn change', async () => {
+ await readPersistentMindTaskCatalog();
+ mocks.getProviderPrerequisiteReadinessMap.mockReturnValue({
+ codex: { status: 'blocked', reasonCodes: ['runtime'] },
+ });
+
+ const [result] = await executePersistentMindTaskRequests({
+ taskRequests: [taskRequest()],
+ turnId: 'turn-readiness-change',
+ wake: { kind: 'message', message: { id: 'message-readiness-change' } },
+ });
+
+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('not ready (runtime)') });
+ expect(mocks.addTask).not.toHaveBeenCalled();
+ });
+
+ it('keeps an unprobed provider distinct from a ready provider', async () => {
+ mocks.getProviderPrerequisiteReadinessMap.mockReturnValue({
+ codex: { status: 'unknown', reasonCodes: ['runtime-unprobed'] },
+ });
+
+ const [result] = await executePersistentMindTaskRequests({
+ taskRequests: [taskRequest()],
+ turnId: 'turn-readiness-unknown',
+ wake: { kind: 'message', message: { id: 'message-readiness-unknown' } },
+ });
+
+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('still being checked') });
+ expect(mocks.addTask).not.toHaveBeenCalled();
+ });
+
it('allows only the provider default when no concrete models are configured', async () => {
mocks.providers = [{
id: 'codex', name: 'Codex', type: 'cli', enabled: true, command: 'codex',
diff --git a/server/services/providerPrerequisites.js b/server/services/providerPrerequisites.js
index ed00fa4d21..675954f8b5 100644
--- a/server/services/providerPrerequisites.js
+++ b/server/services/providerPrerequisites.js
@@ -8,16 +8,16 @@
* - `getProviderPrerequisiteMap(providers)` — the whole collection's verdict,
* for decorating `GET /api/providers` so the AI Providers page reads the
* same answer the router uses instead of deriving its own.
+ * - `getProviderPrerequisiteReadinessMap(providers)` — strict tri-state
+ * readiness for authoritative choices that cannot treat unprobed as ready.
* - `prerequisitesMetForRouting(provider, providers)` — the gate the
* fallback-provider chain in `aiToolkit/providerStatus.js` consults.
*
- * BOTH are synchronous and read only what the runtime probe has already cached,
- * kicking a coalesced background refresh when it has nothing current. Routing
- * has no choice — `getFallbackProvider` is a synchronous decision — and the
- * route must not await either: `GET /api/providers` is fetched by half the app,
- * and a cold cache would put a multi-second `--version` sweep of every CLI on
- * that critical path. The credential checks need no probe at all, so they are
- * always exact; only the runtime finding waits on the cache.
+ * The provider-page map and fallback route stay synchronous and read only what
+ * the runtime probe has already cached. The strict readiness map is async: its
+ * authoritative callers await a cold/expired probe before publishing choices.
+ * This keeps `GET /api/providers` off the multi-second `--version` sweep while
+ * preventing a Persistent Mind turn from receiving an empty, stale catalog.
*
* The result is permissive in three deliberate ways. An un-probed runtime
* yields no finding, so the first pick after boot behaves exactly as it did
@@ -35,7 +35,15 @@
import { blocksRouting, describeMissingPrerequisites, providerPrerequisites, providerRuntimeKey } from '../lib/providerPrerequisites.js';
import { PROVIDER_GATEWAYS } from '../lib/providerGateways.js';
-import { getProviderRuntime, getProviderRuntimeStatuses, peekProviderRuntimeStatuses } from './providerRuntimeInstaller.js';
+import { inferTuiCommand } from '../lib/providerVendors.js';
+import { findCommandOnPath } from '../lib/processEnv.js';
+import { delimiter, isAbsolute } from 'path';
+import {
+ getProviderRuntime,
+ getProviderRuntimeStatus,
+ getProviderRuntimeStatuses,
+ peekProviderRuntimeStatuses,
+} from './providerRuntimeInstaller.js';
/**
* Per gateway id, does the sibling API provider of that id hold the key an
@@ -95,6 +103,53 @@ const forProvider = (provider, runtimes, gatewayKeySet) => providerPrerequisites
gatewayKeySet,
});
+const effectiveProcessCommand = (provider) => {
+ const configured = typeof provider?.command === 'string' ? provider.command.trim() : '';
+ if (configured) return configured;
+ return provider?.type === 'tui' ? inferTuiCommand(provider?.id) : 'claude';
+};
+
+const configuredCommandIsNormalized = (provider) => typeof provider?.command !== 'string'
+ || provider.command === ''
+ || provider.command === provider.command.trim();
+
+const prerequisiteReadinessFor = (provider, runtimes, gatewayKeySet) => {
+ const effectiveProvider = provider?.command
+ ? provider
+ : { ...provider, command: effectiveProcessCommand(provider) };
+ const runtimeKey = providerRuntimeKey(effectiveProvider);
+ const runtime = runtimes?.[runtimeKey ?? ''] ?? null;
+ const { missing } = forProvider(effectiveProvider, runtimes, gatewayKeySet);
+ if (missing.length > 0) {
+ return {
+ status: 'blocked',
+ reasonCodes: [...new Set(missing.map((entry) => entry.code).filter(Boolean))],
+ };
+ }
+ if (runtimeKey && getProviderRuntime(runtimeKey) && !runtime) {
+ return { status: 'unknown', reasonCodes: ['runtime-unprobed'] };
+ }
+ return { status: 'ready', reasonCodes: [] };
+};
+
+const processProviderRuntimeStatus = (provider, { cwd = null, deferCwdDependent = false } = {}) => {
+ if (provider?.type !== 'cli' && provider?.type !== 'tui') return null;
+ if (!configuredCommandIsNormalized(provider)) return { installed: false, reasonCode: 'command' };
+ const command = effectiveProcessCommand(provider);
+ const effectiveProvider = { ...provider, command };
+ const runtimeKey = providerRuntimeKey(effectiveProvider);
+ if (runtimeKey && getProviderRuntime(runtimeKey)) return null;
+ const env = { ...process.env, ...(provider?.envVars || {}) };
+ const explicitRelativeCommand = /[\\/]/.test(command) && !isAbsolute(command);
+ const relativePathEntry = String(env.PATH || env.Path || '')
+ .split(delimiter)
+ .some((entry) => entry === '' || !isAbsolute(entry));
+ if (deferCwdDependent && !cwd && (explicitRelativeCommand || relativePathEntry)) return null;
+ return findCommandOnPath(command, { env, ...(cwd ? { cwd } : {}) })
+ ? { installed: true }
+ : { installed: false };
+};
+
/**
* `{ [providerId]: { met, missing } }` for a whole provider collection.
* @param {Array<object>} providers — raw or sanitized provider records
@@ -107,6 +162,48 @@ export function getProviderPrerequisiteMap(providers) {
return Object.fromEntries(list.map((provider) => [provider.id, forProvider(provider, runtimes, gatewayKeySet)]));
}
+/**
+ * A strict, non-secret prerequisite verdict for authoritative task choices.
+ * Unlike routing, this distinguishes a cold/expired runtime probe from a known
+ * runnable provider so callers that promise a provider choice can fail closed.
+ * Commands outside the fixed installer table are resolved against the same
+ * configured PATH/explicit-path rules the child process uses. `candidates`
+ * limits expensive runtime probes while `providers` remains the full sibling
+ * set used for inherited credential checks. A catalog may defer cwd-dependent
+ * commands, then its execution path must call again with the selected app cwd.
+ */
+export async function getProviderPrerequisiteReadinessMap(providers, {
+ candidates = providers,
+ cwd = null,
+ deferCwdDependent = false,
+} = {}) {
+ const list = Array.isArray(providers) ? providers : [];
+ const targetList = Array.isArray(candidates) ? candidates : [];
+ if (list.length === 0 || targetList.length === 0) return {};
+ const processProviders = targetList.map((provider) => {
+ const command = effectiveProcessCommand(provider);
+ return { ...provider, command };
+ });
+ const runtimeKeys = processProviders.map(providerRuntimeKey);
+ const cached = peekProviderRuntimeStatuses();
+ const missingRuntimeKeys = [...new Set(runtimeKeys
+ .filter((key) => key && getProviderRuntime(key) && !cached[key]))];
+ const probed = await Promise.all(missingRuntimeKeys.map(async (key) => [
+ key,
+ await getProviderRuntimeStatus(key),
+ ]));
+ const runtimes = { ...cached, ...Object.fromEntries(probed) };
+ const gatewayKeySet = gatewayKeyState(list);
+ return Object.fromEntries(targetList.map((provider, index) => {
+ const effectiveProvider = processProviders[index];
+ const customRuntime = processProviderRuntimeStatus(provider, { cwd, deferCwdDependent });
+ const verdict = customRuntime?.installed === false
+ ? { status: 'blocked', reasonCodes: [customRuntime.reasonCode || 'runtime'] }
+ : prerequisiteReadinessFor(effectiveProvider, runtimes, gatewayKeySet);
+ return [provider.id, verdict];
+ }));
+}
+
/**
* Can this provider run right now, as far as the already-probed facts say?
*
diff --git a/server/services/providerPrerequisites.test.js b/server/services/providerPrerequisites.test.js
index c867ee1e48..22c622d58b 100644
--- a/server/services/providerPrerequisites.test.js
+++ b/server/services/providerPrerequisites.test.js
@@ -1,16 +1,27 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { basename, dirname } from 'path';
// Only the probe is stubbed — `getProviderRuntime` stays real so the "is this
// command even in the runtime table?" branch is exercised against the shipped
// table rather than a fixture that could drift from it.
vi.mock('./providerRuntimeInstaller.js', async (importOriginal) => ({
...(await importOriginal()),
+ getProviderRuntimeStatus: vi.fn(),
getProviderRuntimeStatuses: vi.fn(),
peekProviderRuntimeStatuses: vi.fn(),
}));
-const { getProviderRuntimeStatuses, peekProviderRuntimeStatuses } = await import('./providerRuntimeInstaller.js');
-const { getProviderPrerequisiteMap, prerequisitesMetForRouting, __resetPrerequisiteRefresh } =
+const {
+ getProviderRuntimeStatus,
+ getProviderRuntimeStatuses,
+ peekProviderRuntimeStatuses,
+} = await import('./providerRuntimeInstaller.js');
+const {
+ getProviderPrerequisiteMap,
+ getProviderPrerequisiteReadinessMap,
+ prerequisitesMetForRouting,
+ __resetPrerequisiteRefresh,
+} =
await import('./providerPrerequisites.js');
const CODEX_ABSENT = { id: 'codex', label: 'Codex CLI', installed: false };
@@ -22,6 +33,7 @@ beforeEach(() => {
vi.clearAllMocks();
__resetPrerequisiteRefresh();
peekProviderRuntimeStatuses.mockReturnValue({});
+ getProviderRuntimeStatus.mockResolvedValue(null);
getProviderRuntimeStatuses.mockResolvedValue({});
vi.spyOn(console, 'log').mockImplementation(() => {});
vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -82,6 +94,126 @@ describe('getProviderPrerequisiteMap', () => {
});
});
+describe('getProviderPrerequisiteReadinessMap', () => {
+ it('distinguishes ready and blocked runtime states after probing', async () => {
+ peekProviderRuntimeStatuses.mockReturnValue({
+ codex: CODEX_PRESENT,
+ claude: { id: 'claude', label: 'Claude Code CLI', installed: false },
+ });
+
+ getProviderRuntimeStatus.mockImplementation(async (id) => ({
+ codex: CODEX_PRESENT,
+ claude: { id: 'claude', label: 'Claude Code CLI', installed: false },
+ grok: { id: 'grok', label: 'Grok Build CLI', installed: true },
+ })[id]);
+
+ const map = await getProviderPrerequisiteReadinessMap([
+ codex(),
+ { id: 'claude', type: 'cli', command: 'claude' },
+ { id: 'grok', type: 'cli', command: 'grok' },
+ ]);
+
+ expect(map.codex).toEqual({ status: 'ready', reasonCodes: [] });
+ expect(map.claude).toEqual({ status: 'blocked', reasonCodes: ['runtime'] });
+ expect(map.grok).toEqual({ status: 'ready', reasonCodes: [] });
+ });
+
+ it('awaits a cold or expired runtime probe before returning readiness', async () => {
+ peekProviderRuntimeStatuses.mockReturnValue({});
+ getProviderRuntimeStatus.mockResolvedValue(CODEX_PRESENT);
+
+ await expect(getProviderPrerequisiteReadinessMap([codex()]))
+ .resolves.toMatchObject({ codex: { status: 'ready', reasonCodes: [] } });
+ expect(getProviderRuntimeStatus).toHaveBeenCalledTimes(1);
+ });
+
+ it('probes only selectable candidates while retaining the full sibling set for credentials', async () => {
+ const wrapper = { id: 'opencode-orcarouter', type: 'cli', command: 'opencode', orcarouterBacked: true };
+ const sibling = { id: 'orcarouter', type: 'api', endpoint: 'https://api.example.com', hasApiKey: false };
+ const disabled = { id: 'grok', type: 'cli', command: 'grok', enabled: false };
+ getProviderRuntimeStatus.mockResolvedValue({ id: 'opencode', label: 'OpenCode CLI', installed: true });
+
+ const map = await getProviderPrerequisiteReadinessMap([wrapper, sibling, disabled], {
+ candidates: [wrapper],
+ });
+
+ expect(getProviderRuntimeStatus).toHaveBeenCalledTimes(1);
+ expect(getProviderRuntimeStatus).toHaveBeenCalledWith('opencode');
+ expect(map).toEqual({
+ [wrapper.id]: { status: 'blocked', reasonCodes: ['inheritedApiKey'] },
+ });
+ });
+
+ it('uses the actual Claude fallback for a blank CLI command', async () => {
+ getProviderRuntimeStatus.mockResolvedValue({ id: 'claude', label: 'Claude Code CLI', installed: true });
+
+ await expect(getProviderPrerequisiteReadinessMap([
+ { id: 'grok-cli', type: 'cli', command: '' },
+ ])).resolves.toMatchObject({ 'grok-cli': { status: 'ready', reasonCodes: [] } });
+ expect(getProviderRuntimeStatus).toHaveBeenCalledWith('claude');
+ });
+
+ it('blocks a legacy command whose surrounding whitespace would make the spawn fail', async () => {
+ await expect(getProviderPrerequisiteReadinessMap([
+ codex({ command: ' codex ' }),
+ ])).resolves.toMatchObject({ codex: { status: 'blocked', reasonCodes: ['command'] } });
+ });
+
+ it('preserves an executable explicit-path provider outside the runtime table', async () => {
+ const provider = codex({ id: 'custom-codex', command: process.execPath });
+
+ await expect(getProviderPrerequisiteReadinessMap([provider]))
+ .resolves.toMatchObject({ 'custom-codex': { status: 'ready', reasonCodes: [] } });
+ expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();
+ });
+
+ it('resolves a provider command against its configured PATH', async () => {
+ const provider = codex({
+ id: 'custom-path-codex',
+ command: basename(process.execPath),
+ envVars: { PATH: dirname(process.execPath) },
+ });
+
+ await expect(getProviderPrerequisiteReadinessMap([provider]))
+ .resolves.toMatchObject({ 'custom-path-codex': { status: 'ready', reasonCodes: [] } });
+ expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();
+ });
+
+ it('defers app-relative commands in the catalog and resolves them from the selected workspace', async () => {
+ const provider = codex({ id: 'app-local', command: `./${basename(process.execPath)}` });
+
+ await expect(getProviderPrerequisiteReadinessMap([provider], {
+ deferCwdDependent: true,
+ })).resolves.toMatchObject({ 'app-local': { status: 'ready', reasonCodes: [] } });
+ await expect(getProviderPrerequisiteReadinessMap([provider], {
+ cwd: dirname(process.execPath),
+ })).resolves.toMatchObject({ 'app-local': { status: 'ready', reasonCodes: [] } });
+ await expect(getProviderPrerequisiteReadinessMap([provider], {
+ cwd: dirname(dirname(process.execPath)),
+ })).resolves.toMatchObject({ 'app-local': { status: 'blocked', reasonCodes: ['runtime'] } });
+ });
+
+ it('blocks a missing command outside the runtime table', async () => {
+ const provider = codex({ id: 'custom-cli', command: '/missing/example-provider-cli' });
+
+ await expect(getProviderPrerequisiteReadinessMap([provider]))
+ .resolves.toMatchObject({ 'custom-cli': { status: 'blocked', reasonCodes: ['runtime'] } });
+ });
+
+ it('blocks on a known inherited credential finding without exposing its value', async () => {
+ peekProviderRuntimeStatuses.mockReturnValue({
+ opencode: { id: 'opencode', label: 'OpenCode CLI', installed: true },
+ });
+ const wrapper = { id: 'opencode-orcarouter', type: 'cli', command: 'opencode', orcarouterBacked: true };
+ const sibling = { id: 'orcarouter', type: 'api', endpoint: 'https://api.example.com', hasApiKey: false };
+
+ await expect(getProviderPrerequisiteReadinessMap([wrapper, sibling]))
+ .resolves.toMatchObject({
+ [wrapper.id]: { status: 'blocked', reasonCodes: ['inheritedApiKey'] },
+ });
+ });
+});
+
describe('prerequisitesMetForRouting', () => {
it('rejects a provider whose CLI the probe has already found absent', () => {
peekProviderRuntimeStatuses.mockReturnValue({ codex: CODEX_ABSENT });