fix(models): avoid cross-session stale model cache

This commit is contained in:
Supra4E8C
2026-03-27 21:49:22 +08:00
Unverified
parent 0273d3c8fd
commit f66deb36dd
2 changed files with 12 additions and 5 deletions
+3
View File
@@ -11,6 +11,7 @@ import { secureStorage } from '@/services/storage/secureStorage';
import { apiClient } from '@/services/api/client';
import { useConfigStore } from './useConfigStore';
import { useUsageStatsStore } from './useUsageStatsStore';
import { useModelsStore } from './useModelsStore';
import { detectApiBaseFromLocation, normalizeApiBase } from '@/utils/connection';
interface AuthStoreState extends AuthState {
@@ -94,6 +95,7 @@ export const useAuthStore = create<AuthStoreState>()(
try {
set({ connectionStatus: 'connecting' });
useModelsStore.getState().clearCache();
// 配置 API 客户端
apiClient.setConfig({
@@ -138,6 +140,7 @@ export const useAuthStore = create<AuthStoreState>()(
restoreSessionPromise = null;
useConfigStore.getState().clearCache();
useUsageStatsStore.getState().clearUsageStats();
useModelsStore.getState().clearCache();
set({
isAuthenticated: false,
apiBase: '',
+9 -5
View File
@@ -11,6 +11,7 @@ interface ModelsCache {
data: ModelInfo[];
timestamp: number;
apiBase: string;
apiKey: string;
}
interface ModelsState {
@@ -21,7 +22,7 @@ interface ModelsState {
fetchModels: (apiBase: string, apiKey?: string, forceRefresh?: boolean) => Promise<ModelInfo[]>;
clearCache: () => void;
isCacheValid: (apiBase: string) => boolean;
isCacheValid: (apiBase: string, apiKey?: string) => boolean;
}
export const useModelsStore = create<ModelsState>((set, get) => ({
@@ -32,9 +33,10 @@ export const useModelsStore = create<ModelsState>((set, get) => ({
fetchModels: async (apiBase, apiKey, forceRefresh = false) => {
const { cache, isCacheValid } = get();
const apiKeyScope = apiKey?.trim() || '';
// 检查缓存
if (!forceRefresh && isCacheValid(apiBase) && cache) {
if (!forceRefresh && isCacheValid(apiBase, apiKeyScope) && cache) {
set({ models: cache.data, error: null });
return cache.data;
}
@@ -42,13 +44,13 @@ export const useModelsStore = create<ModelsState>((set, get) => ({
set({ loading: true, error: null });
try {
const list = await modelsApi.fetchModels(apiBase, apiKey);
const list = await modelsApi.fetchModels(apiBase, apiKeyScope || undefined);
const now = Date.now();
set({
models: list,
loading: false,
cache: { data: list, timestamp: now, apiBase }
cache: { data: list, timestamp: now, apiBase, apiKey: apiKeyScope }
});
return list;
@@ -68,10 +70,12 @@ export const useModelsStore = create<ModelsState>((set, get) => ({
set({ cache: null, models: [] });
},
isCacheValid: (apiBase) => {
isCacheValid: (apiBase, apiKey) => {
const { cache } = get();
if (!cache) return false;
if (cache.apiBase !== apiBase) return false;
const apiKeyScope = apiKey?.trim() || '';
if ((cache.apiKey || '') !== apiKeyScope) return false;
return Date.now() - cache.timestamp < CACHE_EXPIRY_MS;
}
}));