diff --git a/src/components/AISettingsProvider.test.tsx b/src/components/AISettingsProvider.test.tsx new file mode 100644 index 00000000..427cbe14 --- /dev/null +++ b/src/components/AISettingsProvider.test.tsx @@ -0,0 +1,134 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { AISettingsProvider } from './AISettingsProvider'; +import { useAISettings } from '@/hooks/useAISettings'; +import { TestApp } from '@/test/TestApp'; + +// Mock localStorage +const localStorageMock = { + getItem: vi.fn(), + setItem: vi.fn(), + removeItem: vi.fn(), + clear: vi.fn(), +}; + +Object.defineProperty(window, 'localStorage', { + value: localStorageMock, +}); + +describe('AISettingsProvider', () => { + beforeEach(() => { + vi.clearAllMocks(); + localStorageMock.getItem.mockReturnValue(null); + }); + + it('should initialize with empty recentlyUsedModels array', () => { + const { result } = renderHook(() => useAISettings(), { + wrapper: ({ children }) => ( + + {children} + + ), + }); + + expect(result.current.settings.recentlyUsedModels).toEqual([]); + }); + + it('should add recently used models correctly', () => { + const { result } = renderHook(() => useAISettings(), { + wrapper: ({ children }) => ( + + {children} + + ), + }); + + act(() => { + result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet'); + }); + + expect(result.current.settings.recentlyUsedModels).toEqual([ + 'openrouter/anthropic/claude-3.5-sonnet' + ]); + }); + + it('should move existing model to front when used again', () => { + const { result } = renderHook(() => useAISettings(), { + wrapper: ({ children }) => ( + + {children} + + ), + }); + + // Add multiple models + act(() => { + result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet'); + result.current.addRecentlyUsedModel('openrouter/openai/gpt-4'); + result.current.addRecentlyUsedModel('openrouter/google/gemini-pro'); + }); + + expect(result.current.settings.recentlyUsedModels).toEqual([ + 'openrouter/google/gemini-pro', + 'openrouter/openai/gpt-4', + 'openrouter/anthropic/claude-3.5-sonnet' + ]); + + // Use the first model again - it should move to front + act(() => { + result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet'); + }); + + expect(result.current.settings.recentlyUsedModels).toEqual([ + 'openrouter/anthropic/claude-3.5-sonnet', + 'openrouter/google/gemini-pro', + 'openrouter/openai/gpt-4' + ]); + }); + + it('should limit recently used models to 10 items', () => { + const { result } = renderHook(() => useAISettings(), { + wrapper: ({ children }) => ( + + {children} + + ), + }); + + // Add 12 models + act(() => { + for (let i = 1; i <= 12; i++) { + result.current.addRecentlyUsedModel(`provider/model-${i}`); + } + }); + + // Should only keep the last 10 + expect(result.current.settings.recentlyUsedModels).toHaveLength(10); + expect(result.current.settings.recentlyUsedModels[0]).toBe('provider/model-12'); + expect(result.current.settings.recentlyUsedModels[9]).toBe('provider/model-3'); + }); + + it('should migrate old settings without recentlyUsedModels', () => { + const oldSettings = { + providers: { + openrouter: { + baseURL: 'https://openrouter.ai/api/v1', + apiKey: 'test-key' + } + } + }; + + localStorageMock.getItem.mockReturnValue(JSON.stringify(oldSettings)); + + const { result } = renderHook(() => useAISettings(), { + wrapper: ({ children }) => ( + + {children} + + ), + }); + + expect(result.current.settings.recentlyUsedModels).toEqual([]); + expect(result.current.settings.providers).toEqual(oldSettings.providers); + }); +}); \ No newline at end of file diff --git a/src/components/AISettingsProvider.tsx b/src/components/AISettingsProvider.tsx index dd7e50ab..dae75f72 100644 --- a/src/components/AISettingsProvider.tsx +++ b/src/components/AISettingsProvider.tsx @@ -7,6 +7,7 @@ interface AISettingsProviderProps { const DEFAULT_SETTINGS: AISettings = { providers: {}, + recentlyUsedModels: [], }; const STORAGE_KEY = 'ai-settings'; @@ -22,11 +23,16 @@ function migrateOldSettings(stored: unknown): AISettings { apiKey: oldSettings.apiKey || '', }, }, + recentlyUsedModels: [], }; } // If it's already the new format or invalid, return as AISettings or default if (stored && typeof stored === 'object' && 'providers' in stored) { - return stored as AISettings; + const settings = stored as Partial; + return { + providers: settings.providers || {}, + recentlyUsedModels: settings.recentlyUsedModels || [], + }; } return DEFAULT_SETTINGS; } @@ -87,6 +93,30 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { })); }; + const addRecentlyUsedModel = (modelId: string) => { + setSettings(prev => { + const existingIndex = prev.recentlyUsedModels.indexOf(modelId); + if (existingIndex === 0) { + return prev; + } else if (existingIndex === -1) { + // Add new model to front, keep only last 10 + return { + ...prev, + recentlyUsedModels: [modelId, ...prev.recentlyUsedModels].slice(0, 10), + } + } else { + // Move existing model to front + return { + ...prev, + recentlyUsedModels: [ + modelId, + ...prev.recentlyUsedModels.filter((_, index) => index !== existingIndex) + ] + } + } + }); + }; + const isConfigured = Object.entries(settings.providers).length > 0; const contextValue: AISettingsContextType = { @@ -95,6 +125,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { addProvider, removeProvider, updateProvider, + addRecentlyUsedModel, isConfigured, }; diff --git a/src/contexts/AISettingsContext.ts b/src/contexts/AISettingsContext.ts index 9b4bf916..a8821ab6 100644 --- a/src/contexts/AISettingsContext.ts +++ b/src/contexts/AISettingsContext.ts @@ -7,6 +7,7 @@ export interface AIConnection { export interface AISettings { providers: Record; + recentlyUsedModels: string[]; } export interface AISettingsContextType { @@ -15,6 +16,7 @@ export interface AISettingsContextType { addProvider: (name: string, connection: AIConnection) => void; removeProvider: (name: string) => void; updateProvider: (name: string, connection: Partial) => void; + addRecentlyUsedModel: (modelId: string) => void; isConfigured: boolean; } diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index c450ae9d..4dde4c6a 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -38,7 +38,7 @@ export function useAIChat({ const [isLoading, setIsLoading] = useState(false); const [sessionName, setSessionName] = useState(''); const abortControllerRef = useRef(null); - const { settings, isConfigured } = useAISettings(); + const { settings, isConfigured, addRecentlyUsedModel } = useAISettings(); const { fs } = useFS(); // Save all messages to history @@ -164,11 +164,18 @@ export function useAIChat({ let accumulatedContent = ''; const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = []; let finishReason: string | null = null; + let hasRecordedModel = false; // Process the stream for await (const chunk of stream) { const delta = chunk.choices[0]?.delta; + // Track recently used model on first chunk + if (!hasRecordedModel && providerModel) { + addRecentlyUsedModel(providerModel); + hasRecordedModel = true; + } + if (delta?.content) { accumulatedContent += delta.content; setStreamingMessage(prev => prev ? { @@ -341,7 +348,7 @@ export function useAIChat({ setIsLoading(false); abortControllerRef.current = null; } - }, [isConfigured, isLoading, addMessage, messages, settings.providers, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps]); + }, [isConfigured, isLoading, addMessage, messages, settings.providers, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps, addRecentlyUsedModel]); // Load message history when component mounts or projectId changes useEffect(() => { diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts index 3d2f3a0d..704194f4 100644 --- a/src/hooks/useAIProjectId.test.ts +++ b/src/hooks/useAIProjectId.test.ts @@ -18,12 +18,13 @@ describe('useAIProjectId', () => { it('should return not configured when AI settings are not configured', () => { mockUseAISettings.mockReturnValue({ - settings: { providers: {} }, + settings: { providers: {}, recentlyUsedModels: [] }, isConfigured: false, updateSettings: vi.fn(), addProvider: vi.fn(), removeProvider: vi.fn(), updateProvider: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); const { result } = renderHook(() => useAIProjectId()); @@ -34,12 +35,13 @@ describe('useAIProjectId', () => { it('should throw error when trying to generate ID without configuration', async () => { mockUseAISettings.mockReturnValue({ - settings: { providers: {} }, + settings: { providers: {}, recentlyUsedModels: [] }, isConfigured: false, updateSettings: vi.fn(), addProvider: vi.fn(), removeProvider: vi.fn(), updateProvider: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); const { result } = renderHook(() => useAIProjectId()); @@ -54,13 +56,15 @@ describe('useAIProjectId', () => { settings: { providers: { openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - } + }, + recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), addProvider: vi.fn(), removeProvider: vi.fn(), updateProvider: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); const { result } = renderHook(() => useAIProjectId()); @@ -75,13 +79,15 @@ describe('useAIProjectId', () => { settings: { providers: { openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - } + }, + recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), addProvider: vi.fn(), removeProvider: vi.fn(), updateProvider: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); const { result } = renderHook(() => useAIProjectId());