fix(ai): allow dismissing the model catalog warning banner (#4431)

* fix(ai): allow dismissing the model catalog warning banner

* fix(ai): address Codex review on catalog warning dismissal

* fix(ai): persist catalog warning dismissals across empty-panel remounts

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
This commit is contained in:
GOUKI9999andbincxz authored and GitHub committed 2026-11-26 22:32:23 +08:00
1 parent 1009f131fe
commit bbbea4a157
6 files changed
+290 -3

No files matched your search

@@ -0,0 +1,125 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { JSDOM } from 'jsdom';
import {
resetModelCatalogWarningDismissals,
useModelCatalogWarningDismissal,
type ModelCatalogWarningDismissalState,
} from './useModelCatalogWarningDismissal.ts';
import { isModelCatalogWarningVisible } from '../../components/AIChatSidePanelHelpers.ts';
test('useModelCatalogWarningDismissal dismisses per cacheKey, survives remounts, and rearms on clean catalog', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>');
const prevWindow = globalThis.window;
const prevDocument = globalThis.document;
const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;
(globalThis as Record<string, unknown>).window = dom.window;
(globalThis as Record<string, unknown>).document = dom.window.document;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
resetModelCatalogWarningDismissals();
let latest!: ModelCatalogWarningDismissalState;
const Probe: React.FC = () => {
latest = useModelCatalogWarningDismissal();
return null;
};
const container = dom.window.document.getElementById('root')!;
let root = createRoot(container);
try {
await React.act(async () => {
root.render(React.createElement(Probe));
});
assert.equal(latest.dismissedKeys.size, 0);
const warningK1 = { cacheKey: 'k1', message: 'Catalog unavailable' };
const warningK2 = { cacheKey: 'k2', message: 'Other catalog unavailable' };
assert.equal(
isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys),
'Catalog unavailable',
);
// Dismissing k1 hides only k1, leaving k2 visible.
await React.act(async () => {
latest.dismissWarning('k1');
});
assert.equal(latest.dismissedKeys.has('k1'), true);
assert.equal(isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), undefined);
assert.equal(
isModelCatalogWarningVisible(warningK2, 'k2', latest.dismissedKeys),
'Other catalog unavailable',
);
// Unmounting and remounting (e.g., empty panel hidden on tab/tool switch)
// must keep the dismissed cacheKey hidden until a clean catalog arrives.
await React.act(async () => {
root.unmount();
});
root = createRoot(container);
await React.act(async () => {
root.render(React.createElement(Probe));
});
assert.equal(latest.dismissedKeys.has('k1'), true);
assert.equal(isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), undefined);
// Undefined and duplicate dismissals are no-ops that keep state identity.
const setBeforeNoop = latest.dismissedKeys;
await React.act(async () => {
latest.dismissWarning(undefined);
latest.dismissWarning('k1');
});
assert.equal(latest.dismissedKeys, setBeforeNoop);
// A clean catalog for k1 re-arms k1 so future failures surface again.
await React.act(async () => {
latest.rearmWarning('k1');
});
assert.equal(latest.dismissedKeys.has('k1'), false);
assert.equal(
isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys),
'Catalog unavailable',
);
// Rearming a non-dismissed or undefined key is a no-op.
const setAfterRearm = latest.dismissedKeys;
await React.act(async () => {
latest.rearmWarning('k1');
latest.rearmWarning(undefined);
});
assert.equal(latest.dismissedKeys, setAfterRearm);
} finally {
await React.act(async () => {
root.unmount();
});
resetModelCatalogWarningDismissals();
(globalThis as Record<string, unknown>).window = prevWindow;
(globalThis as Record<string, unknown>).document = prevDocument;
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;
}
});
test('AIChatPanelContent keeps raw modelCatalogWarning for ChatInput when banner is dismissed', () => {
const panelSource = readFileSync(new URL('../../components/AIChatPanelContent.tsx', import.meta.url), 'utf8');
const sidePanelSource = readFileSync(new URL('../../components/AIChatSidePanel.tsx', import.meta.url), 'utf8');
assert.match(
panelSource,
/modelCatalogWarning && !modelCatalogWarningDismissed \?/,
'banner visibility must check modelCatalogWarningDismissed separately from raw modelCatalogWarning',
);
assert.match(
panelSource,
/<ChatInput[\s\S]*?modelCatalogWarning=\{modelCatalogWarning\}/,
'ChatInput must still receive the raw modelCatalogWarning so ComposerModelPicker keeps its refresh action',
);
assert.match(
sidePanelSource,
/useModelCatalogWarningDismissal\(\)/,
'AIChatSidePanel must consume the application/state dismissal hook rather than owning inline dismissal state',
);
});
@@ -0,0 +1,70 @@
import { useSyncExternalStore } from 'react';
export interface ModelCatalogWarningDismissalState {
dismissedKeys: ReadonlySet<string>;
dismissWarning: (cacheKey: string | undefined) => void;
rearmWarning: (cacheKey: string | undefined) => void;
}
type Listener = () => void;
let dismissedKeysSnapshot: ReadonlySet<string> = new Set();
const listeners = new Set<Listener>();
function emitChange(): void {
for (const listener of listeners) {
listener();
}
}
function subscribe(listener: Listener): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
function getSnapshot(): ReadonlySet<string> {
return dismissedKeysSnapshot;
}
export function dismissModelCatalogWarningKey(cacheKey: string | undefined): void {
if (!cacheKey || dismissedKeysSnapshot.has(cacheKey)) return;
const next = new Set(dismissedKeysSnapshot);
next.add(cacheKey);
dismissedKeysSnapshot = next;
emitChange();
}
export function rearmModelCatalogWarningKey(cacheKey: string | undefined): void {
if (!cacheKey || !dismissedKeysSnapshot.has(cacheKey)) return;
const next = new Set(dismissedKeysSnapshot);
next.delete(cacheKey);
dismissedKeysSnapshot = next;
emitChange();
}
export function resetModelCatalogWarningDismissals(): void {
if (dismissedKeysSnapshot.size === 0) return;
dismissedKeysSnapshot = new Set();
emitChange();
}
/**
* Tracks SDK model catalog cache keys whose composer warning banner was
* dismissed by the user.
*
* Stored at module scope so dismissals survive empty-panel unmounts during
* normal tab/tool navigation and stay consistent with the shared
* `sdkRuntimeModelCache`. Dismissals remain scoped by cacheKey so switching
* agents or config re-arms the banner, and a clean catalog load clears that
* key so a later failure warns again.
*/
export function useModelCatalogWarningDismissal(): ModelCatalogWarningDismissalState {
const dismissedKeys = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
return {
dismissedKeys,
dismissWarning: dismissModelCatalogWarningKey,
rearmWarning: rearmModelCatalogWarningKey,
};
}
+19 -2
View File
@@ -1,5 +1,5 @@
import React, { type Dispatch, type SetStateAction } from 'react';
import { History, Plus, Undo2 } from 'lucide-react';
import { History, Plus, Undo2, X } from 'lucide-react';
import type { AIPermissionMode, AISession, ChatMessage, DiscoveredAgent, ExternalAgentConfig, AgentModelPreset, ProviderConfig, UploadedFile } from '../infrastructure/ai/types';
import type { Host, VaultNote } from '../types';
import type { UserSkillOption } from './ai/userSkillsState';
@@ -87,6 +87,8 @@ interface AIChatPanelContentProps {
providerDisplayName?: string;
modelDisplayName?: string;
modelCatalogWarning?: string;
/** Whether the composer warning banner itself was dismissed (picker still sees raw warning). */
modelCatalogWarningDismissed?: boolean;
/** Live SDK model catalog is loading (no built-in presets to show yet). */
modelCatalogLoading?: boolean;
/** Provenance of the active model list, rendered as the picker status chip. */
@@ -95,6 +97,8 @@ interface AIChatPanelContentProps {
modelCatalogFetchedAt?: string;
/** Retry a failed SDK model catalog load from the warning banner. */
handleModelCatalogRetry?: () => void;
/** Dismiss the warning banner for this agent config until a clean catalog re-arms it. */
handleModelCatalogDismiss?: () => void;
handleModelPickerOpen?: () => void;
agentModelPresets: AgentModelPreset[];
/** Suppress the composer picker's "use custom model" action (locked model). */
@@ -174,6 +178,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
handleSteer,
handleStop,
handleModelCatalogRetry,
handleModelCatalogDismiss,
handleModelPickerOpen,
canSteer,
isSteering,
@@ -183,6 +188,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
providerDisplayName,
modelDisplayName,
modelCatalogWarning,
modelCatalogWarningDismissed = false,
modelCatalogLoading = false,
modelCatalogSource,
modelCatalogFetchedAt,
@@ -421,7 +427,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
<div role="status" className="mx-3 mb-1.5 rounded-md border border-amber-500/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] leading-4 text-amber-600 dark:text-amber-400">
{steerWarning}
</div>
) : modelCatalogWarning ? (
) : modelCatalogWarning && !modelCatalogWarningDismissed ? (
<div role="status" className="mx-3 mb-1.5 flex items-center gap-2 rounded-md border border-amber-500/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] leading-4 text-amber-600 dark:text-amber-400">
<span className="min-w-0 flex-1">{modelCatalogWarning}</span>
{handleModelCatalogRetry && (
@@ -432,6 +438,17 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
{t('ai.chat.modelCatalogRetry')}
</button>
)}
{handleModelCatalogDismiss && (
<button
type="button"
aria-label={t('common.close')}
title={t('common.close')}
onClick={handleModelCatalogDismiss}
className="shrink-0 rounded p-0.5 text-amber-600/70 transition-colors hover:bg-amber-500/10 hover:text-amber-600 cursor-pointer dark:text-amber-400/70 dark:hover:text-amber-300"
>
<X className="h-3.5 w-3.5" aria-hidden="true" />
</button>
)}
</div>
) : modelCatalogLoading ? (
<div role="status" className="mx-3 mb-1.5 rounded-md bg-muted/40 px-2.5 py-1.5 text-[11px] leading-4 text-muted-foreground/70">
+36 -1
View File
@@ -85,12 +85,14 @@ import { getAgentRuntime } from '../infrastructure/ai/harness/globalAgentRuntime
import { useAIPermissionGrantsState } from '../application/state/useAIPermissionGrantsState';
import { useConversationExport } from './ai/hooks/useConversationExport';
import { useAgentContextUsage } from '../application/state/useAgentCompactionUi';
import { useModelCatalogWarningDismissal } from '../application/state/useModelCatalogWarningDismissal';
import type { AIChatSidePanelProps } from './AIChatSidePanel.types';
import {
buildCursorListModelsAgentEnv,
buildSdkRuntimeModelCacheKey,
sdkRuntimeModelCache,
reconcileRuntimeModelWarning,
isModelCatalogWarningVisible,
retainStoredModelPresetForCatalog,
toSdkRuntimeModelCatalog,
generateId,
@@ -361,6 +363,11 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const [isUndoingLastTurn, setIsUndoingLastTurn] = useState(false);
const [runtimeAgentModelPresets, setRuntimeAgentModelPresets] = useState<Record<string, { cacheKey: string; models: AgentModelPreset[]; catalogUnavailable: boolean }>>({});
const [runtimeModelWarnings, setRuntimeModelWarnings] = useState<Record<string, { cacheKey: string; message: string }>>({});
const {
dismissedKeys: dismissedModelCatalogKeys,
dismissWarning: dismissModelCatalogWarning,
rearmWarning: rearmModelCatalogWarning,
} = useModelCatalogWarningDismissal();
// Tracks SDK runtime model catalogs currently loading (per agent scope);
// the composer shows the loading row alongside the build-time presets and
// the live catalog replaces them when it arrives.
@@ -1352,6 +1359,11 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
t('ai.chat.modelCatalogWarning'),
);
});
// A clean catalog re-arms a banner the user previously dismissed, so a
// later failure for the same config is visible again.
if (catalog && !catalog.warning) {
rearmModelCatalogWarning(target.cacheKey);
}
return catalog;
}).catch((err) => {
setRuntimeModelWarnings((current) => {
@@ -1367,7 +1379,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}
return null;
});
}, [t, buildExternalAgentRuntimeModelTarget]);
}, [t, buildExternalAgentRuntimeModelTarget, rearmModelCatalogWarning]);
useEffect(() => {
if (!isVisible) return;
@@ -1390,6 +1402,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
Boolean(cached.warning),
t('ai.chat.modelCatalogWarning'),
));
if (!cached.warning) {
rearmModelCatalogWarning(target.cacheKey);
}
}
// Respect renderer TTL / in-flight coalescing for all SDK agents including
@@ -1470,6 +1485,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
buildExternalAgentRuntimeModelTarget,
loadSdkRuntimeModelCatalog,
applySdkRuntimeModelCatalog,
rearmModelCatalogWarning,
t,
]);
@@ -1625,6 +1641,14 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
applySdkRuntimeModelCatalog,
]);
// Hide the composer warning banner for this config until a clean catalog
// re-arms it. The underlying warning stays active so the model picker keeps
// its manual refresh action.
const handleDismissModelCatalogWarning = useCallback(() => {
const target = buildExternalAgentRuntimeModelTarget(currentAgentConfig);
dismissModelCatalogWarning(target?.cacheKey);
}, [currentAgentConfig, buildExternalAgentRuntimeModelTarget, dismissModelCatalogWarning]);
const selectedCattyThinking = agentThinkingMap.catty;
const handleCattyThinkingSelect = useCallback((level: string) => {
setAgentThinking('catty', level);
@@ -2516,6 +2540,17 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
&& runtimeModelWarnings[currentAgentId].cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey
? runtimeModelWarnings[currentAgentId].message
: undefined}
modelCatalogWarningDismissed={!hasCodexCustomConfig
&& Boolean(
runtimeModelWarnings[currentAgentId]
&& runtimeModelWarnings[currentAgentId].cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey
&& !isModelCatalogWarningVisible(
runtimeModelWarnings[currentAgentId],
buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey,
dismissedModelCatalogKeys,
),
)}
handleModelCatalogDismiss={handleDismissModelCatalogWarning}
modelCatalogLoading={
!hasCodexCustomConfig
&& Boolean(runtimeModelLoading[currentAgentId])
@@ -17,6 +17,7 @@ import {
normalizeSdkRuntimeModelPresets,
resolveSdkRuntimeCatalogDefaultModelId,
reconcileRuntimeModelWarning,
isModelCatalogWarningVisible,
toSdkRuntimeModelCatalog,
shouldAdoptSdkCurrentModel,
shouldLoadSdkRuntimeModels,
@@ -685,6 +686,26 @@ test('reconcileRuntimeModelWarning clears only the banner that belongs to this c
assert.equal(reconcileRuntimeModelWarning(current, 'copilot', 'k2', false, 'warn'), current);
});
test('isModelCatalogWarningVisible shows a matching, non-dismissed banner', () => {
const warning = { cacheKey: 'k1', message: 'cannot load models' };
assert.equal(isModelCatalogWarningVisible(warning, 'k1', new Set()), 'cannot load models');
});
test('isModelCatalogWarningVisible hides a dismissed cache key but re-arms on a new key', () => {
const warning = { cacheKey: 'k1', message: 'cannot load models' };
const dismissed = new Set(['k1']);
assert.equal(isModelCatalogWarningVisible(warning, 'k1', dismissed), undefined);
// A config/agent switch produces a different cache key, which is not dismissed.
assert.equal(isModelCatalogWarningVisible({ cacheKey: 'k2', message: 'again' }, 'k2', dismissed), 'again');
});
test('isModelCatalogWarningVisible never shows a warning for another cache key or without a target', () => {
const warning = { cacheKey: 'k1', message: 'cannot load models' };
assert.equal(isModelCatalogWarningVisible(warning, 'k2', new Set()), undefined);
assert.equal(isModelCatalogWarningVisible(warning, undefined, new Set()), undefined);
assert.equal(isModelCatalogWarningVisible(undefined, 'k1', new Set()), undefined);
});
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(
+19
View File
@@ -293,6 +293,25 @@ export const sdkRuntimeModelCache = createSdkRuntimeModelCache();
export type RuntimeModelWarnings = Record<string, { cacheKey: string; message: string }>;
/**
* Whether a per-agent catalog warning should surface in the composer banner.
*
* A warning the user explicitly dismissed stays hidden for its cache key until
* a clean catalog is observed (the caller then drops the key from
* `dismissedKeys`). A warning belonging to a different cache key is never
* shown — config/agent switches must not inherit a stale dismissal.
*/
export function isModelCatalogWarningVisible(
warning: { cacheKey: string; message: string } | undefined,
cacheKey: string | undefined,
dismissedKeys: ReadonlySet<string>,
): string | undefined {
if (!warning || !cacheKey) return undefined;
if (warning.cacheKey !== cacheKey) return undefined;
if (dismissedKeys.has(cacheKey)) return undefined;
return warning.message;
}
/**
* Make the per-agent catalog warning banner match a catalog result. Used both
* for cache reads and after a refresh settles: a refresh that coalesced onto