Merge pull request #3884 from binaricat/fix/pr3883-force-refresh

feat(ai): LKG-first model catalogs with reliable manual refresh
This commit is contained in:
陈大猫 authored and GitHub committed 2026-10-23 18:20:40 +08:00
commit a3b3e70388
18 files changed
+315 -39

No files matched your search

+1
View File
@@ -582,6 +582,7 @@ export const enAiMessages: Messages = {
'ai.chat.modelCatalogSourceCached': 'Cached · last success {time}',
'ai.chat.modelCatalogSourceCachedNoTime': 'Cached',
'ai.chat.modelCatalogSourcePresets': 'Built-in default list',
'ai.chat.refreshModelList': 'Refresh model list',
'ai.chat.noMatchingModels': 'No matching models',
'ai.chat.recent': 'Recent',
'ai.chat.viewAll': 'View All',
+1
View File
@@ -565,6 +565,7 @@ export const esAiMessages: Messages = {
'ai.chat.modelCatalogSourceCached': 'En caché · último éxito {time}',
'ai.chat.modelCatalogSourceCachedNoTime': 'En caché',
'ai.chat.modelCatalogSourcePresets': 'Lista predeterminada integrada',
'ai.chat.refreshModelList': 'Actualizar la lista de modelos',
'ai.chat.noMatchingModels': 'No hay modelos coincidentes',
'ai.chat.recent': 'Recientes',
'ai.chat.viewAll': 'Ver todo',
+1
View File
@@ -521,6 +521,7 @@ export const ruAiMessages: Messages = {
'ai.chat.modelCatalogSourceCached': 'Кэш · обновлён {time}',
'ai.chat.modelCatalogSourceCachedNoTime': 'Кэш',
'ai.chat.modelCatalogSourcePresets': 'Встроенный список моделей',
'ai.chat.refreshModelList': 'Обновить список моделей',
'ai.chat.noMatchingModels': 'Нет подходящих моделей',
'ai.chat.recent': 'Недавние',
'ai.chat.viewAll': 'Показать всё',
+1
View File
@@ -582,6 +582,7 @@ export const zhCNAiMessages: Messages = {
'ai.chat.modelCatalogSourceCached': '缓存 · 上次成功 {time}',
'ai.chat.modelCatalogSourceCachedNoTime': '缓存',
'ai.chat.modelCatalogSourcePresets': '内置默认列表',
'ai.chat.refreshModelList': '刷新模型列表',
'ai.chat.noMatchingModels': '没有匹配的模型',
'ai.chat.recent': '最近',
'ai.chat.viewAll': '查看全部',
+1
View File
@@ -572,6 +572,7 @@ export const zhTWAiMessages: Messages = {
'ai.chat.modelCatalogSourceCached': '快取 · 上次成功 {time}',
'ai.chat.modelCatalogSourceCachedNoTime': '快取',
'ai.chat.modelCatalogSourcePresets': '內建預設清單',
'ai.chat.refreshModelList': '重新整理模型清單',
'ai.chat.noMatchingModels': '沒有符合的模型',
'ai.chat.recent': '最近',
'ai.chat.viewAll': '檢視全部',
+2
View File
@@ -411,6 +411,8 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
modelCatalogLoading={modelCatalogLoading}
modelCatalogSource={modelCatalogSource}
modelCatalogFetchedAt={modelCatalogFetchedAt}
modelCatalogWarning={modelCatalogWarning}
onRefreshModelCatalog={handleModelCatalogRetry}
allowCustomModelEntry={allowCustomModelEntry}
selectedModelId={selectedAgentModel}
onModelSelect={handleAgentModelSelect}
+3
View File
@@ -1090,6 +1090,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
target.agentEnv,
target.agentCommand,
target.codexRuntime,
// Manual refresh (retry banner / picker button) must bypass the
// main-side LKG-first policy and go live.
options.force === true,
);
if (!result?.ok || !Array.isArray(result.models)) {
throw new Error(result?.error || 'Failed to load SDK agent models');
@@ -620,6 +620,34 @@ test('SDK runtime model cache preserves degraded warnings until a successful ret
assert.equal(cache.read('copilot')?.warning, undefined);
});
test('SDK runtime model cache re-queries main past the TTL so a clean LKG serve clears a stale banner', async () => {
let now = 1_000;
const cache = createSdkRuntimeModelCache({ ttlMs: 100, now: () => now });
// A degraded serve (warning) is cached and replayed within the TTL.
await cache.refresh('claude:/opt/bin/claude', async () => ({
currentModelId: 'claude-opus-5-5',
models: [{ id: 'claude-opus-5-5', name: 'Opus 5.5' }],
warning: 'live fetch failed',
}));
assert.equal(cache.read('claude:/opt/bin/claude')?.warning, 'live fetch failed');
// Past the TTL the entry is evicted and the next automatic load re-queries
// main; with the LKG-first policy that round-trip returns a clean
// last-known-good serve, so the stale banner clears.
now = 1_150;
const cleared = await cache.refresh('claude:/opt/bin/claude', async () => ({
currentModelId: 'claude-opus-5-5',
models: [{ id: 'claude-opus-5-5', name: 'Opus 5.5' }],
source: 'last-known-good',
fetchedAt: '2026-10-23T08:00:00.000Z',
}));
assert.equal(cleared.source, 'last-known-good');
assert.equal(cleared.warning, undefined);
assert.equal(cache.read('claude:/opt/bin/claude')?.warning, undefined);
assert.equal(cache.read('claude:/opt/bin/claude')?.fetchedAt, '2026-10-23T08:00:00.000Z');
});
// #3584 alignment: OpenCode must render build-time presets while its live
// catalog load is pending, exactly like every other backend. The old host
// code suppressed presets for opencode while `runtimeModelLoading` was set,
+4
View File
@@ -247,6 +247,10 @@ export function createSdkRuntimeModelCache(options: SdkRuntimeModelCacheOptions
pruneEntries();
const cached = entries.get(key);
if (!refreshOptions.force && cached && now() - cached.updatedAt < ttlMs) {
// The LKG-first policy lives in main: once a persisted catalog exists
// there, a TTL-expired non-force refresh is answered from disk with a
// clean last-known-good serve (no live attempt, no warning), so the
// next automatic load here clears a stale banner.
touchEntry(key, cached);
return Promise.resolve(cloneCatalog(cached));
}
+10
View File
@@ -212,6 +212,10 @@ interface ChatInputProps {
modelCatalogSource?: 'live' | 'last-known-good' | 'presets';
/** ISO timestamp of the successful fetch backing `modelCatalogSource`. */
modelCatalogFetchedAt?: string;
/** The catalog warning text behind the host's retry banner, when present. */
modelCatalogWarning?: string;
/** Manual refresh action for the picker's refresh button (force path). */
onRefreshModelCatalog?: () => 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
@@ -286,6 +290,8 @@ const ChatInput: React.FC<ChatInputProps> = ({
modelCatalogLoading = false,
modelCatalogSource,
modelCatalogFetchedAt,
modelCatalogWarning,
onRefreshModelCatalog,
allowCustomModelEntry = true,
selectedModelId,
onModelSelect,
@@ -1608,6 +1614,8 @@ const ChatInput: React.FC<ChatInputProps> = ({
loading={!hasProviderSwitcher ? modelCatalogLoading : undefined}
catalogSource={!hasProviderSwitcher ? modelCatalogSource : undefined}
catalogFetchedAt={!hasProviderSwitcher ? modelCatalogFetchedAt : undefined}
catalogWarning={!hasProviderSwitcher ? modelCatalogWarning : undefined}
onRefreshCatalog={!hasProviderSwitcher ? onRefreshModelCatalog : undefined}
allowCustomEntry={allowCustomModelEntry}
prefs={modelPrefs}
onSelectProviderModel={(providerId, modelId, contextWindow) => {
@@ -1824,6 +1832,8 @@ function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boo
&& prev.modelCatalogLoading === next.modelCatalogLoading
&& prev.modelCatalogSource === next.modelCatalogSource
&& prev.modelCatalogFetchedAt === next.modelCatalogFetchedAt
&& prev.modelCatalogWarning === next.modelCatalogWarning
&& prev.onRefreshModelCatalog === next.onRefreshModelCatalog
&& prev.allowCustomModelEntry === next.allowCustomModelEntry
&& prev.selectedModelId === next.selectedModelId
&& prev.onModelSelect === next.onModelSelect
@@ -156,3 +156,36 @@ test('external agent picker shows the loading row while the live catalog is pend
// keeps built-in presets visible during loading and passes them through.
assert.doesNotMatch(html, /gpt-5\.1/);
});
test('manual refresh button renders for any fetched catalog or warning and stays localized', () => {
const base = {
modelPresets: [{ id: 'm-1', name: 'M1' }],
selectedModelId: 'm-1',
prefs: { recent: [], pinned: [] },
onSelectModel: () => {},
onTogglePinned: () => {},
};
for (const [locale, refreshLabel] of [
['en', 'Refresh model list'],
['zh-CN', '刷新模型列表'],
['zh-TW', '重新整理模型清單'],
['es', 'Actualizar la lista de modelos'],
['ru', 'Обновить список моделей'],
]) {
const html = renderToStaticMarkup(
<I18nProvider locale={locale}>
<ComposerModelPicker {...base} catalogSource="last-known-good" onRefreshCatalog={() => {}} />
</I18nProvider>,
);
assert.ok(html.includes(`aria-label="${refreshLabel}"`));
}
// A plain preset list without a host refresh action stays buttonless.
assert.doesNotMatch(renderToStaticMarkup(<ComposerModelPicker {...base} />), /refreshModelList/);
// A degraded preset serve (warning, no source) still offers the refresh.
const warned = renderToStaticMarkup(
<ComposerModelPicker {...base} catalogWarning="live fetch failed" onRefreshCatalog={() => {}} />,
);
assert.match(warned, /aria-label="ai\.chat\.refreshModelList"/);
});
+43 -4
View File
@@ -1,4 +1,4 @@
import { Check, ChevronLeft, ChevronRight, Loader2, Pin, Search, Star } from 'lucide-react';
import { Check, ChevronLeft, ChevronRight, Loader2, Pin, RotateCw, Search, Star } from 'lucide-react';
import React, { useEffect, useMemo, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import {
@@ -37,6 +37,18 @@ export interface ComposerModelPickerProps {
catalogSource?: 'live' | 'last-known-good' | 'presets';
/** ISO timestamp of the successful fetch backing `catalogSource`. */
catalogFetchedAt?: string;
/**
* The catalog warning text behind the host's retry banner, when present.
* Together with `catalogSource` it decides whether the manual refresh
* button renders: any fetched catalog (live or last-known-good) or a
* degraded preset fallback offers a refresh; a plain preset list does not.
*/
catalogWarning?: string | null;
/**
* Manual refresh action (LKG-first policy: the picker hydrates from disk
* and the user refreshes explicitly). Triggers the host's force refresh.
*/
onRefreshCatalog?: () => void;
prefs: ComposerModelPrefs;
/**
* Offer the "use custom model" action. Disable when the host locks the
@@ -107,6 +119,8 @@ export const ComposerModelPicker: React.FC<ComposerModelPickerProps> = ({
loading = false,
catalogSource,
catalogFetchedAt,
catalogWarning,
onRefreshCatalog,
prefs,
allowCustomEntry = true,
onSelectProviderModel,
@@ -174,6 +188,18 @@ export const ComposerModelPicker: React.FC<ComposerModelPickerProps> = ({
? t('ai.chat.modelCatalogSourceCached').replace('{time}', time)
: t('ai.chat.modelCatalogSourceCachedNoTime');
}, [loading, catalogSource, catalogFetchedAt, t]);
// Manual refresh (LKG-first): offered whenever a fetched catalog (any
// source) or the degraded-preset warning is present. Hidden while loading —
// the spinner row is the in-flight feedback — and in provider mode, where
// neither a catalog chip nor a host refresh action exists.
const showRefreshButton = useMemo(() => (
!loading
&& Boolean(onRefreshCatalog)
&& (catalogSource === 'live'
|| catalogSource === 'last-known-good'
|| Boolean(catalogWarning))
), [loading, onRefreshCatalog, catalogSource, catalogWarning]);
const refreshLabel = t('ai.chat.refreshModelList');
// Manual model ids are accepted in both modes: provider-bound catalogs and
// preset lists from external CLI agents whose catalogs lag new models.
const showCustom = Boolean(
@@ -384,9 +410,22 @@ export const ComposerModelPicker: React.FC<ComposerModelPickerProps> = ({
)}
</div>
{catalogChipText && (
<div className="border-t border-border/40 px-2.5 py-1 text-[10px] text-muted-foreground/45" title={catalogChipText}>
{catalogChipText}
{(catalogChipText || showRefreshButton) && (
<div className="flex items-center gap-1 border-t border-border/40 px-2.5 py-1 text-[10px] text-muted-foreground/45">
{catalogChipText && (
<span className="min-w-0 flex-1 truncate" title={catalogChipText}>{catalogChipText}</span>
)}
{showRefreshButton && (
<button
type="button"
aria-label={refreshLabel}
title={refreshLabel}
onClick={onRefreshCatalog}
className="shrink-0 rounded p-0.5 text-muted-foreground/55 transition-colors hover:bg-muted/40 hover:text-foreground/75 cursor-pointer"
>
<RotateCw size={11} />
</button>
)}
</div>
)}
</div>
+1 -1
View File
@@ -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<string, string> }) => Promise<{ ok: boolean; state?: CodexIntegrationState; isConnected?: boolean; rawOutput?: string; logoutOutput?: string; error?: string }>;
aiResolveCli?: (params: { command: string; customPath?: string; refreshShellEnv?: boolean; apiKeyPresent?: boolean }) => Promise<AgentPathInfo>;
aiSdkAgentListModels?: (sdkBackend: string, cwd?: string, providerId?: string, chatSessionId?: string, agentEnv?: Record<string, string>, agentCommand?: string, codexRuntime?: 'sdk' | 'app-server') => 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<string, string>, 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 }>;
codexAppServerGetStatus?: (agentCommand?: string, agentEnv?: Record<string, string>) => Promise<{ ok: boolean; available: boolean; error?: string }>;
aiUserSkillsGetStatus?: () => Promise<UserSkillsStatusResult>;
aiUserSkillsOpenFolder?: () => Promise<UserSkillsStatusResult>;
@@ -201,6 +201,28 @@ function normalizeSdkListModelsResult(raw) {
return { currentModelId, models };
}
/**
* Map a persisted last-known-good current id to one the picker can show
* (visible default, else first remaining model). A persisted id can be absent
* from the persisted rows: mimo entries written before the auto-channel
* normalization carry one on the filtered `mimo` provider, and any backend can
* advertise a default whose provider returned no rows. The picker would show
* the first row while the send preflight adopted the hidden id, so remap it
* for every backend. No persisted current id means "use the backend default":
* keep null.
*/
function remapLastKnownCurrentModelId(lastKnown) {
if (!lastKnown.currentModelId) return null;
// An effort-decorated id (grok-4.6/high) is served as is when its base row
// advertises that level, matching the renderer's modelPresetsContainId; any
// other suffix stays a dangling id.
return lastKnown.models.some((model) => model.id === lastKnown.currentModelId
|| (Array.isArray(model.thinkingLevels)
&& model.thinkingLevels.some((level) => `${model.id}/${level}` === lastKnown.currentModelId)))
? lastKnown.currentModelId
: lastKnown.models[0]?.id ?? null;
}
/**
* 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
@@ -1074,6 +1096,9 @@ function registerSdkStreamHandlers(ctx) {
ipcMain.handle("netcatty:ai:sdk-agent:list-models", async (event, payload) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
const { sdkBackend, agentEnv: requestedAgentEnv, agentCommand, codexRuntime: requestedCodexRuntime } = payload || {};
// 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 backendKey = resolveBackendKey(sdkBackend);
if (!backendKey) return { ok: false, error: `Unknown SDK backend: ${sdkBackend}` };
@@ -1144,7 +1169,7 @@ function registerSdkStreamHandlers(ctx) {
`${codexRuntime}:${cursorAuthMode}`,
);
const shouldCacheModels = shouldCacheSdkRuntimeModels(backendKey);
const cached = shouldCacheModels ? getSdkModelCacheEntry(sdkModelCache, cacheKey) : null;
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).
@@ -1156,10 +1181,33 @@ function registerSdkStreamHandlers(ctx) {
};
}
// 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);
if (lastKnown) {
console.debug(
`[sdk] list-models(${backendKey}) serving last-known-good catalog from ${lastKnown.fetchedAt} without a live fetch`,
);
return {
ok: true,
currentModelId: remapLastKnownCurrentModelId(lastKnown),
models: lastKnown.models,
source: "last-known-good",
fetchedAt: lastKnown.fetchedAt,
};
}
}
const loadPromise = (async () => {
const abortController = new AbortController();
try {
@@ -1227,37 +1275,23 @@ function registerSdkStreamHandlers(ctx) {
fetchedAt,
};
} catch (err) {
// Degrade to curated presets, but first offer the last-known-good
// catalog persisted from a prior successful fetch (preferred over
// presets, including copilot's single `auto` entry). The warning
// Live attempts happen only when there was nothing to show (no
// cache, no persisted entry) or on an explicit force refresh, so
// this catch is the failure path for exactly those cases: serve
// the last-known-good catalog persisted from a prior success
// (preferred over presets, including copilot's single `auto`
// entry) with a warning — the user acted, or the auto first fetch
// failed and the renderer keeps its curated presets. The warning
// keeps the renderer's retry banner, and the marker lets the UI
// say the list is the previous success.
const lastKnown = readLastKnownCatalogEntry(lastKnownPath, cacheKey);
if (lastKnown) {
// Serve a current id the picker can show (visible default, else
// first remaining model). A persisted id can be absent from the
// persisted rows: mimo entries written before the auto-channel
// normalization carry one on the filtered `mimo` provider, and
// any backend can advertise a default whose provider returned
// no rows. The picker would show the first row while the send
// preflight adopted the hidden id, so remap it for every backend.
// No persisted current id means "use the backend default": keep null.
const lastKnownCurrentModelId = !lastKnown.currentModelId
? null
// An effort-decorated id (grok-4.6/high) is served as is when its
// base row advertises that level, matching the renderer's
// modelPresetsContainId; any other suffix stays a dangling id.
: lastKnown.models.some((model) => model.id === lastKnown.currentModelId
|| (Array.isArray(model.thinkingLevels)
&& model.thinkingLevels.some((level) => `${model.id}/${level}` === lastKnown.currentModelId)))
? lastKnown.currentModelId
: lastKnown.models[0]?.id ?? null;
console.debug(
`[sdk] list-models(${backendKey}) unavailable, serving last-known-good catalog from ${lastKnown.fetchedAt}`,
);
return {
ok: true,
currentModelId: lastKnownCurrentModelId,
currentModelId: remapLastKnownCurrentModelId(lastKnown),
models: lastKnown.models,
warning: `${err?.message || String(err)} — serving the last-known-good catalog fetched at ${lastKnown.fetchedAt}`,
source: "last-known-good",
@@ -1784,7 +1784,7 @@ test("list-models serves a visible current id from last-known-good when the pers
ctx.sdkModelCache.clear();
driver.listModels.mock.mockImplementation(async () => []);
const failed = await listModels({ sender: {} }, { sdkBackend: "opencode", agentCommand: "/test/lkg-dangling" });
const failed = await listModels({ sender: {} }, { sdkBackend: "opencode", agentCommand: "/test/lkg-dangling", force: true });
assert.equal(failed.source, "last-known-good");
assert.equal(failed.currentModelId, "a/m-1", "the served current id must be one the picker shows");
assert.equal(failed.models.some((model) => model.id === failed.currentModelId), true);
@@ -1808,7 +1808,7 @@ test("list-models keeps an effort-decorated current id from last-known-good when
ctx.sdkModelCache.clear();
driver.listModels.mock.mockImplementation(async () => []);
const failed = await listModels({ sender: {} }, { sdkBackend: "grok", agentCommand: "/test/lkg-grok-effort" });
const failed = await listModels({ sender: {} }, { sdkBackend: "grok", agentCommand: "/test/lkg-grok-effort", force: true });
assert.equal(failed.source, "last-known-good");
assert.equal(failed.currentModelId, "grok-4.6/high", "the effort must survive when the base row is listed");
} finally {
@@ -1832,7 +1832,7 @@ test("list-models does not keep a nested current id that is not an advertised th
ctx.sdkModelCache.clear();
driver.listModels.mock.mockImplementation(async () => []);
const failed = await listModels({ sender: {} }, { sdkBackend: "opencode", agentCommand: "/test/lkg-nested" });
const failed = await listModels({ sender: {} }, { sdkBackend: "opencode", agentCommand: "/test/lkg-nested", force: true });
assert.equal(failed.source, "last-known-good");
assert.equal(failed.currentModelId, "a/m-1");
} finally {
@@ -1866,10 +1866,12 @@ test("list-models persists a successful live catalog and serves it as last-known
assert.deepEqual(entries[0].models, liveCatalog);
assert.match(entries[0].fetchedAt, /^\d{4}-\d{2}-\d{2}T/);
// 2. Live failure after that success → the persisted catalog is served.
ctx.sdkModelCache.clear();
// 2. Forced live failure after that success → the persisted catalog is
// served with its warning even while the in-memory cache is warm.
assert.equal(ctx.sdkModelCache.size > 0, true);
driver.listModels.mock.mockImplementation(async () => []);
const failed = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-success" });
const failed = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-success", force: true });
assert.equal(driver.listModels.mock.callCount(), 2, "force must attempt live despite the warm cache");
assert.equal(failed.ok, true);
assert.deepEqual(failed.models, liveCatalog);
assert.equal(failed.currentModelId, null);
@@ -1882,6 +1884,119 @@ test("list-models persists a successful live catalog and serves it as last-known
}
});
test("list-models serves the persisted catalog without a live fetch on a non-force load (LKG-first)", async (t) => {
const { getDriver } = require("./index.cjs");
const { handlers, ctx, cleanup } = makeLastKnownCtx();
try {
const driver = getDriver("claude");
const liveCatalog = [{ id: "claude-opus-5-5", name: "Opus 5.5" }];
t.mock.method(driver, "listModels", async () => liveCatalog);
const listModels = handlers.get("netcatty:ai:sdk-agent:list-models");
// Seed a prior success so the store holds an entry for this cache key.
const seeded = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-first" });
assert.equal(seeded.source, "live");
// A later non-force load must hydrate from the store and never reach the
// driver: no live-fetch budget spent, and no warning — plain panel-open
// stays silent even when the CLI would fail or stall today.
ctx.sdkModelCache.clear();
driver.listModels.mock.mockImplementation(async () => {
throw new Error("the live driver must not run for a non-force load once an LKG entry exists");
});
const hydrated = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-first" });
assert.equal(driver.listModels.mock.callCount(), 1, "only the seeding call may reach the driver");
assert.deepEqual(hydrated, {
ok: true,
currentModelId: null,
models: liveCatalog,
source: "last-known-good",
fetchedAt: hydrated.fetchedAt,
});
assert.equal(hydrated.warning, undefined);
assert.match(hydrated.fetchedAt, /^\d{4}-\d{2}-\d{2}T/);
} finally {
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();
try {
const driver = getDriver("claude");
t.mock.method(driver, "listModels", async () => [{ id: "claude-opus-5-5", name: "Opus 5.5" }]);
const listModels = handlers.get("netcatty:ai:sdk-agent:list-models");
// Keep the prior success warm: force must bypass both cache layers.
await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-force" });
assert.equal(ctx.sdkModelCache.size > 0, true);
const nextCatalog = [{ id: "claude-opus-5-5", name: "Opus 5.5" }, { id: "claude-opus-6-1", name: "Opus 6.1" }];
driver.listModels.mock.mockImplementation(async () => nextCatalog);
const forced = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-force", force: true });
assert.equal(driver.listModels.mock.callCount(), 2);
assert.deepEqual(forced, {
ok: true,
currentModelId: null,
models: nextCatalog,
source: "live",
fetchedAt: forced.fetchedAt,
});
assert.equal(forced.warning, undefined);
// The forced success replaces the persisted entry, so future non-force
// loads and failure fallbacks serve the refreshed list.
const entries = Object.values(readLastKnownCatalogStore(catalogFile));
assert.equal(entries.length, 1);
assert.deepEqual(entries[0].models, nextCatalog);
const cached = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-force" });
assert.deepEqual(cached, forced);
assert.equal(driver.listModels.mock.callCount(), 2, "ordinary loads still reuse the refreshed memory cache");
} finally {
cleanup();
}
});
test("list-models coalesces force refreshes with an existing live fetch", async (t) => {
for (const warmCache of [false, true]) {
await t.test(warmCache ? "warm memory cache" : "cold cache", async (t) => {
const { getDriver } = require("./index.cjs");
const { handlers, cleanup } = makeLastKnownCtx();
try {
const driver = getDriver("claude");
t.mock.method(driver, "listModels", async () => [{ id: "old-model" }]);
const listModels = handlers.get("netcatty:ai:sdk-agent:list-models");
const request = { sdkBackend: "claude", agentCommand: `/test/force-coalesce-${warmCache}` };
if (warmCache) await listModels({ sender: {} }, request);
let complete;
let started;
const entered = new Promise((resolve) => { started = resolve; });
driver.listModels.mock.mockImplementation(() => {
started();
return new Promise((resolve) => { complete = resolve; });
});
const first = listModels({ sender: {} }, { ...request, force: warmCache });
await entered;
const second = listModels({ sender: {} }, { ...request, force: true });
await Promise.resolve();
assert.equal(driver.listModels.mock.callCount(), warmCache ? 2 : 1);
const nextCatalog = [{ id: "new-model" }];
complete(nextCatalog);
const [firstResult, secondResult] = await Promise.all([first, second]);
assert.deepEqual(firstResult.models, nextCatalog);
assert.deepEqual(secondResult, firstResult);
assert.equal(firstResult.source, "live");
assert.equal(driver.listModels.mock.callCount(), warmCache ? 2 : 1);
} finally {
cleanup();
}
});
}
});
test("list-models cache hit replays the live provenance (source + fetchedAt)", async (t) => {
const { getDriver } = require("./index.cjs");
const { handlers, cleanup } = makeLastKnownCtx();
@@ -1919,13 +2034,15 @@ test("list-models admits a current-only catalog by refreshing the persisted curr
await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-current-only" });
// 2. A current-only success (zero visible models, valid selection) must
// refresh the persisted current id without losing the models list.
// refresh the persisted current id without losing the models list. A
// non-force load now hydrates from the persisted entry (LKG-first), so
// only the forced refresh reaches the live current-only result.
ctx.sdkModelCache.clear();
driver.listModels.mock.mockImplementation(async () => ({
currentModelId: "claude-opus-5-5",
models: [],
}));
const currentOnly = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-current-only" });
const currentOnly = await listModels({ sender: {} }, { sdkBackend: "claude", agentCommand: "/test/lkg-current-only", force: true });
assert.deepEqual(currentOnly, {
ok: true,
currentModelId: "claude-opus-5-5",
+2 -2
View File
@@ -2115,8 +2115,8 @@ function createPreloadApi(ctx) {
clientUserMessageId,
});
},
aiSdkAgentListModels: async (sdkBackend, cwd, providerId, chatSessionId, agentEnv, agentCommand, codexRuntime) => {
return ipcRenderer.invoke("netcatty:ai:sdk-agent:list-models", { sdkBackend, cwd, providerId, chatSessionId, agentEnv, agentCommand, codexRuntime });
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 });
},
codexAppServerGetStatus: async (agentCommand, agentEnv) => {
return ipcRenderer.invoke("netcatty:ai:codex-app-server:status", { agentCommand, agentEnv });
@@ -161,6 +161,7 @@ export interface PanelBridge extends NetcattyBridge {
agentEnv?: Record<string, string>,
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 }>;
aiCattyCancelExec?(chatSessionId: string): Promise<unknown>;
aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean): Promise<{ ok: boolean; error?: string }>;
+1 -1
View File
@@ -200,7 +200,7 @@ declare global {
message?: string;
turnKind?: 'review' | 'compact';
}>;
aiSdkAgentListModels?(sdkBackend: string, cwd?: string, providerId?: string, chatSessionId?: string, agentEnv?: Record<string, string>, agentCommand?: string, codexRuntime?: 'sdk' | 'app-server'): 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<string, string>, 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 }>;
codexAppServerGetStatus?(agentCommand?: string, agentEnv?: Record<string, string>): Promise<{ ok: boolean; available: boolean; error?: string }>;
onCodexAppServerInteractionRequest?(cb: (payload: Record<string, unknown>) => void): () => void;
onCodexAppServerInteractionCleared?(cb: (payload: { interactionIds: string[]; chatSessionId?: string }) => void): () => void;