diff --git a/components/AIChatPanelContent.tsx b/components/AIChatPanelContent.tsx index 669e98acd..ed0ece3d7 100644 --- a/components/AIChatPanelContent.tsx +++ b/components/AIChatPanelContent.tsx @@ -95,6 +95,7 @@ interface AIChatPanelContentProps { modelCatalogFetchedAt?: string; /** Retry a failed SDK model catalog load from the warning banner. */ handleModelCatalogRetry?: () => void; + handleModelPickerOpen?: () => void; agentModelPresets: AgentModelPreset[]; /** Suppress the composer picker's "use custom model" action (locked model). */ allowCustomModelEntry?: boolean; @@ -173,6 +174,7 @@ export const AIChatPanelContent: React.FC = ({ handleSteer, handleStop, handleModelCatalogRetry, + handleModelPickerOpen, canSteer, isSteering, steerWarning, @@ -462,6 +464,7 @@ export const AIChatPanelContent: React.FC = ({ modelCatalogFetchedAt={modelCatalogFetchedAt} modelCatalogWarning={modelCatalogWarning} onRefreshModelCatalog={handleModelCatalogRetry} + onModelPickerOpen={handleModelPickerOpen} allowCustomModelEntry={allowCustomModelEntry} selectedModelId={selectedAgentModel} onModelSelect={handleAgentModelSelect} diff --git a/components/AIChatSidePanel.tsx b/components/AIChatSidePanel.tsx index 9a4cdf082..cc8ae26c9 100644 --- a/components/AIChatSidePanel.tsx +++ b/components/AIChatSidePanel.tsx @@ -1265,9 +1265,9 @@ const AIChatSidePanelActive: React.FC = ({ ? prev : { ...prev, [agentId]: { cacheKey: target.cacheKey, models: catalogPresets, catalogUnavailable: Boolean(catalog.warning) } } )); - // Another path (e.g. send preflight) applied the catalog before the - // deferred idle callback scheduled in the visibility effect: clear its - // stale pending flag so the composer stops claiming models are loading. + // Another path (e.g. send preflight or picker open) applied the catalog + // before the deferred idle callback scheduled in the visibility effect: + // clear its stale pending flag so the composer stops claiming models are loading. setRuntimeModelLoading((prev) => { if (!prev[agentId] || prev[agentId].cacheKey !== target.cacheKey) return prev; const { [agentId]: _removed, ...rest } = prev; @@ -1291,11 +1291,11 @@ const AIChatSidePanelActive: React.FC = ({ ) { setAgentModel(agentId, defaultModelId); } - }, [setAgentModel, setRuntimeModelLoading, buildExternalAgentRuntimeModelTarget, collectCustomModelIds]); + }, [setAgentModel, buildExternalAgentRuntimeModelTarget, collectCustomModelIds]); const loadSdkRuntimeModelCatalog = useCallback(( target: SdkRuntimeModelTarget, - options: { force?: boolean; logErrors?: boolean } = {}, + options: { force?: boolean; recheck?: boolean; logErrors?: boolean } = {}, ): Promise => { const bridge = getNetcattyBridge(); if (!bridge?.aiSdkAgentListModels) return Promise.resolve(null); @@ -1335,7 +1335,7 @@ const AIChatSidePanelActive: React.FC = ({ }); return toSdkRuntimeModelCatalog(result); }, - { force: options.force }, + { force: options.force || options.recheck }, ).then((catalog) => { // A refresh that joined another panel's in-flight load never ran the // loader above, so sync this panel's banner from the shared result. @@ -1404,17 +1404,46 @@ const AIChatSidePanelActive: React.FC = ({ }; let cancelled = false; let idleFired = false; - // Mark the catalog pending as soon as the refresh is scheduled so the - // composer can show its loading affordance for the whole idle delay (and - // longer while the composer stays focused) instead of silently keeping - // only the build-time presets (#3584). Only do this on a cache miss: - // when a cached catalog was already applied above, the runtime presets are - // available, so a pending flag would keep the composer banner/picker in the - // "loading" state indefinitely while the idle callback is deferred. + let loadSettled = false; if (!cached) { - setRuntimeModelLoading((prev) => ( - prev[target.agentId]?.cacheKey === target.cacheKey ? prev : { ...prev, [target.agentId]: { cacheKey: target.cacheKey } } - )); + // Hydrate persisted choices during the idle delay, including stale + // catalogs. This request never starts a runtime query. Only show the + // loading indicator when no persisted models exist yet (#3584). + void getNetcattyBridge()?.aiSdkAgentListModels?.( + target.sdkBackend, undefined, undefined, `models_${target.agentId}`, + target.agentEnv, target.agentCommand, target.codexRuntime, false, true, + ).then((result) => { + if (cancelled || sdkRuntimeModelCache.read(target.cacheKey)) return; + if (result?.ok && result.models?.length) { + setRuntimeModelWarnings((current) => { + const agent = externalAgentsRef.current.find((item) => item.id === target.agentId); + if (buildExternalAgentRuntimeModelTarget(agent)?.cacheKey !== target.cacheKey) return current; + return reconcileRuntimeModelWarning( + current, + target.agentId, + target.cacheKey, + Boolean(result.warning), + t('ai.chat.modelCatalogWarning'), + ); + }); + applySdkRuntimeModelCatalog(target, toSdkRuntimeModelCatalog({ + ...result, models: result.models, + })); + return; + } + if (!loadSettled) { + setRuntimeModelLoading((prev) => ( + prev[target.agentId]?.cacheKey === target.cacheKey ? prev : { ...prev, [target.agentId]: { cacheKey: target.cacheKey } } + )); + } + }).catch((err) => { + console.debug('[AIChatSidePanel] Failed to read cached agent models:', err); + if (!cancelled && !loadSettled && !sdkRuntimeModelCache.read(target.cacheKey)) { + setRuntimeModelLoading((prev) => ( + prev[target.agentId]?.cacheKey === target.cacheKey ? prev : { ...prev, [target.agentId]: { cacheKey: target.cacheKey } } + )); + } + }); } const cancelIdle = scheduleWhenAiComposerIdle(() => { idleFired = true; @@ -1422,8 +1451,7 @@ const AIChatSidePanelActive: React.FC = ({ if (cancelled || !catalog) return; applySdkRuntimeModelCatalog(target, catalog, { adoptCurrentModel: true }); }).finally(() => { - // Always clear, even after cancellation: a stale flag would keep the - // composer in the loading state forever. + loadSettled = true; clearRuntimeModelLoading(); }); }); @@ -1431,9 +1459,6 @@ const AIChatSidePanelActive: React.FC = ({ return () => { cancelled = true; cancelIdle(); - // If the idle callback never fired, the load never started and nothing - // would clear the pending flag — do it here. In-flight loads clear their - // own flag in `.finally`, so leave them alone. if (!idleFired) clearRuntimeModelLoading(); }; }, [ @@ -1561,6 +1586,18 @@ const AIChatSidePanelActive: React.FC = ({ setAgentModel(currentAgentId, modelId); }, [currentAgentId, setAgentModel]); + const handleOpenSdkModelPicker = useCallback(() => { + if (hasCodexCustomConfig) return; + const target = buildExternalAgentRuntimeModelTarget(currentAgentConfig); + if (!target) return; + // Check freshness in the main process even if the renderer cache is warm. + // Keep the existing choices usable while a stale catalog revalidates. + void loadSdkRuntimeModelCatalog(target, { recheck: true }).then((catalog) => { + if (catalog) applySdkRuntimeModelCatalog(target, catalog, { adoptCurrentModel: true }); + }); + }, [hasCodexCustomConfig, currentAgentConfig, buildExternalAgentRuntimeModelTarget, + loadSdkRuntimeModelCatalog, applySdkRuntimeModelCatalog]); + // Retry a failed SDK runtime model catalog load (composer warning banner). // Failures are never cached, so a forced refresh re-queries the CLI/daemon. const handleRetrySdkModelCatalog = useCallback(() => { @@ -2468,6 +2505,10 @@ const AIChatSidePanelActive: React.FC = ({ modelCatalogSource={modelCatalogSource} modelCatalogFetchedAt={modelCatalogFetchedAt} handleModelCatalogRetry={handleRetrySdkModelCatalog} + handleModelPickerOpen={!hasCodexCustomConfig && currentAgentConfig + && (shouldLoadSdkRuntimeModels(currentAgentConfig) || isCodexManagedAgent) + ? handleOpenSdkModelPicker + : undefined} agentModelPresets={agentModelPresets} // A managed Codex config's `model` field overrides every selection on // send, so the manual-entry action would be a silent no-op. diff --git a/components/AIChatSidePanelHelpers.test.tsx b/components/AIChatSidePanelHelpers.test.tsx index 4a7135734..3dda4ed15 100644 --- a/components/AIChatSidePanelHelpers.test.tsx +++ b/components/AIChatSidePanelHelpers.test.tsx @@ -685,6 +685,18 @@ test('reconcileRuntimeModelWarning clears only the banner that belongs to this c assert.equal(reconcileRuntimeModelWarning(current, 'copilot', 'k2', false, 'warn'), current); }); +test('cacheOnly hydration in AIChatSidePanel reconciles cached refresh warnings before applying persisted models', () => { + const source = readFileSync(new URL('./AIChatSidePanel.tsx', import.meta.url), 'utf8'); + assert.match( + source, + /target\.codexRuntime, false, true,\s*\)\.then\(\(result\) => \{[\s\S]*?reconcileRuntimeModelWarning\([\s\S]*?Boolean\(result\.warning\)[\s\S]*?applySdkRuntimeModelCatalog\(/, + ); + assert.match( + source, + /loadSdkRuntimeModelCatalog\(target, \{ recheck: true \}\)\.then\(\(catalog\) => \{\s*if \(catalog\) applySdkRuntimeModelCatalog\(target, catalog, \{ adoptCurrentModel: true \}\);/, + ); +}); + test('renderer model cache env hints cover every key the main-process catalog cache fingerprints', () => { // Both caches must split on the same profile-affecting environment: a key that // only the main process knows lets the renderer serve one profile's catalog to another. diff --git a/components/ai/ChatInput.test.tsx b/components/ai/ChatInput.test.tsx index 063e5ba8a..559abec27 100644 --- a/components/ai/ChatInput.test.tsx +++ b/components/ai/ChatInput.test.tsx @@ -69,6 +69,12 @@ test('parked composer closes body-portaled menus', () => { assert.match(source, /becameParked/); }); +test('opens the SDK model picker and starts its catalog check without awaiting it', () => { + const source = readFileSync(new URL('./ChatInput.tsx', import.meta.url), 'utf8'); + assert.match(source, /setActiveMenu\('model'\);\s*if \(!hasProviderSwitcher\) onModelPickerOpen\?\.\(\);\s*} else/); + assert.match(source, /prev\.onModelPickerOpen === next\.onModelPickerOpen/); +}); + test('first keystrokes stay local so IME and Chromium spellcheck cannot stall the composer', () => { const source = readFileSync(new URL('./ChatInput.tsx', import.meta.url), 'utf8'); assert.match(source, /spellCheck=\{false\}/); diff --git a/components/ai/ChatInput.tsx b/components/ai/ChatInput.tsx index 3408d3609..ca2a8e3f8 100644 --- a/components/ai/ChatInput.tsx +++ b/components/ai/ChatInput.tsx @@ -231,6 +231,7 @@ interface ChatInputProps { modelCatalogWarning?: string; /** Manual refresh action for the picker's refresh button (force path). */ onRefreshModelCatalog?: () => void; + onModelPickerOpen?: () => void; /** * Offer the picker's "use custom model" action. Disable when the current * agent locks the model (e.g. managed Codex `model` config overrides the @@ -313,6 +314,7 @@ const ChatInput: React.FC = ({ modelCatalogFetchedAt, modelCatalogWarning, onRefreshModelCatalog, + onModelPickerOpen, allowCustomModelEntry = true, selectedModelId, onModelSelect, @@ -1069,7 +1071,7 @@ const ChatInput: React.FC = ({ // now shows build-time presets during loading, with the loading row when // presets are still empty (#3584). const hasModelPicker = hasProviderSwitcher - || ((modelPresets.length > 0 || modelCatalogLoading) && !!onModelSelect); + || ((modelPresets.length > 0 || modelCatalogLoading || !!onModelPickerOpen) && !!onModelSelect); const thinkingLevels = useMemo( () => ( hasProviderSwitcher && onThinkingLevelChange @@ -1591,6 +1593,7 @@ const ChatInput: React.FC = ({ setMenuPos({ left, bottom: window.innerHeight - rect.top + 6 }); } setActiveMenu('model'); + if (!hasProviderSwitcher) onModelPickerOpen?.(); } else { closeAllMenus(); } @@ -1887,6 +1890,7 @@ function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boo && prev.modelCatalogFetchedAt === next.modelCatalogFetchedAt && prev.modelCatalogWarning === next.modelCatalogWarning && prev.onRefreshModelCatalog === next.onRefreshModelCatalog + && prev.onModelPickerOpen === next.onModelPickerOpen && prev.allowCustomModelEntry === next.allowCustomModelEntry && prev.selectedModelId === next.selectedModelId && prev.onModelSelect === next.onModelSelect diff --git a/components/settings/tabs/ai/types.ts b/components/settings/tabs/ai/types.ts index 5d0f9e0bb..845ba8a35 100644 --- a/components/settings/tabs/ai/types.ts +++ b/components/settings/tabs/ai/types.ts @@ -158,7 +158,7 @@ export interface NetcattyAiBridge { aiCodexCancelLogin?: (sessionId: string) => Promise<{ ok: boolean; found?: boolean; session?: CodexLoginSession; error?: string }>; aiCodexLogout?: (options?: { codexPath?: string; agentEnv?: Record }) => Promise<{ ok: boolean; state?: CodexIntegrationState; isConnected?: boolean; rawOutput?: string; logoutOutput?: string; error?: string }>; aiResolveCli?: (params: { command: string; customPath?: string; refreshShellEnv?: boolean; apiKeyPresent?: boolean }) => Promise; - aiSdkAgentListModels?: (sdkBackend: string, cwd?: string, providerId?: string, chatSessionId?: string, agentEnv?: Record, agentCommand?: string, codexRuntime?: 'sdk' | 'app-server', force?: boolean) => Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[]; defaultThinkingLevel?: string }>; currentModelId?: string | null; warning?: string; source?: 'live' | 'last-known-good'; fetchedAt?: string; error?: string }>; + aiSdkAgentListModels?: (sdkBackend: string, cwd?: string, providerId?: string, chatSessionId?: string, agentEnv?: Record, agentCommand?: string, codexRuntime?: 'sdk' | 'app-server', force?: boolean, cacheOnly?: boolean) => Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[]; defaultThinkingLevel?: string }>; currentModelId?: string | null; warning?: string; source?: 'live' | 'last-known-good'; fetchedAt?: string; error?: string }>; codexAppServerGetStatus?: (agentCommand?: string, agentEnv?: Record) => Promise<{ ok: boolean; available: boolean; error?: string }>; aiUserSkillsGetStatus?: () => Promise; aiUserSkillsOpenFolder?: () => Promise; diff --git a/electron/bridges/aiBridge/sdk/modelCatalogLastKnown.cjs b/electron/bridges/aiBridge/sdk/modelCatalogLastKnown.cjs index bf4cbfb19..dbdedce11 100644 --- a/electron/bridges/aiBridge/sdk/modelCatalogLastKnown.cjs +++ b/electron/bridges/aiBridge/sdk/modelCatalogLastKnown.cjs @@ -23,17 +23,44 @@ function buildLastKnownCatalogPath(userDataDir) { return path.join(userDataDir, LAST_KNOWN_CATALOG_FILE); } -/** Read the whole store; any corruption or absence degrades to {}. */ -function readLastKnownCatalogStore(filePath) { +/** Read the full store object ({ entries, aliases }); any corruption degrades to empty maps. */ +function readLastKnownCatalogFile(filePath) { try { const parsed = JSON.parse(readFileSync(filePath, "utf8")); - if (!parsed || parsed.version !== LAST_KNOWN_STORE_VERSION) return {}; - return parsed.entries && typeof parsed.entries === "object" ? parsed.entries : {}; + if (!parsed || parsed.version !== LAST_KNOWN_STORE_VERSION) { + return { entries: {}, aliases: {} }; + } + const aliases = parsed.aliases && typeof parsed.aliases === "object" && !Array.isArray(parsed.aliases) + ? parsed.aliases + : {}; + return { + entries: parsed.entries && typeof parsed.entries === "object" ? parsed.entries : {}, + aliases, + }; } catch { - return {}; + return { entries: {}, aliases: {} }; } } +/** Read the whole store; any corruption or absence degrades to {}. */ +function readLastKnownCatalogStore(filePath) { + return readLastKnownCatalogFile(filePath).entries; +} + +function pruneAliasesForEntries(aliases, entries) { + const pruned = {}; + const validPairs = Object.entries(aliases || {}).filter( + ([aliasKey, targetKey]) => typeof aliasKey === "string" + && typeof targetKey === "string" + && Object.prototype.hasOwnProperty.call(entries, targetKey), + ); + const capped = validPairs.slice(-LAST_KNOWN_MAX_ENTRIES); + for (const [aliasKey, targetKey] of capped) { + pruned[aliasKey] = targetKey; + } + return pruned; +} + /** * Load the persisted catalog for one cache key. Returns null unless the entry * carries a non-empty models list - the renderer has nothing to show otherwise. @@ -45,6 +72,45 @@ function readLastKnownCatalogEntry(filePath, cacheKey) { return entry; } +/** + * Resolve a persisted alias (for a bare command, Cursor sentinel, or + * previously normalized configured path) back to its exact persisted catalog + * cache key, or null if absent/evicted. + */ +function readLastKnownCatalogAlias(filePath, aliasKey) { + if (!filePath || !aliasKey) return null; + const { entries, aliases } = readLastKnownCatalogFile(filePath); + const targetKey = aliases[aliasKey]; + if (typeof targetKey === "string" && Object.prototype.hasOwnProperty.call(entries, targetKey)) { + return targetKey; + } + return null; +} + +/** + * Persist a mapping from a side-effect-free alias key (bare command or Cursor + * sentinel) to its resolved catalog cache key so cacheOnly hydration can + * recover the exact entry across restarts without PATH/auth probing or + * cross-matching explicit custom binaries. + */ +function writeLastKnownCatalogAlias(filePath, aliasKey, targetKey) { + if (!filePath || !aliasKey || !targetKey || aliasKey === targetKey) return false; + try { + const { entries, aliases } = readLastKnownCatalogFile(filePath); + if (!Object.prototype.hasOwnProperty.call(entries, targetKey)) return false; + if (aliases[aliasKey] === targetKey) return false; + const nextAliases = pruneAliasesForEntries({ ...aliases, [aliasKey]: targetKey }, entries); + mkdirSync(path.dirname(filePath), { recursive: true }); + writeFileSync( + filePath, + `${JSON.stringify({ version: LAST_KNOWN_STORE_VERSION, entries, aliases: nextAliases }, null, 2)}\n`, + ); + return true; + } catch { + return false; + } +} + /** * Refresh the persisted current id for one cache key without replacing the * persisted models list. Current-only catalogs (models: [] with a valid @@ -56,7 +122,7 @@ function readLastKnownCatalogEntry(filePath, cacheKey) { function refreshLastKnownCatalogCurrentId(filePath, cacheKey, currentModelId) { if (!filePath || !cacheKey || !currentModelId) return false; try { - const entries = readLastKnownCatalogStore(filePath); + const { entries, aliases } = readLastKnownCatalogFile(filePath); const entry = entries[cacheKey]; if (!entry || !Array.isArray(entry.models) || entry.models.length === 0) return false; if (entry.currentModelId === currentModelId) return false; @@ -78,7 +144,11 @@ function refreshLastKnownCatalogCurrentId(filePath, cacheKey, currentModelId) { models.push({ id: currentModelId, name: currentModelId }); } entries[cacheKey] = { ...entry, models, currentModelId }; - writeFileSync(filePath, `${JSON.stringify({ version: LAST_KNOWN_STORE_VERSION, entries }, null, 2)}\n`); + const nextAliases = pruneAliasesForEntries(aliases, entries); + writeFileSync( + filePath, + `${JSON.stringify({ version: LAST_KNOWN_STORE_VERSION, entries, aliases: nextAliases }, null, 2)}\n`, + ); return true; } catch { return false; @@ -110,7 +180,7 @@ function writeLastKnownCatalogEntry(filePath, cacheKey, { backend, models, curre } } try { - const entries = readLastKnownCatalogStore(filePath); + const { entries, aliases } = readLastKnownCatalogFile(filePath); entries[cacheKey] = { backend: String(backend || ""), models: trimmedModels, @@ -125,8 +195,12 @@ function writeLastKnownCatalogEntry(filePath, cacheKey, { backend, models, curre while (orderedKeys.length > LAST_KNOWN_MAX_ENTRIES) { delete entries[orderedKeys.shift()]; } + const nextAliases = pruneAliasesForEntries(aliases, entries); mkdirSync(path.dirname(filePath), { recursive: true }); - writeFileSync(filePath, `${JSON.stringify({ version: LAST_KNOWN_STORE_VERSION, entries }, null, 2)}\n`); + writeFileSync( + filePath, + `${JSON.stringify({ version: LAST_KNOWN_STORE_VERSION, entries, aliases: nextAliases }, null, 2)}\n`, + ); return true; } catch { return false; @@ -138,8 +212,10 @@ module.exports = { LAST_KNOWN_MAX_ENTRIES, LAST_KNOWN_MAX_MODELS, buildLastKnownCatalogPath, + readLastKnownCatalogAlias, readLastKnownCatalogEntry, readLastKnownCatalogStore, refreshLastKnownCatalogCurrentId, + writeLastKnownCatalogAlias, writeLastKnownCatalogEntry, }; diff --git a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs index 5af6c28e9..436416ccc 100644 --- a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs +++ b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs @@ -16,8 +16,11 @@ const codebuddyDriver = require("./codebuddyDriver.cjs"); const { OPENCODE_SERVER_START_TIMEOUT_MS } = require("./opencodeDriver.cjs"); const { buildLastKnownCatalogPath, + readLastKnownCatalogAlias, readLastKnownCatalogEntry, + readLastKnownCatalogStore, refreshLastKnownCatalogCurrentId, + writeLastKnownCatalogAlias, writeLastKnownCatalogEntry, } = require("./modelCatalogLastKnown.cjs"); @@ -31,6 +34,8 @@ const VALID_BACKENDS = new Set(listBackends()); // (issue #2184). const MODEL_CACHE_TTL_MS = 5 * 60 * 1000; const MODEL_CACHE_MAX_ENTRIES = 32; +const MODEL_CATALOG_MAX_AGE_MS = 12 * 60 * 60 * 1000; +const MODEL_CATALOG_RETRY_MS = 15 * 60 * 1000; const MODEL_LIST_TIMEOUT_MS = 10000; // Per-backend overrides for the catalog budget above. MiMo cold-boots a // dedicated `mimo serve` process for every catalog pull (unlike OpenCode's @@ -39,6 +44,9 @@ const MODEL_LIST_TIMEOUT_MS = 10000; const MODEL_LIST_TIMEOUT_OVERRIDES_MS = { mimo: 30_000 }; const sdkModelCache = new Map(); const sdkModelInFlight = new Map(); +const sdkModelRefreshFailures = new Map(); +const sdkModelKeyAliases = new Map(); +const cursorCliBinCache = new Map(); const { parseSdkSessionIdentity: parseSdkSessionIdentityPayload, normalizeSdkRuntime, @@ -141,11 +149,15 @@ const SDK_MODEL_CACHE_ENV_KEYS = [ // catalog + server teardown) instead of aborting mid-IPC. const MODEL_LIST_DEADLINE_HEADROOM_MS = 1_000; -function buildSdkModelCacheKey(backendKey, binPath, env, runtime = "sdk") { +function buildSdkModelEnvHash(env) { const envFingerprint = SDK_MODEL_CACHE_ENV_KEYS .map((key) => `${key}=${env?.[key] == null ? "" : String(env[key])}`) .join("\u0000"); - const envHash = createHash("sha256").update(envFingerprint).digest("hex"); + return createHash("sha256").update(envFingerprint).digest("hex"); +} + +function buildSdkModelCacheKey(backendKey, binPath, env, runtime = "sdk") { + const envHash = buildSdkModelEnvHash(env); return [String(backendKey || ""), String(binPath || ""), String(runtime || "sdk"), envHash].join("\u0000"); } @@ -223,6 +235,11 @@ function remapLastKnownCurrentModelId(lastKnown) { : lastKnown.models[0]?.id ?? null; } +function isFreshModelCatalog(catalog) { + const fetchedAtMs = Date.parse(catalog?.fetchedAt || ""); + return Number.isFinite(fetchedAtMs) && Date.now() - fetchedAtMs < MODEL_CATALOG_MAX_AGE_MS; +} + /** * Fetch a runtime model catalog for one SDK backend. For Codex on the default * `sdk` runtime, the codex-sdk exposes no model catalog (its driver always @@ -447,7 +464,7 @@ function resolveRealCliPath(cliPath, realpath = realpathSync) { try { return realpath(cliPath); } catch { return cliPath; } } -function normalizeConfiguredCommandPath(command, normalizeCliPathForPlatform) { +function normalizeConfiguredCommandPath(command, normalizeCliPathForPlatform, { validate = true } = {}) { const raw = String(command || "").trim(); const pathLike = raw.includes("/") || raw.includes("\\") || /^[a-z]:/i.test(raw); if (!raw || !pathLike) { @@ -457,6 +474,7 @@ function normalizeConfiguredCommandPath(command, normalizeCliPathForPlatform) { ? normalizeCliPathForPlatform(raw) : raw; if (!normalized) { + if (!validate) return raw; throw new Error(`Agent CLI path not found: ${raw}`); } return normalized; @@ -484,9 +502,14 @@ function resolveConfiguredSdkPath({ function resolveSdkBackendBinPath({ backendKey, configuredCommand, shellEnv, env, resolveCliFromPath, normalizeCliPathForPlatform, resolveSdkBinPath, resolveClaudeCodeExecutableForSdk, resolveCodexExecutableForSdk, - resolveCodebuddyExecutableForSdk, realpath = realpathSync, + resolveCodebuddyExecutableForSdk, realpath = realpathSync, allowPathProbe = true, + validateConfiguredPath = true, }) { - const configuredPath = normalizeConfiguredCommandPath(configuredCommand, normalizeCliPathForPlatform); + const configuredPath = normalizeConfiguredCommandPath( + configuredCommand, + normalizeCliPathForPlatform, + { validate: validateConfiguredPath }, + ); if (configuredPath) { return resolveConfiguredSdkPath({ backendKey, @@ -498,9 +521,18 @@ function resolveSdkBackendBinPath({ }); } + const normalizeOptionalEnvPath = (rawValue) => { + const raw = String(rawValue || "").trim(); + if (!raw) return null; + const normalized = typeof normalizeCliPathForPlatform === "function" + ? normalizeCliPathForPlatform(raw) + : raw; + return normalized || (!validateConfiguredPath ? raw : null); + }; + if (backendKey === "codebuddy") { - const configuredEnvPath = normalizeCliPathForPlatform?.(env?.CODEBUDDY_CODE_PATH); - const rawPath = configuredEnvPath || resolveCliFromPath(backendKey, shellEnv) || undefined; + const configuredEnvPath = normalizeOptionalEnvPath(env?.CODEBUDDY_CODE_PATH); + const rawPath = configuredEnvPath || (allowPathProbe ? resolveCliFromPath(backendKey, shellEnv) : null) || undefined; if (!rawPath) return undefined; const realPath = resolveRealCliPath(rawPath, realpath); // On Windows the discovered path is an npm shim (codebuddy.cmd/.ps1) that the @@ -513,16 +545,36 @@ function resolveSdkBackendBinPath({ return sdkPath || undefined; } if (backendKey === "opencode") { - const configuredEnvPath = normalizeCliPathForPlatform?.(env?.OPENCODE_BIN); - const rawPath = configuredEnvPath || resolveCliFromPath(backendKey, shellEnv) || undefined; + const configuredEnvPath = normalizeOptionalEnvPath(env?.OPENCODE_BIN); + const rawPath = configuredEnvPath || (allowPathProbe ? resolveCliFromPath(backendKey, shellEnv) : null) || undefined; return rawPath ? resolveRealCliPath(rawPath, realpath) : undefined; } if (backendKey === "mimo") { - const configuredEnvPath = normalizeCliPathForPlatform?.(env?.MIMOCODE_BIN || env?.MIMOCODE_BIN_PATH); - const rawPath = configuredEnvPath || resolveCliFromPath(backendKey, shellEnv) || undefined; + const configuredEnvPath = normalizeOptionalEnvPath(env?.MIMOCODE_BIN || env?.MIMOCODE_BIN_PATH); + const rawPath = configuredEnvPath || (allowPathProbe ? resolveCliFromPath(backendKey, shellEnv) : null) || undefined; return rawPath ? resolveRealCliPath(rawPath, realpath) : undefined; } - return resolveSdkBinPath?.(backendKey, shellEnv) || undefined; + return allowPathProbe ? (resolveSdkBinPath?.(backendKey, shellEnv) || undefined) : undefined; +} + +async function resolveSdkBackendBinPathAsync({ + backendKey, shellEnv, resolveCliFromPathAsync, resolveSdkBinPathAsync, + resolveCodebuddyExecutableForSdk, realpath = realpathSync, +}) { + if (backendKey === "codebuddy") { + const rawPath = await resolveCliFromPathAsync?.(backendKey, shellEnv) || undefined; + if (!rawPath) return undefined; + const realPath = resolveRealCliPath(rawPath, realpath); + const sdkPath = typeof resolveCodebuddyExecutableForSdk === "function" + ? resolveCodebuddyExecutableForSdk(realPath) + : realPath; + return sdkPath || undefined; + } + if (backendKey === "opencode" || backendKey === "mimo") { + const rawPath = await resolveCliFromPathAsync?.(backendKey, shellEnv) || undefined; + return rawPath ? resolveRealCliPath(rawPath, realpath) : undefined; + } + return await resolveSdkBinPathAsync?.(backendKey, shellEnv) || undefined; } function defaultWriteAttachmentToTemp(attachment) { @@ -1126,6 +1178,7 @@ function registerSdkStreamHandlers(ctx) { // Manual refresh (retry banner / picker refresh button) must always go // live; automatic loads follow the LKG-first policy below. const force = payload?.force === true; + const cacheOnly = payload?.cacheOnly === true; const backendKey = resolveBackendKey(sdkBackend); if (!backendKey) return { ok: false, error: `Unknown SDK backend: ${sdkBackend}` }; @@ -1135,7 +1188,7 @@ function registerSdkStreamHandlers(ctx) { return { ok: true, currentModelId: null, models: [] }; } const shellEnv = await getShellEnv(); - const normalizedAgentEnv = normalizeAgentEnv(requestedAgentEnv); + const normalizedAgentEnv = { ...(normalizeAgentEnv(requestedAgentEnv) || {}) }; const cursorAuthMode = normalizedAgentEnv.NETCATTY_CURSOR_AUTH_MODE === "cli-login" ? "cli-login" : "api-key"; @@ -1154,7 +1207,15 @@ function registerSdkStreamHandlers(ctx) { if (cursorAuthMode === "cli-login") { delete env.CURSOR_API_KEY; } - const binPath = resolveSdkBackendBinPath({ + let configuredPathError = null; + if (!cacheOnly) { + try { + normalizeConfiguredCommandPath(agentCommand, normalizeCliPathForPlatform, { validate: true }); + } catch (err) { + configuredPathError = err; + } + } + const explicitBinPath = resolveSdkBackendBinPath({ backendKey, configuredCommand: agentCommand, shellEnv, @@ -1165,74 +1226,318 @@ function registerSdkStreamHandlers(ctx) { resolveClaudeCodeExecutableForSdk, resolveCodexExecutableForSdk, resolveCodebuddyExecutableForSdk, + allowPathProbe: false, + validateConfiguredPath: false, }); - if (backendKey === "cursor" && cursorAuthMode === "cli-login") { - const looksLikeSentinel = !cursorCliBinPath - || cursorCliBinPath === "cursor" - || /(?:^|[/\\])cursor$/i.test(cursorCliBinPath); - if (looksLikeSentinel && typeof probeCursorCliAuth === "function") { - try { - const cliAuth = probeCursorCliAuth({ env: shellEnv }); - if (cliAuth?.binPath) cursorCliBinPath = cliAuth.binPath; - } catch { /* best effort */ } - } - if (!cursorCliBinPath) { - // Only `cursor-agent` — bare `agent` collides with other CLIs (e.g. Grok). - cursorCliBinPath = await resolveCliFromPathAsync?.("cursor-agent", shellEnv) - || null; - } - } + const binPath = cacheOnly || configuredPathError + ? explicitBinPath + : resolveSdkBackendBinPath({ + backendKey, + configuredCommand: agentCommand, + shellEnv, + env, + resolveCliFromPath, + normalizeCliPathForPlatform, + resolveSdkBinPath, + resolveClaudeCodeExecutableForSdk, + resolveCodexExecutableForSdk, + resolveCodebuddyExecutableForSdk, + allowPathProbe: true, + validateConfiguredPath: true, + }); const codexRuntime = backendKey === "codex" && requestedCodexRuntime === "app-server" ? "app-server" : "sdk"; + const runtimeKey = `${codexRuntime}:${cursorAuthMode}`; + const shouldCacheModels = shouldCacheSdkRuntimeModels(backendKey); + const lastKnownPath = resolveLastKnownCatalogPath(electronModule); + const initialCursorCliBinPath = cursorCliBinPath; + const isCursorCliLoginSentinel = backendKey === "cursor" + && cursorAuthMode === "cli-login" + && (!cursorCliBinPath + || cursorCliBinPath === "cursor" + || /(?:^|[/\\])cursor$/i.test(cursorCliBinPath)); + const rawConfiguredCommand = String(agentCommand || "").trim(); + const hasConfiguredPathLikeCommand = Boolean( + rawConfiguredCommand + && (rawConfiguredCommand.includes("/") || rawConfiguredCommand.includes("\\") || /^[a-z]:/i.test(rawConfiguredCommand)), + ); + const rawEnvBinPath = !hasConfiguredPathLikeCommand + ? (backendKey === "codebuddy" + ? String(env?.CODEBUDDY_CODE_PATH || "").trim() + : backendKey === "opencode" + ? String(env?.OPENCODE_BIN || "").trim() + : backendKey === "mimo" + ? String(env?.MIMOCODE_BIN || env?.MIMOCODE_BIN_PATH || "").trim() + : "") + : ""; + const needsResolvedKeyAlias = isCursorCliLoginSentinel + || !explicitBinPath + || hasConfiguredPathLikeCommand + || Boolean(rawEnvBinPath); + const pathHash = needsResolvedKeyAlias + ? createHash("sha256").update(String(shellEnv?.PATH || "")).digest("hex") + : null; + const aliasKey = needsResolvedKeyAlias + ? buildSdkModelCacheKey( + backendKey, + hasConfiguredPathLikeCommand && !isCursorCliLoginSentinel + ? `alias:configured:${rawConfiguredCommand}` + : rawEnvBinPath && !isCursorCliLoginSentinel + ? `alias:env-bin:${rawEnvBinPath}` + : `alias:${rawConfiguredCommand}:${String(initialCursorCliBinPath || "")}:${pathHash}`, + env, + runtimeKey, + ) + : null; + const recordResolvedKeyAlias = (targetKey) => { + if (!aliasKey || !targetKey || targetKey === aliasKey) return; + setSdkModelCacheEntry(sdkModelKeyAliases, aliasKey, { + at: Date.now(), + targetKey, + }, { ttlMs: MODEL_CATALOG_MAX_AGE_MS }); + writeLastKnownCatalogAlias(lastKnownPath, aliasKey, targetKey); + }; + const cursorBinCacheKey = isCursorCliLoginSentinel + ? createHash("sha256").update([ + String(shellEnv?.PATH || ""), + String(shellEnv?.HOME || ""), + String(shellEnv?.USERPROFILE || ""), + String(initialCursorCliBinPath || ""), + ].join("\u0000")).digest("hex") + : null; + if (isCursorCliLoginSentinel && !force) { + const cachedCursorBin = getSdkModelCacheEntry(cursorCliBinCache, cursorBinCacheKey, { + ttlMs: MODEL_CATALOG_MAX_AGE_MS, + }); + if (cachedCursorBin?.binPath) { + cursorCliBinPath = cachedCursorBin.binPath; + } + } // claude/copilot/opencode enumerate models via the SDK; codex's sdk // driver returns [] and falls back to the App Server catalog (see // fetchSdkModelCatalog). Cache + in-flight coalescing avoid spawn // storms (#2184). - const cacheKey = buildSdkModelCacheKey( + const buildCacheKey = () => buildSdkModelCacheKey( backendKey, cursorAuthMode === "cli-login" ? (cursorCliBinPath || binPath) : binPath, env, - `${codexRuntime}:${cursorAuthMode}`, + runtimeKey, ); - const shouldCacheModels = shouldCacheSdkRuntimeModels(backendKey); - const cached = !force && shouldCacheModels ? getSdkModelCacheEntry(sdkModelCache, cacheKey) : null; - if (cached) { - // A cache hit replays the live fetch that populated the entry, so it - // keeps the live provenance (and the original fetchedAt). - return { - ok: true, - currentModelId: cached.currentModelId || null, - models: cached.models, - ...(cached.fetchedAt ? { source: "live", fetchedAt: cached.fetchedAt } : {}), - }; + const tryServeCachedCatalog = (key) => { + const cached = !force && shouldCacheModels ? getSdkModelCacheEntry(sdkModelCache, key) : null; + if (cached) { + // A cache hit replays the live fetch that populated the entry, so it + // keeps the live provenance (and the original fetchedAt). + return { + value: { + ok: true, + currentModelId: cached.currentModelId || null, + models: cached.models, + ...(cached.fetchedAt ? { source: "live", fetchedAt: cached.fetchedAt } : {}), + }, + }; + } + + // In-flight entries are live fetches, so forced refreshes can share + // them without replaying either memory or persisted cache results. + const existing = sdkModelInFlight.get(key); + if (existing && !cacheOnly) return { promise: existing }; + + // Normal loads reuse a fresh catalog and revalidate stale ones on use. + // A failed revalidation is briefly cached to avoid repeat queries when + // switching panels; manual refresh bypasses the retry interval. + if (!force || cacheOnly) { + const failedRefresh = getSdkModelCacheEntry(sdkModelRefreshFailures, key, { + ttlMs: MODEL_CATALOG_RETRY_MS, + }); + if (failedRefresh) return { value: failedRefresh.result }; + + const lastKnown = readLastKnownCatalogEntry(lastKnownPath, key); + if (lastKnown && (cacheOnly || isFreshModelCatalog(lastKnown))) { + console.debug( + `[sdk] list-models(${backendKey}) serving last-known-good catalog from ${lastKnown.fetchedAt} without a live fetch`, + ); + return { + value: { + ok: true, + currentModelId: remapLastKnownCurrentModelId(lastKnown), + models: lastKnown.models, + source: "last-known-good", + fetchedAt: lastKnown.fetchedAt, + }, + }; + } + } + return null; + }; + + const resolveAliasedKey = () => { + if (!aliasKey) return null; + return getSdkModelCacheEntry(sdkModelKeyAliases, aliasKey, { + ttlMs: MODEL_CATALOG_MAX_AGE_MS, + })?.targetKey || readLastKnownCatalogAlias(lastKnownPath, aliasKey); + }; + const cacheCursorBinFromKey = (targetKey) => { + if (!isCursorCliLoginSentinel || !cursorBinCacheKey || !targetKey) return; + const resolvedBin = targetKey.split("\u0000")[1] || ""; + if (!resolvedBin || resolvedBin === "cursor" || /(?:^|[/\\])cursor$/i.test(resolvedBin)) return; + setSdkModelCacheEntry(cursorCliBinCache, cursorBinCacheKey, { + at: Date.now(), + binPath: resolvedBin, + }, { ttlMs: MODEL_CATALOG_MAX_AGE_MS }); + }; + + if (cacheOnly) { + const aliasedKey = resolveAliasedKey(); + if (aliasedKey) { + const aliasedImmediate = tryServeCachedCatalog(aliasedKey); + if (aliasedImmediate) { + if (aliasedImmediate.value?.source === "live" || isFreshModelCatalog(aliasedImmediate.value)) { + cacheCursorBinFromKey(aliasedKey); + } + return aliasedImmediate.value; + } + } + const exactKey = buildCacheKey(); + const exactImmediate = tryServeCachedCatalog(exactKey); + if (exactImmediate) return exactImmediate.value; + // Backward-compatible exact lookup for pre-alias v1 stores: only when + // persisted entries exist for this backend+runtime, resolve the + // executable asynchronously (never blocking on sync PATH lookup and + // never spawning Cursor status probes) and match only its exact key. + if (isCursorCliLoginSentinel || !explicitBinPath) { + const hasStoredEntriesForBackend = Object.keys(readLastKnownCatalogStore(lastKnownPath)).some((key) => { + const parts = key.split("\u0000"); + return parts.length === 4 && parts[0] === backendKey && parts[2] === runtimeKey; + }); + if (hasStoredEntriesForBackend) { + const asyncBinPath = isCursorCliLoginSentinel + ? await resolveCliFromPathAsync?.("cursor-agent", shellEnv) || null + : await resolveSdkBackendBinPathAsync({ + backendKey, + shellEnv, + resolveCliFromPathAsync: typeof resolveCliFromPathAsync === "function" ? resolveCliFromPathAsync : undefined, + resolveSdkBinPathAsync: typeof resolveSdkBinPathAsync === "function" ? resolveSdkBinPathAsync : undefined, + resolveCodebuddyExecutableForSdk, + }); + if (asyncBinPath) { + const asyncKey = buildSdkModelCacheKey(backendKey, asyncBinPath, env, runtimeKey); + const asyncImmediate = tryServeCachedCatalog(asyncKey); + if (asyncImmediate) { + if (asyncImmediate.value?.source === "live" || isFreshModelCatalog(asyncImmediate.value)) { + cacheCursorBinFromKey(asyncKey); + } + recordResolvedKeyAlias(asyncKey); + return asyncImmediate.value; + } + } + } + } + return { ok: true, currentModelId: null, models: [] }; } - // In-flight entries are live fetches, so forced refreshes can share - // them without replaying either memory or persisted cache results. - const existing = sdkModelInFlight.get(cacheKey); - if (existing) return await existing; - - const lastKnownPath = resolveLastKnownCatalogPath(electronModule); - // LKG-first policy: a non-force load never spends the live-fetch budget - // while a persisted catalog exists — the picker hydrates instantly from - // disk (source 'last-known-good', persisted fetchedAt for the chip) and - // the user refreshes manually. Only a cache miss with no persisted - // entry (fresh install, new profile fingerprint) goes live - // automatically. force skips this branch and always attempts live. - if (!force) { - const lastKnown = readLastKnownCatalogEntry(lastKnownPath, cacheKey); + let cacheKey = (!binPath && !isCursorCliLoginSentinel) + ? (resolveAliasedKey() || buildCacheKey()) + : buildCacheKey(); + if (configuredPathError) { + const fallbackKey = resolveAliasedKey() || cacheKey; + const fallbackImmediate = tryServeCachedCatalog(fallbackKey); + if (fallbackImmediate) { + const result = fallbackImmediate.promise ? await fallbackImmediate.promise : fallbackImmediate.value; + recordResolvedKeyAlias(fallbackKey); + return result; + } + const lastKnown = readLastKnownCatalogEntry(lastKnownPath, fallbackKey); if (lastKnown) { console.debug( - `[sdk] list-models(${backendKey}) serving last-known-good catalog from ${lastKnown.fetchedAt} without a live fetch`, + `[sdk] list-models(${backendKey}) unavailable, serving last-known-good catalog from ${lastKnown.fetchedAt}`, ); - return { + const result = { ok: true, currentModelId: remapLastKnownCurrentModelId(lastKnown), models: lastKnown.models, + warning: `${configuredPathError?.message || String(configuredPathError)} — serving the last-known-good catalog fetched at ${lastKnown.fetchedAt}`, source: "last-known-good", fetchedAt: lastKnown.fetchedAt, }; + if (!isFreshModelCatalog(lastKnown)) { + setSdkModelCacheEntry(sdkModelRefreshFailures, fallbackKey, { at: Date.now(), result }, { + ttlMs: MODEL_CATALOG_RETRY_MS, + }); + } + recordResolvedKeyAlias(fallbackKey); + return result; + } + throw configuredPathError; + } + const immediate = tryServeCachedCatalog(cacheKey); + if (immediate) { + const result = immediate.promise ? await immediate.promise : immediate.value; + recordResolvedKeyAlias(cacheKey); + return result; + } + + if (isCursorCliLoginSentinel) { + const stillSentinel = !cursorCliBinPath + || cursorCliBinPath === "cursor" + || /(?:^|[/\\])cursor$/i.test(cursorCliBinPath); + if (stillSentinel && !force) { + const aliasedKey = resolveAliasedKey(); + if (aliasedKey && aliasedKey !== cacheKey) { + const aliasedImmediate = tryServeCachedCatalog(aliasedKey); + if (aliasedImmediate) { + const result = aliasedImmediate.promise ? await aliasedImmediate.promise : aliasedImmediate.value; + cacheCursorBinFromKey(aliasedKey); + recordResolvedKeyAlias(aliasedKey); + return result; + } + } + } + // Any non-cached load (missing catalog, stale >=12h revalidation, or + // forced refresh) re-probes the sentinel so a moved cursor-agent + // binary is discovered automatically instead of staying pinned. + let resolvedCursorBin = null; + if (typeof probeCursorCliAuth === "function") { + try { + const cliAuth = await probeCursorCliAuth({ env: shellEnv }); + if (cliAuth?.binPath) resolvedCursorBin = cliAuth.binPath; + } catch { /* best effort */ } + } + if (!resolvedCursorBin && (!cursorCliBinPath || stillSentinel)) { + // Only `cursor-agent` — bare `agent` collides with other CLIs (e.g. Grok). + resolvedCursorBin = await resolveCliFromPathAsync?.("cursor-agent", shellEnv) + || null; + } + if (resolvedCursorBin) { + cursorCliBinPath = resolvedCursorBin; + setSdkModelCacheEntry(cursorCliBinCache, cursorBinCacheKey, { + at: Date.now(), + binPath: resolvedCursorBin, + }, { ttlMs: MODEL_CATALOG_MAX_AGE_MS }); + } else { + cursorCliBinCache.delete(cursorBinCacheKey); + } + const resolvedCacheKey = buildCacheKey(); + if (resolvedCacheKey !== cacheKey) { + cacheKey = resolvedCacheKey; + const resolvedImmediate = tryServeCachedCatalog(cacheKey); + if (resolvedImmediate) { + const result = resolvedImmediate.promise ? await resolvedImmediate.promise : resolvedImmediate.value; + recordResolvedKeyAlias(cacheKey); + return result; + } + } else if (!resolvedCursorBin) { + const fallbackAliasedKey = resolveAliasedKey(); + if (fallbackAliasedKey && fallbackAliasedKey !== cacheKey) { + cacheKey = fallbackAliasedKey; + const fallbackImmediate = tryServeCachedCatalog(cacheKey); + if (fallbackImmediate) { + const result = fallbackImmediate.promise ? await fallbackImmediate.promise : fallbackImmediate.value; + recordResolvedKeyAlias(cacheKey); + return result; + } + } } } const loadPromise = (async () => { @@ -1263,6 +1568,44 @@ function registerSdkStreamHandlers(ctx) { abortController, ); const { currentModelId, models } = normalizeSdkListModelsResult(raw); + if (models.length === 0 && currentModelId && !force) { + const existingLastKnown = readLastKnownCatalogEntry(lastKnownPath, cacheKey); + if (existingLastKnown) { + // Automatic stale-catalog revalidation returned only a current + // model id without catalog rows: treat it as incomplete so the + // picker keeps its saved choices and original catalog age while + // honoring the reported current id. + refreshLastKnownCatalogCurrentId(lastKnownPath, cacheKey, currentModelId); + const preserved = readLastKnownCatalogEntry(lastKnownPath, cacheKey) || existingLastKnown; + const hasCurrentRow = preserved.models.some((model) => model && ( + model.id === currentModelId + || (Array.isArray(model.thinkingLevels) + && model.thinkingLevels.some((level) => `${model.id}/${level}` === currentModelId)) + )); + const preservedModels = hasCurrentRow + ? preserved.models + : [...preserved.models, { id: currentModelId, name: currentModelId }]; + const result = { + ok: true, + currentModelId: remapLastKnownCurrentModelId({ + ...preserved, + models: preservedModels, + currentModelId, + }), + models: preservedModels, + source: "last-known-good", + fetchedAt: preserved.fetchedAt, + }; + if (!isFreshModelCatalog(preserved)) { + setSdkModelCacheEntry(sdkModelRefreshFailures, cacheKey, { at: Date.now(), result }, { + ttlMs: MODEL_CATALOG_RETRY_MS, + }); + } + recordResolvedKeyAlias(cacheKey); + return result; + } + } + sdkModelRefreshFailures.delete(cacheKey); const fetchedAt = new Date().toISOString(); // Do not cache degraded empty catalogs: listOpenCodeModels and // other drivers often return [] on timeout/startup failure, and @@ -1280,6 +1623,7 @@ function registerSdkStreamHandlers(ctx) { models, currentModelId, }); + recordResolvedKeyAlias(cacheKey); } else if (currentModelId) { // A current-only success still advertises a usable selection. // Keep previous rows when available; otherwise persist that @@ -1293,6 +1637,7 @@ function registerSdkStreamHandlers(ctx) { currentModelId, }); } + recordResolvedKeyAlias(cacheKey); } return { ok: true, @@ -1316,7 +1661,7 @@ function registerSdkStreamHandlers(ctx) { console.debug( `[sdk] list-models(${backendKey}) unavailable, serving last-known-good catalog from ${lastKnown.fetchedAt}`, ); - return { + const result = { ok: true, currentModelId: remapLastKnownCurrentModelId(lastKnown), models: lastKnown.models, @@ -1324,6 +1669,13 @@ function registerSdkStreamHandlers(ctx) { source: "last-known-good", fetchedAt: lastKnown.fetchedAt, }; + if (!isFreshModelCatalog(lastKnown)) { + setSdkModelCacheEntry(sdkModelRefreshFailures, cacheKey, { at: Date.now(), result }, { + ttlMs: MODEL_CATALOG_RETRY_MS, + }); + } + recordResolvedKeyAlias(cacheKey); + return result; } console.debug(`[sdk] list-models(${backendKey}) unavailable, using curated presets`); return { @@ -1652,6 +2004,9 @@ function registerSdkStreamHandlers(ctx) { ctx.sdkRequestSessions = sdkRequestSessions; ctx.sdkRequestRuntimes = sdkRequestRuntimes; ctx.sdkModelCache = sdkModelCache; // exposed for catalog tests + ctx.sdkModelRefreshFailures = sdkModelRefreshFailures; // exposed for catalog tests + ctx.sdkModelKeyAliases = sdkModelKeyAliases; // exposed for catalog tests + ctx.cursorCliBinCache = cursorCliBinCache; // exposed for catalog tests ctx.codexAppServerRuntime = codexAppServerRuntime; ctx.codebuddySessionManager = codebuddySessionManager; } diff --git a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.test.cjs b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.test.cjs index 68fa06ad9..6f05509d1 100644 --- a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.test.cjs +++ b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.test.cjs @@ -1920,6 +1920,765 @@ test("list-models serves the persisted catalog without a live fetch on a non-for } }); +test("list-models refreshes a persisted catalog on use at the 12-hour boundary", async (t) => { + const { getDriver } = require("./index.cjs"); + const now = Date.parse("2026-11-18T00:00:00Z"); + const maxAge = 12 * 60 * 60 * 1000; + t.mock.timers.enable({ apis: ["Date"], now }); + const { handlers, ctx, cleanup } = makeLastKnownCtx(); + try { + const driver = getDriver("claude"); + t.mock.method(driver, "listModels", async () => [{ id: "old", name: "Old" }]); + const load = () => handlers.get("netcatty:ai:sdk-agent:list-models")( + { sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-expiry" }, + ); + await load(); + ctx.sdkModelCache.clear(); + t.mock.timers.setTime(now + maxAge - 1); + assert.equal((await load()).source, "last-known-good"); + assert.equal(driver.listModels.mock.callCount(), 1); + + t.mock.timers.setTime(now + maxAge); + driver.listModels.mock.mockImplementation(async () => [{ id: "new", name: "New" }]); + const loadCached = () => handlers.get("netcatty:ai:sdk-agent:list-models")( + { sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-expiry", cacheOnly: true }, + ); + const cached = await loadCached(); + assert.equal(cached.source, "last-known-good"); + assert.deepEqual(cached.models.map(({ id }) => id), ["old"]); + assert.equal(driver.listModels.mock.callCount(), 1); + const [first, second] = await Promise.all([load(), load()]); + assert.equal(first.source, "live"); + assert.deepEqual(first.models.map(({ id }) => id), ["new"]); + assert.deepEqual(second, first); + assert.equal(driver.listModels.mock.callCount(), 2); + ctx.sdkModelCache.clear(); + assert.equal((await load()).models[0].id, "new"); + assert.equal(driver.listModels.mock.callCount(), 2); + } finally { + cleanup(); + } +}); + +test("list-models keeps stale models after failure and limits automatic retries", async (t) => { + const { getDriver } = require("./index.cjs"); + const now = Date.parse("2026-11-18T00:00:00Z"); + const expiredAt = now + 12 * 60 * 60 * 1000; + const retryAt = expiredAt + 15 * 60 * 1000; + t.mock.timers.enable({ apis: ["Date"], now }); + const { handlers, cleanup } = makeLastKnownCtx(); + try { + const driver = getDriver("claude"); + t.mock.method(driver, "listModels", async () => [{ id: "old", name: "Old" }]); + const load = (force = false) => handlers.get("netcatty:ai:sdk-agent:list-models")( + { sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-retry", force }, + ); + const seeded = await load(); + t.mock.timers.setTime(expiredAt); + driver.listModels.mock.mockImplementation(async () => { throw new Error("offline"); }); + const fallback = await load(); + assert.equal(fallback.source, "last-known-good"); + assert.deepEqual(fallback.models, seeded.models); + assert.equal(fallback.fetchedAt, seeded.fetchedAt); + assert.match(fallback.warning, /offline/); + + t.mock.timers.setTime(retryAt - 1); + assert.deepEqual(await load(), fallback); + assert.equal(driver.listModels.mock.callCount(), 2); + t.mock.timers.setTime(retryAt); + assert.deepEqual(await load(), fallback); + assert.equal(driver.listModels.mock.callCount(), 3); + + driver.listModels.mock.mockImplementation(async () => [{ id: "new", name: "New" }]); + assert.equal((await load(true)).models[0].id, "new"); + assert.equal((await load()).models[0].id, "new"); + assert.equal(driver.listModels.mock.callCount(), 4); + } finally { + cleanup(); + } +}); + +test("list-models preserves saved rows, original timestamp, and retry interval when automatic stale refresh returns only currentModelId", async (t) => { + const { getDriver } = require("./index.cjs"); + const now = Date.parse("2026-11-18T00:00:00Z"); + const expiredAt = now + 12 * 60 * 60 * 1000; + const retryAt = expiredAt + 15 * 60 * 1000; + t.mock.timers.enable({ apis: ["Date"], now }); + const { handlers, catalogFile, cleanup } = makeLastKnownCtx(); + try { + const driver = getDriver("claude"); + const initialModels = [ + { id: "old-a", name: "Old A" }, + { id: "old-b", name: "Old B" }, + ]; + t.mock.method(driver, "listModels", async () => ({ + currentModelId: "old-a", + models: initialModels, + })); + const load = (force = false) => handlers.get("netcatty:ai:sdk-agent:list-models")( + { sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-stale-current-only", force }, + ); + const seeded = await load(); + assert.equal(seeded.source, "live"); + assert.deepEqual(seeded.models, initialModels); + + t.mock.timers.setTime(expiredAt); + driver.listModels.mock.mockImplementation(async () => ({ + currentModelId: "old-b", + models: [], + })); + const preserved = await load(); + assert.equal(driver.listModels.mock.callCount(), 2); + assert.equal(preserved.ok, true); + assert.equal(preserved.source, "last-known-good"); + assert.equal(preserved.fetchedAt, seeded.fetchedAt); + assert.equal(preserved.currentModelId, "old-b"); + assert.deepEqual(preserved.models, initialModels); + assert.equal(preserved.warning, undefined); + + const [cacheKey] = Object.keys(readLastKnownCatalogStore(catalogFile)); + const persisted = readLastKnownCatalogEntry(catalogFile, cacheKey); + assert.equal(persisted.fetchedAt, seeded.fetchedAt); + assert.equal(persisted.currentModelId, "old-b"); + assert.deepEqual(persisted.models, initialModels); + + // Degraded retry interval applies because the full catalog was not refreshed. + t.mock.timers.setTime(retryAt - 1); + assert.deepEqual(await load(), preserved); + assert.equal(driver.listModels.mock.callCount(), 2); + + // After the retry interval, automatic refresh runs again; an unlisted + // current-only id is synthesized without discarding the saved rows or age. + t.mock.timers.setTime(retryAt); + driver.listModels.mock.mockImplementation(async () => ({ + currentModelId: "new-current", + models: [], + })); + const retried = await load(); + assert.equal(driver.listModels.mock.callCount(), 3); + assert.equal(retried.source, "last-known-good"); + assert.equal(retried.fetchedAt, seeded.fetchedAt); + assert.equal(retried.currentModelId, "new-current"); + assert.deepEqual(retried.models, [ + ...initialModels, + { id: "new-current", name: "new-current" }, + ]); + + // A full catalog response replaces the stale rows and clears retry state. + const freshModels = [ + { id: "live-1", name: "Live 1" }, + { id: "live-2", name: "Live 2" }, + ]; + driver.listModels.mock.mockImplementation(async () => ({ + currentModelId: "live-1", + models: freshModels, + })); + const forced = await load(true); + assert.equal(forced.source, "live"); + assert.equal(forced.currentModelId, "live-1"); + assert.deepEqual(forced.models, freshModels); + assert.notEqual(forced.fetchedAt, seeded.fetchedAt); + assert.equal(driver.listModels.mock.callCount(), 4); + assert.deepEqual(await load(), forced); + assert.equal(driver.listModels.mock.callCount(), 4); + } finally { + cleanup(); + } +}); + +test("list-models cacheOnly returns empty without invoking the driver on a cold cache", async (t) => { + const { getDriver } = require("./index.cjs"); + const { handlers, cleanup } = makeLastKnownCtx(); + try { + const driver = getDriver("claude"); + t.mock.method(driver, "listModels", async () => { + throw new Error("cacheOnly must not invoke driver.listModels"); + }); + const result = await handlers.get("netcatty:ai:sdk-agent:list-models")( + { sender: {} }, + { sdkBackend: "claude", agentCommand: "/test/lkg-cache-only-cold", cacheOnly: true }, + ); + assert.deepEqual(result, { ok: true, currentModelId: null, models: [] }); + assert.equal(driver.listModels.mock.callCount(), 0); + } finally { + cleanup(); + } +}); + +test("list-models skips Cursor CLI probes during cacheOnly hydration and warm/fresh picker rechecks", async (t) => { + const { getDriver } = require("./index.cjs"); + let probeCalls = 0; + let pathResolveCalls = 0; + const { handlers, ctx, cleanup } = makeLastKnownCtx({ + getShellEnv: async () => ({ PATH: "/test/cursor-probe-skip-bin" }), + probeCursorCliAuth: async () => { + probeCalls += 1; + return { authenticated: true, authSource: "cli-login", email: "a@b.c", binPath: "/test/cursor-probe-skip-bin/cursor-agent" }; + }, + resolveCliFromPathAsync: async () => { + pathResolveCalls += 1; + return "/test/cursor-probe-skip-bin/cursor-agent"; + }, + }); + ctx.cursorCliBinCache.clear(); + try { + const driver = getDriver("cursor"); + t.mock.method(driver, "listModels", async () => [ + { id: "auto", name: "Auto" }, + { id: "claude-4.5-sonnet", name: "Claude 4.5 Sonnet" }, + ]); + const listModels = handlers.get("netcatty:ai:sdk-agent:list-models"); + const request = { + sdkBackend: "cursor", + agentCommand: "cursor", + agentEnv: { NETCATTY_CURSOR_AUTH_MODE: "cli-login", NETCATTY_CURSOR_CLI_BIN: "cursor" }, + }; + + // 1. Cold cacheOnly hydration must not spawn Cursor probes or listModels. + const coldHydration = await listModels({ sender: {} }, { ...request, cacheOnly: true }); + assert.deepEqual(coldHydration, { ok: true, currentModelId: null, models: [] }); + assert.equal(probeCalls, 0); + assert.equal(pathResolveCalls, 0); + assert.equal(driver.listModels.mock.callCount(), 0); + + // 2. First live refresh probes once and caches both the resolved binary and catalog. + const live = await listModels({ sender: {} }, request); + assert.equal(live.source, "live"); + assert.equal(live.models.length, 2); + assert.equal(probeCalls, 1); + assert.equal(driver.listModels.mock.callCount(), 1); + + // 3. Repeated picker-open rechecks (warm memory cache, then fresh disk LKG) + // and cacheOnly hydration must not re-probe Cursor. + const warmRecheck = await listModels({ sender: {} }, request); + assert.equal(warmRecheck.source, "live"); + assert.equal(probeCalls, 1); + assert.equal(driver.listModels.mock.callCount(), 1); + + ctx.sdkModelCache.clear(); + const freshLkgRecheck = await listModels({ sender: {} }, request); + assert.equal(freshLkgRecheck.source, "last-known-good"); + assert.equal(freshLkgRecheck.models.length, 2); + assert.equal(probeCalls, 1); + assert.equal(driver.listModels.mock.callCount(), 1); + + const warmCacheOnly = await listModels({ sender: {} }, { ...request, cacheOnly: true }); + assert.equal(warmCacheOnly.source, "last-known-good"); + assert.equal(warmCacheOnly.models.length, 2); + assert.equal(probeCalls, 1); + assert.equal(pathResolveCalls, 0); + + // 4. Simulate an app restart (all memory caches empty): cacheOnly AND the + // following idle/picker freshness check both recover the fresh persisted + // Cursor catalog from its alias without invoking any probe or PATH lookup. + ctx.sdkModelCache.clear(); + ctx.sdkModelKeyAliases.clear(); + ctx.cursorCliBinCache.clear(); + const afterRestartCacheOnly = await listModels({ sender: {} }, { ...request, cacheOnly: true }); + assert.equal(afterRestartCacheOnly.source, "last-known-good"); + assert.deepEqual(afterRestartCacheOnly.models.map(({ id }) => id), ["auto", "claude-4.5-sonnet"]); + assert.equal(probeCalls, 1); + assert.equal(pathResolveCalls, 0); + + const afterRestartFreshCheck = await listModels({ sender: {} }, request); + assert.equal(afterRestartFreshCheck.source, "last-known-good"); + assert.deepEqual(afterRestartFreshCheck.models.map(({ id }) => id), ["auto", "claude-4.5-sonnet"]); + assert.equal(probeCalls, 1); + assert.equal(pathResolveCalls, 0); + assert.equal(driver.listModels.mock.callCount(), 1); + + // Even if an idle/picker freshness check runs directly after restart + // without a preceding cacheOnly call, it still uses the persisted alias first. + ctx.sdkModelCache.clear(); + ctx.sdkModelKeyAliases.clear(); + ctx.cursorCliBinCache.clear(); + const directFreshCheck = await listModels({ sender: {} }, request); + assert.equal(directFreshCheck.source, "last-known-good"); + assert.deepEqual(directFreshCheck.models.map(({ id }) => id), ["auto", "claude-4.5-sonnet"]); + assert.equal(probeCalls, 1); + assert.equal(pathResolveCalls, 0); + assert.equal(driver.listModels.mock.callCount(), 1); + } finally { + ctx.sdkModelKeyAliases.clear(); + ctx.cursorCliBinCache.clear(); + cleanup(); + } +}); + +test("list-models reprobes a moved Cursor executable during stale automatic revalidation", async (t) => { + const { getDriver } = require("./index.cjs"); + const now = Date.parse("2026-11-18T00:00:00Z"); + const expiredAt = now + 12 * 60 * 60 * 1000; + t.mock.timers.enable({ apis: ["Date"], now }); + let currentCursorBin = "/old/cursor-agent"; + let probeCalls = 0; + const { handlers, ctx, cleanup } = makeLastKnownCtx({ + getShellEnv: async () => ({ PATH: "/test/cursor-moved-bin" }), + probeCursorCliAuth: async () => { + probeCalls += 1; + return { authenticated: true, authSource: "cli-login", email: "a@b.c", binPath: currentCursorBin }; + }, + }); + ctx.sdkModelKeyAliases.clear(); + ctx.cursorCliBinCache.clear(); + try { + const driver = getDriver("cursor"); + t.mock.method(driver, "listModels", async ({ cursorCliBinPath }) => { + if (cursorCliBinPath === "/old/cursor-agent") return [{ id: "old-model", name: "Old Model" }]; + if (cursorCliBinPath === "/new/cursor-agent") return [{ id: "new-model", name: "New Model" }]; + return []; + }); + const listModels = handlers.get("netcatty:ai:sdk-agent:list-models"); + const request = { + sdkBackend: "cursor", + agentCommand: "cursor", + agentEnv: { NETCATTY_CURSOR_AUTH_MODE: "cli-login", NETCATTY_CURSOR_CLI_BIN: "cursor" }, + }; + + // 1. Seed with /old/cursor-agent. + const seeded = await listModels({ sender: {} }, request); + assert.equal(seeded.source, "live"); + assert.deepEqual(seeded.models.map(({ id }) => id), ["old-model"]); + assert.equal(probeCalls, 1); + + // 2. Move cursor-agent to /new/cursor-agent, advance 12h, and restart. + currentCursorBin = "/new/cursor-agent"; + t.mock.timers.setTime(expiredAt); + ctx.sdkModelCache.clear(); + ctx.sdkModelKeyAliases.clear(); + ctx.cursorCliBinCache.clear(); + + // cacheOnly hydrates stale models immediately without probing or pinning the old binary. + const cached = await listModels({ sender: {} }, { ...request, cacheOnly: true }); + assert.equal(cached.source, "last-known-good"); + assert.deepEqual(cached.models.map(({ id }) => id), ["old-model"]); + assert.equal(probeCalls, 1); + + // Automatic stale revalidation re-probes, discovers /new/cursor-agent, and refreshes live models. + const refreshed = await listModels({ sender: {} }, request); + assert.equal(refreshed.source, "live"); + assert.deepEqual(refreshed.models.map(({ id }) => id), ["new-model"]); + assert.equal(probeCalls, 2); + + // Subsequent cacheOnly after restart recovers the new catalog via the updated alias. + ctx.sdkModelCache.clear(); + ctx.sdkModelKeyAliases.clear(); + ctx.cursorCliBinCache.clear(); + const afterUpdate = await listModels({ sender: {} }, { ...request, cacheOnly: true }); + assert.equal(afterUpdate.source, "last-known-good"); + assert.deepEqual(afterUpdate.models.map(({ id }) => id), ["new-model"]); + assert.equal(probeCalls, 2); + } finally { + ctx.sdkModelKeyAliases.clear(); + ctx.cursorCliBinCache.clear(); + cleanup(); + } +}); + +test("list-models cacheOnly avoids synchronous PATH discovery and never hydrates a bare command from another explicit binary", async (t) => { + const { getDriver } = require("./index.cjs"); + let syncPathCalls = 0; + let sdkBinCalls = 0; + const { handlers, ctx, cleanup } = makeLastKnownCtx({ + getShellEnv: async () => ({ PATH: "/test/bare-bin" }), + resolveCliFromPath: () => { + syncPathCalls += 1; + return "/test/bare-bin/opencode"; + }, + resolveSdkBinPath: () => { + sdkBinCalls += 1; + return "/test/bare-bin/claude"; + }, + }); + ctx.sdkModelKeyAliases.clear(); + try { + const claudeDriver = getDriver("claude"); + const opencodeDriver = getDriver("opencode"); + t.mock.method(claudeDriver, "listModels", async () => [{ id: "custom-only-model", name: "Custom Only" }]); + t.mock.method(opencodeDriver, "listModels", async () => [{ id: "openai/gpt-6", name: "GPT-6" }]); + const listModels = handlers.get("netcatty:ai:sdk-agent:list-models"); + + // 1. Seed an explicit custom binary first: a bare command sharing the same + // backend and env must NOT hydrate from this explicit binary's catalog. + await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/custom/isolated/claude" }); + assert.equal(sdkBinCalls, 0); + ctx.sdkModelCache.clear(); + const bareBeforeSeed = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "claude", cacheOnly: true }); + assert.deepEqual(bareBeforeSeed, { ok: true, currentModelId: null, models: [] }); + assert.equal(sdkBinCalls, 0); + + // 2. Seed persisted catalogs for bare commands (resolved via PATH on live load). + claudeDriver.listModels.mock.mockImplementation(async () => [{ id: "claude-opus-6-2", name: "Opus 6.2" }]); + await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "claude" }); + await listModels({ sender: {} }, { sdkBackend: "opencode", agentCommand: "opencode" }); + assert.equal(sdkBinCalls, 1); + assert.equal(syncPathCalls, 1); + + // Even if the explicit binary writes a newer catalog afterward, bare-command + // hydration must still resolve to its own persisted alias after restart. + claudeDriver.listModels.mock.mockImplementation(async () => [{ id: "custom-newer-model", name: "Custom Newer" }]); + await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/custom/isolated/claude", force: true }); + assert.equal(sdkBinCalls, 1); + + // 3. Simulate app restart (all in-memory caches cleared): cacheOnly must + // hydrate each profile's own persisted catalog without sync PATH discovery. + ctx.sdkModelCache.clear(); + ctx.sdkModelKeyAliases.clear(); + const claudeCached = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "claude", cacheOnly: true }); + const opencodeCached = await listModels({ sender: {} }, { sdkBackend: "opencode", agentCommand: "opencode", cacheOnly: true }); + const customPathCached = await listModels({ sender: {} }, { + sdkBackend: "claude", + agentCommand: "/custom/isolated/claude", + cacheOnly: true, + }); + assert.equal(claudeCached.source, "last-known-good"); + assert.deepEqual(claudeCached.models.map(({ id }) => id), ["claude-opus-6-2"]); + assert.equal(opencodeCached.source, "last-known-good"); + assert.deepEqual(opencodeCached.models.map(({ id }) => id), ["openai/gpt-6"]); + assert.equal(customPathCached.source, "last-known-good"); + assert.deepEqual(customPathCached.models.map(({ id }) => id), ["custom-newer-model"]); + assert.equal(sdkBinCalls, 1); + assert.equal(syncPathCalls, 1); + } finally { + ctx.sdkModelKeyAliases.clear(); + cleanup(); + } +}); + +test("list-models cacheOnly resolves pre-alias version-1 stores asynchronously by exact binary and ignores unrelated binaries", async (t) => { + const { getDriver } = require("./index.cjs"); + let syncSdkBinCalls = 0; + let syncPathCalls = 0; + let asyncSdkBinCalls = 0; + let asyncPathCalls = 0; + const { handlers, ctx, catalogFile, cleanup } = makeLastKnownCtx({ + getShellEnv: async () => ({ PATH: "/test/upgrade-bin" }), + resolveSdkBinPath: () => { + syncSdkBinCalls += 1; + return "/test/upgrade-bin/claude"; + }, + resolveSdkBinPathAsync: async () => { + asyncSdkBinCalls += 1; + return "/test/upgrade-bin/claude"; + }, + resolveCliFromPath: () => { + syncPathCalls += 1; + return "/test/upgrade-bin/opencode"; + }, + resolveCliFromPathAsync: async () => { + asyncPathCalls += 1; + return "/test/upgrade-bin/opencode"; + }, + }); + ctx.sdkModelKeyAliases.clear(); + try { + const driver = getDriver("claude"); + t.mock.method(driver, "listModels", async () => { + throw new Error("fresh pre-alias store must not invoke driver.listModels"); + }); + const listModels = handlers.get("netcatty:ai:sdk-agent:list-models"); + const exactKey = buildSdkModelCacheKey("claude", "/test/upgrade-bin/claude", {}, "sdk:api-key"); + const customLegacyKey = buildSdkModelCacheKey("claude", "/custom/only/claude", {}, "sdk:api-key"); + const opencodeLegacyKey = buildSdkModelCacheKey("opencode", "/test/upgrade-bin/opencode", {}, "sdk:api-key"); + const fetchedAt = new Date().toISOString(); + + // 1. Pre-alias v1 store containing ONLY an unrelated explicit binary: + // bare `claude` resolves to `/test/upgrade-bin/claude`, so it must NOT + // hydrate `/custom/only/claude` even though backend/runtime/env match. + fs.writeFileSync(catalogFile, JSON.stringify({ + version: 1, + entries: { + [customLegacyKey]: { + backend: "claude", + models: [{ id: "custom-only-model", name: "Custom Only" }], + currentModelId: "custom-only-model", + fetchedAt, + }, + }, + })); + + const unrelated = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "claude", cacheOnly: true }); + assert.deepEqual(unrelated, { ok: true, currentModelId: null, models: [] }); + assert.equal(syncSdkBinCalls, 0); + assert.equal(asyncSdkBinCalls, 1); + + // 2. Pre-alias v1 store containing both matching and unrelated entries: + // async resolution matches ONLY the exact binary and persists its alias. + fs.writeFileSync(catalogFile, JSON.stringify({ + version: 1, + entries: { + [exactKey]: { + backend: "claude", + models: [{ id: "claude-opus-5-5", name: "Opus 5.5" }], + currentModelId: "claude-opus-5-5", + fetchedAt, + }, + [customLegacyKey]: { + backend: "claude", + models: [{ id: "custom-only-model", name: "Custom Only" }], + currentModelId: "custom-only-model", + fetchedAt, + }, + [opencodeLegacyKey]: { + backend: "opencode", + models: [{ id: "openai/gpt-6", name: "GPT-6" }], + currentModelId: "openai/gpt-6", + fetchedAt, + }, + }, + })); + + const hydrated = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "claude", cacheOnly: true }); + assert.equal(hydrated.source, "last-known-good"); + assert.equal(hydrated.fetchedAt, fetchedAt); + assert.deepEqual(hydrated.models.map(({ id }) => id), ["claude-opus-5-5"]); + assert.equal(syncSdkBinCalls, 0); + assert.equal(asyncSdkBinCalls, 2); + + // After restart, the persisted alias resolves claude in O(1) without re-running async PATH resolution. + ctx.sdkModelKeyAliases.clear(); + const afterRestart = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "claude", cacheOnly: true }); + assert.equal(afterRestart.source, "last-known-good"); + assert.deepEqual(afterRestart.models.map(({ id }) => id), ["claude-opus-5-5"]); + assert.equal(syncSdkBinCalls, 0); + assert.equal(asyncSdkBinCalls, 2); + + // Unmigrated opencode entry in the same partially migrated store still hydrates asynchronously. + const opencodeHydrated = await listModels({ sender: {} }, { + sdkBackend: "opencode", + agentCommand: "opencode", + cacheOnly: true, + }); + assert.equal(opencodeHydrated.source, "last-known-good"); + assert.deepEqual(opencodeHydrated.models.map(({ id }) => id), ["openai/gpt-6"]); + assert.equal(syncPathCalls, 0); + assert.equal(asyncPathCalls, 1); + } finally { + ctx.sdkModelKeyAliases.clear(); + cleanup(); + } +}); + +test("list-models cacheOnly recovers persisted models when a manually configured executable is missing", async (t) => { + const { getDriver } = require("./index.cjs"); + let cliExists = true; + const { handlers, ctx, cleanup } = makeLastKnownCtx({ + normalizeCliPathForPlatform: (value) => (cliExists ? value : null), + }); + ctx.sdkModelKeyAliases.clear(); + try { + const driver = getDriver("claude"); + t.mock.method(driver, "listModels", async () => [ + { id: "claude-opus-6-2", name: "Opus 6.2" }, + { id: "claude-sonnet-6-0", name: "Sonnet 6.0" }, + ]); + const listModels = handlers.get("netcatty:ai:sdk-agent:list-models"); + const request = { sdkBackend: "claude", agentCommand: "/opt/moved/claude" }; + + // 1. Seed persisted catalog while the configured CLI exists. + const seeded = await listModels({ sender: {} }, request); + assert.equal(seeded.source, "live"); + assert.equal(seeded.models.length, 2); + + // 2. Delete/move the configured CLI and clear in-memory caches: BOTH + // cacheOnly AND the subsequent automatic / forced refresh must preserve + // the saved models instead of replacing them with an empty warned catalog. + cliExists = false; + ctx.sdkModelCache.clear(); + ctx.sdkModelKeyAliases.clear(); + const cached = await listModels({ sender: {} }, { ...request, cacheOnly: true }); + assert.equal(cached.source, "last-known-good"); + assert.deepEqual(cached.models.map(({ id }) => id), ["claude-opus-6-2", "claude-sonnet-6-0"]); + assert.equal(cached.warning, undefined); + + const normal = await listModels({ sender: {} }, request); + assert.equal(normal.source, "last-known-good"); + assert.deepEqual(normal.models.map(({ id }) => id), ["claude-opus-6-2", "claude-sonnet-6-0"]); + assert.equal(normal.warning, undefined); + + const forced = await listModels({ sender: {} }, { ...request, force: true }); + assert.equal(forced.source, "last-known-good"); + assert.deepEqual(forced.models.map(({ id }) => id), ["claude-opus-6-2", "claude-sonnet-6-0"]); + assert.match(forced.warning, /Agent CLI path not found: \/opt\/moved\/claude/); + } finally { + ctx.sdkModelKeyAliases.clear(); + cleanup(); + } +}); + +test("list-models persists aliases for callers that join an in-flight load", async (t) => { + const { getDriver } = require("./index.cjs"); + const { handlers, ctx, catalogFile, cleanup } = makeLastKnownCtx({ + getShellEnv: async () => ({ PATH: "/test/join-bin" }), + resolveSdkBinPath: () => "/test/join-bin/claude", + }); + ctx.sdkModelKeyAliases.clear(); + try { + const driver = getDriver("claude"); + let release; + const gate = new Promise((resolve) => { release = resolve; }); + t.mock.method(driver, "listModels", async () => { + await gate; + return [{ id: "claude-opus-6-2", name: "Opus 6.2" }]; + }); + const listModels = handlers.get("netcatty:ai:sdk-agent:list-models"); + + // Start two concurrent requests with different aliases resolving to the same binary. + const first = listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "claude" }); + await new Promise((resolve) => setImmediate(resolve)); + const second = listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/join-bin/claude" }); + await new Promise((resolve) => setImmediate(resolve)); + release(); + const [firstResult, secondResult] = await Promise.all([first, second]); + assert.deepEqual(secondResult, firstResult); + assert.equal(driver.listModels.mock.callCount(), 1); + + // Both aliases must be persisted on disk once the shared load completes. + const stored = JSON.parse(fs.readFileSync(catalogFile, "utf8")); + assert.equal(Object.keys(stored.aliases || {}).length, 2); + } finally { + ctx.sdkModelKeyAliases.clear(); + cleanup(); + } +}); + +test("list-models preserves saved models when a previously discovered bare CLI disappears", async (t) => { + const { getDriver } = require("./index.cjs"); + let cliAvailable = true; + const { handlers, ctx, cleanup } = makeLastKnownCtx({ + getShellEnv: async () => ({ PATH: "/test/disappear-bin" }), + resolveSdkBinPath: () => (cliAvailable ? "/test/disappear-bin/claude" : undefined), + }); + ctx.sdkModelKeyAliases.clear(); + try { + const driver = getDriver("claude"); + t.mock.method(driver, "listModels", async () => [ + { id: "claude-opus-6-2", name: "Opus 6.2" }, + { id: "claude-sonnet-6-0", name: "Sonnet 6.0" }, + ]); + const listModels = handlers.get("netcatty:ai:sdk-agent:list-models"); + const request = { sdkBackend: "claude", agentCommand: "claude" }; + + const seeded = await listModels({ sender: {} }, request); + assert.equal(seeded.source, "live"); + assert.equal(seeded.models.length, 2); + + // Bare CLI disappears from PATH after restart: cacheOnly, normal load, and + // forced refresh must all preserve the saved catalog via its alias. + cliAvailable = false; + ctx.sdkModelCache.clear(); + ctx.sdkModelKeyAliases.clear(); + driver.listModels.mock.mockImplementation(async () => { + throw new Error("spawn claude ENOENT"); + }); + + const cached = await listModels({ sender: {} }, { ...request, cacheOnly: true }); + assert.equal(cached.source, "last-known-good"); + assert.deepEqual(cached.models.map(({ id }) => id), ["claude-opus-6-2", "claude-sonnet-6-0"]); + + const normal = await listModels({ sender: {} }, request); + assert.equal(normal.source, "last-known-good"); + assert.deepEqual(normal.models.map(({ id }) => id), ["claude-opus-6-2", "claude-sonnet-6-0"]); + assert.equal(normal.warning, undefined); + + const forced = await listModels({ sender: {} }, { ...request, force: true }); + assert.equal(forced.source, "last-known-good"); + assert.deepEqual(forced.models.map(({ id }) => id), ["claude-opus-6-2", "claude-sonnet-6-0"]); + assert.match(forced.warning, /ENOENT/); + } finally { + ctx.sdkModelKeyAliases.clear(); + cleanup(); + } +}); + +test("list-models preserves saved models when an environment-configured OPENCODE_BIN symlink target disappears", async (t) => { + const { getDriver } = require("./index.cjs"); + const tmpDir = fs.mkdtempSync(nodePath.join(os.tmpdir(), "netcatty-env-symlink-")); + const targetBin = nodePath.join(tmpDir, "opencode-real"); + const symlinkBin = nodePath.join(tmpDir, "opencode-link"); + fs.writeFileSync(targetBin, "#!/bin/sh\n"); + fs.symlinkSync(targetBin, symlinkBin); + const { handlers, ctx, cleanup } = makeLastKnownCtx({ + normalizeCliPathForPlatform: (value) => (fs.existsSync(value) ? value : null), + }); + ctx.sdkModelKeyAliases.clear(); + try { + const driver = getDriver("opencode"); + t.mock.method(driver, "listModels", async () => [ + { id: "openai/gpt-6", name: "GPT-6" }, + { id: "anthropic/claude-6", name: "Claude 6" }, + ]); + const listModels = handlers.get("netcatty:ai:sdk-agent:list-models"); + const request = { + sdkBackend: "opencode", + agentCommand: "opencode", + agentEnv: { OPENCODE_BIN: symlinkBin }, + }; + + // 1. Seed catalog while OPENCODE_BIN symlink resolves to targetBin. + const seeded = await listModels({ sender: {} }, request); + assert.equal(seeded.source, "live"); + assert.equal(seeded.models.length, 2); + + // 2. Remove the symlink target and simulate restart: cacheOnly, normal load, + // and forced refresh must still recover the saved models via the env-bin alias. + fs.unlinkSync(targetBin); + ctx.sdkModelCache.clear(); + ctx.sdkModelKeyAliases.clear(); + driver.listModels.mock.mockImplementation(async () => { + throw new Error("spawn opencode ENOENT"); + }); + + const cached = await listModels({ sender: {} }, { ...request, cacheOnly: true }); + assert.equal(cached.source, "last-known-good"); + assert.deepEqual(cached.models.map(({ id }) => id), ["openai/gpt-6", "anthropic/claude-6"]); + + const normal = await listModels({ sender: {} }, request); + assert.equal(normal.source, "last-known-good"); + assert.deepEqual(normal.models.map(({ id }) => id), ["openai/gpt-6", "anthropic/claude-6"]); + assert.equal(normal.warning, undefined); + + const forced = await listModels({ sender: {} }, { ...request, force: true }); + assert.equal(forced.source, "last-known-good"); + assert.deepEqual(forced.models.map(({ id }) => id), ["openai/gpt-6", "anthropic/claude-6"]); + assert.match(forced.warning, /ENOENT/); + } finally { + ctx.sdkModelKeyAliases.clear(); + cleanup(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test("list-models preserves PATH fallback when CODEBUDDY_CODE_PATH points to a missing file", async (t) => { + const { getDriver } = require("./index.cjs"); + const seenBinPaths = []; + const { handlers, ctx, cleanup } = makeLastKnownCtx({ + getShellEnv: async () => ({ PATH: "/test/codebuddy-path" }), + normalizeCliPathForPlatform: (value) => (value === "/test/codebuddy-path/codebuddy" ? value : null), + resolveCliFromPath: (cmd) => (cmd === "codebuddy" ? "/test/codebuddy-path/codebuddy" : null), + }); + ctx.sdkModelKeyAliases.clear(); + try { + const driver = getDriver("codebuddy"); + t.mock.method(driver, "listModels", async ({ binPath }) => { + seenBinPaths.push(binPath); + return [{ id: "codebuddy-live", name: "CodeBuddy Live" }]; + }); + const listModels = handlers.get("netcatty:ai:sdk-agent:list-models"); + const result = await listModels({ sender: {} }, { + sdkBackend: "codebuddy", + agentCommand: "codebuddy", + agentEnv: { CODEBUDDY_CODE_PATH: "/missing/codebuddy" }, + }); + assert.equal(result.source, "live"); + assert.deepEqual(result.models.map(({ id }) => id), ["codebuddy-live"]); + assert.deepEqual(seenBinPaths, ["/test/codebuddy-path/codebuddy"]); + } finally { + ctx.sdkModelKeyAliases.clear(); + cleanup(); + } +}); + test("list-models force refresh bypasses warm memory and last-known-good and updates both caches", async (t) => { const { getDriver } = require("./index.cjs"); const { handlers, ctx, catalogFile, cleanup } = makeLastKnownCtx(); diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index c78e58a61..080447c56 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -2227,8 +2227,8 @@ function createPreloadApi(ctx) { clientUserMessageId, }); }, - aiSdkAgentListModels: async (sdkBackend, cwd, providerId, chatSessionId, agentEnv, agentCommand, codexRuntime, force) => { - return ipcRenderer.invoke("netcatty:ai:sdk-agent:list-models", { sdkBackend, cwd, providerId, chatSessionId, agentEnv, agentCommand, codexRuntime, force }); + aiSdkAgentListModels: async (sdkBackend, cwd, providerId, chatSessionId, agentEnv, agentCommand, codexRuntime, force, cacheOnly) => { + return ipcRenderer.invoke("netcatty:ai:sdk-agent:list-models", { sdkBackend, cwd, providerId, chatSessionId, agentEnv, agentCommand, codexRuntime, force, cacheOnly }); }, codexAppServerGetStatus: async (agentCommand, agentEnv) => { return ipcRenderer.invoke("netcatty:ai:codex-app-server:status", { agentCommand, agentEnv }); diff --git a/infrastructure/ai/aiChatStreamingSupport.ts b/infrastructure/ai/aiChatStreamingSupport.ts index b930fea72..4d6ab8ddb 100644 --- a/infrastructure/ai/aiChatStreamingSupport.ts +++ b/infrastructure/ai/aiChatStreamingSupport.ts @@ -175,6 +175,7 @@ export interface PanelBridge extends NetcattyBridge { agentCommand?: string, codexRuntime?: 'sdk' | 'app-server', force?: boolean, + cacheOnly?: boolean, ) => Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[]; defaultThinkingLevel?: string }>; currentModelId?: string | null; warning?: string; source?: 'live' | 'last-known-good'; fetchedAt?: string; error?: string }>; aiCattyCancelExec?(chatSessionId: string, delegationTag?: string): Promise; aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean, delegationTag?: string): Promise<{ ok: boolean; error?: string }>; diff --git a/types/global/netcatty-bridge-ai.d.ts b/types/global/netcatty-bridge-ai.d.ts index 38bc871a6..d90593d11 100644 --- a/types/global/netcatty-bridge-ai.d.ts +++ b/types/global/netcatty-bridge-ai.d.ts @@ -200,7 +200,7 @@ declare global { message?: string; turnKind?: 'review' | 'compact'; }>; - aiSdkAgentListModels?(sdkBackend: string, cwd?: string, providerId?: string, chatSessionId?: string, agentEnv?: Record, agentCommand?: string, codexRuntime?: 'sdk' | 'app-server', force?: boolean): Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[]; defaultThinkingLevel?: string }>; currentModelId?: string | null; warning?: string; source?: 'live' | 'last-known-good'; fetchedAt?: string; error?: string }>; + aiSdkAgentListModels?(sdkBackend: string, cwd?: string, providerId?: string, chatSessionId?: string, agentEnv?: Record, agentCommand?: string, codexRuntime?: 'sdk' | 'app-server', force?: boolean, cacheOnly?: boolean): Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[]; defaultThinkingLevel?: string }>; currentModelId?: string | null; warning?: string; source?: 'live' | 'last-known-good'; fetchedAt?: string; error?: string }>; codexAppServerGetStatus?(agentCommand?: string, agentEnv?: Record): Promise<{ ok: boolean; available: boolean; error?: string }>; onCodexAppServerInteractionRequest?(cb: (payload: Record) => void): () => void; onCodexAppServerInteractionCleared?(cb: (payload: { interactionIds: string[]; chatSessionId?: string }) => void): () => void;