diff --git a/AGENTS.md b/AGENTS.md index fad685d3..22d275ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,6 +13,9 @@ Shakespeare uses LightningFS to provide a browser-based virtual filesystem (VFS) ├── projects/ │ └── {projectId}/ # Individual project directory │ └── ... # Project files (package.json, src/, public/, etc.) +├── config/ # Configuration files +│ ├── ai.json # AI provider settings and API keys +│ └── git.json # Git credentials and repository settings └── tmp/ # Temporary files and scratch space └── ... # Various temporary files and directories ``` diff --git a/src/components/AISettingsProvider.test.tsx b/src/components/AISettingsProvider.test.tsx index 783d2a4a..2ef9d26d 100644 --- a/src/components/AISettingsProvider.test.tsx +++ b/src/components/AISettingsProvider.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { renderHook, act } from '@testing-library/react'; +import { renderHook, act, waitFor } from '@testing-library/react'; import { useQueryClient } from '@tanstack/react-query'; import React from 'react'; import { useAISettings } from '@/hooks/useAISettings'; @@ -17,25 +17,44 @@ Object.defineProperty(window, 'localStorage', { value: localStorageMock, }); +// Mock the config utils +vi.mock('@/lib/configUtils', () => ({ + readAISettings: vi.fn(), + writeAISettings: vi.fn(), +})); + describe('AISettingsProvider', () => { - beforeEach(() => { + beforeEach(async () => { vi.clearAllMocks(); localStorageMock.getItem.mockReturnValue(null); + + // Mock the read function to return default settings + const { readAISettings } = await import('@/lib/configUtils'); + vi.mocked(readAISettings).mockResolvedValue({ + providers: {}, + recentlyUsedModels: [], + }); }); - it('should initialize with empty recentlyUsedModels array', () => { + it('should initialize with empty recentlyUsedModels array', async () => { const { result } = renderHook(() => useAISettings(), { wrapper: ({ children }) => {children}, }); - expect(result.current.settings.recentlyUsedModels).toEqual([]); + await waitFor(() => { + expect(result.current.settings.recentlyUsedModels).toEqual([]); + }); }); - it('should add recently used models correctly', () => { + it('should add recently used models correctly', async () => { const { result } = renderHook(() => useAISettings(), { wrapper: ({ children }) => {children}, }); + await waitFor(() => { + expect(result.current.settings.recentlyUsedModels).toEqual([]); + }); + act(() => { result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet'); }); @@ -45,11 +64,15 @@ describe('AISettingsProvider', () => { ]); }); - it('should move existing model to front when used again', () => { + it('should move existing model to front when used again', async () => { const { result } = renderHook(() => useAISettings(), { wrapper: ({ children }) => {children}, }); + await waitFor(() => { + expect(result.current.settings.recentlyUsedModels).toEqual([]); + }); + // Add multiple models act(() => { result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet'); @@ -75,11 +98,15 @@ describe('AISettingsProvider', () => { ]); }); - it('should limit recently used models to 10 items', () => { + it('should limit recently used models to 10 items', async () => { const { result } = renderHook(() => useAISettings(), { wrapper: ({ children }) => {children}, }); + await waitFor(() => { + expect(result.current.settings.recentlyUsedModels).toEqual([]); + }); + // Add 12 models act(() => { for (let i = 1; i <= 12; i++) { @@ -93,27 +120,31 @@ describe('AISettingsProvider', () => { expect(result.current.settings.recentlyUsedModels[9]).toBe('provider/model-3'); }); - it('should migrate old settings without recentlyUsedModels', () => { + it('should migrate old settings without recentlyUsedModels', async () => { const oldSettings = { providers: { openrouter: { baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' } - } + }, + recentlyUsedModels: [] }; - localStorageMock.getItem.mockReturnValue(JSON.stringify(oldSettings)); + const { readAISettings } = await import('@/lib/configUtils'); + vi.mocked(readAISettings).mockResolvedValue(oldSettings); const { result } = renderHook(() => useAISettings(), { wrapper: ({ children }) => {children}, }); - expect(result.current.settings.recentlyUsedModels).toEqual([]); - expect(result.current.settings.providers).toEqual(oldSettings.providers); + await waitFor(() => { + expect(result.current.settings.recentlyUsedModels).toEqual([]); + expect(result.current.settings.providers).toEqual(oldSettings.providers); + }); }); - it('should invalidate provider-models query when updateSettings is called with providers', () => { + it('should invalidate provider-models query when updateSettings is called with providers', async () => { // Mock the QueryClient.invalidateQueries method const mockInvalidateQueries = vi.fn(); @@ -132,6 +163,10 @@ describe('AISettingsProvider', () => { ), }); + await waitFor(() => { + expect(result.current.settings.recentlyUsedModels).toEqual([]); + }); + act(() => { result.current.updateSettings({ providers: { @@ -146,7 +181,7 @@ describe('AISettingsProvider', () => { expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-models'] }); }); - it('should not invalidate provider-models query when updateSettings is called without providers', () => { + it('should not invalidate provider-models query when updateSettings is called without providers', async () => { // Mock the QueryClient.invalidateQueries method const mockInvalidateQueries = vi.fn(); @@ -165,6 +200,10 @@ describe('AISettingsProvider', () => { ), }); + await waitFor(() => { + expect(result.current.settings.recentlyUsedModels).toEqual([]); + }); + act(() => { result.current.updateSettings({ recentlyUsedModels: ['test-model'] diff --git a/src/components/AISettingsProvider.tsx b/src/components/AISettingsProvider.tsx index 6d06a4de..5788ba54 100644 --- a/src/components/AISettingsProvider.tsx +++ b/src/components/AISettingsProvider.tsx @@ -1,6 +1,8 @@ import { useQueryClient } from '@tanstack/react-query'; import { ReactNode, useState, useEffect } from 'react'; import { AISettingsContext, type AISettings, type AIConnection, type AISettingsContextType } from '@/contexts/AISettingsContext'; +import { useFS } from '@/hooks/useFS'; +import { readAISettings, writeAISettings } from '@/lib/configUtils'; interface AISettingsProviderProps { children: ReactNode; @@ -11,33 +13,43 @@ const DEFAULT_SETTINGS: AISettings = { recentlyUsedModels: [], }; -const STORAGE_KEY = 'ai-settings'; - export function AISettingsProvider({ children }: AISettingsProviderProps) { const queryClient = useQueryClient(); + const { fs } = useFS(); + const [settings, setSettings] = useState(DEFAULT_SETTINGS); + const [isInitialized, setIsInitialized] = useState(false); - const [settings, setSettings] = useState(() => { - const stored = localStorage.getItem(STORAGE_KEY); - if (stored) { - try { - const parsed = JSON.parse(stored); - if (parsed && typeof parsed === 'object' && 'providers' in parsed) { - const settings = parsed as Partial; - return { - providers: settings.providers || {}, - recentlyUsedModels: settings.recentlyUsedModels || [], - }; - } - } catch { - return DEFAULT_SETTINGS; - } - } - return DEFAULT_SETTINGS; - }); - + // Initialize settings from VFS on mount useEffect(() => { - localStorage.setItem(STORAGE_KEY, JSON.stringify(settings)); - }, [settings]); + const initializeSettings = async () => { + try { + const settings = await readAISettings(fs); + setSettings(settings); + } catch (error) { + console.error('Failed to initialize AI settings:', error); + setSettings(DEFAULT_SETTINGS); + } finally { + setIsInitialized(true); + } + }; + + initializeSettings(); + }, [fs]); + + // Save settings to VFS whenever they change (but not during initialization) + useEffect(() => { + if (!isInitialized) return; + + const saveSettings = async () => { + try { + await writeAISettings(fs, settings); + } catch (error) { + console.error('Failed to save AI settings:', error); + } + }; + + saveSettings(); + }, [fs, settings, isInitialized]); const updateSettings = (newSettings: Partial) => { setSettings(prev => ({ ...prev, ...newSettings })); diff --git a/src/components/GitSettingsProvider.test.tsx b/src/components/GitSettingsProvider.test.tsx index f15c1963..96a201f3 100644 --- a/src/components/GitSettingsProvider.test.tsx +++ b/src/components/GitSettingsProvider.test.tsx @@ -1,9 +1,16 @@ -import { describe, it, expect, beforeEach } from 'vitest'; -import { render, screen, fireEvent } from '@testing-library/react'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import { ReactNode } from 'react'; import { GitSettingsProvider } from './GitSettingsProvider'; import { useGitSettings } from '@/hooks/useGitSettings'; import type { GitCredential } from '@/contexts/GitSettingsContext'; +import { TestApp } from '@/test/TestApp'; + +// Mock the config utils +vi.mock('@/lib/configUtils', () => ({ + readGitSettings: vi.fn(), + writeGitSettings: vi.fn(), +})); // Test component that uses the hook function TestComponent() { @@ -52,35 +59,51 @@ function TestComponent() { function TestWrapper({ children }: { children: ReactNode }) { return ( - - {children} - + + + {children} + + ); } describe('GitSettingsProvider', () => { - beforeEach(() => { + beforeEach(async () => { + vi.clearAllMocks(); localStorage.clear(); + + // Mock the read function to return default settings + const { readGitSettings } = await import('@/lib/configUtils'); + vi.mocked(readGitSettings).mockResolvedValue({ + credentials: {}, + corsProxy: 'https://cors.isomorphic-git.org', + }); }); - it('provides initial empty state', () => { + it('provides initial empty state', async () => { render( ); - expect(screen.getByTestId('configured')).toHaveTextContent('not-configured'); - expect(screen.getByTestId('count')).toHaveTextContent('0'); + await waitFor(() => { + expect(screen.getByTestId('configured')).toHaveTextContent('not-configured'); + expect(screen.getByTestId('count')).toHaveTextContent('0'); + }); }); - it('can add credentials', () => { + it('can add credentials', async () => { render( ); + await waitFor(() => { + expect(screen.getByTestId('configured')).toHaveTextContent('not-configured'); + }); + fireEvent.click(screen.getByText('Add GitHub')); expect(screen.getByTestId('configured')).toHaveTextContent('configured'); @@ -88,13 +111,17 @@ describe('GitSettingsProvider', () => { expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token'); }); - it('can update credentials', () => { + it('can update credentials', async () => { render( ); + await waitFor(() => { + expect(screen.getByTestId('configured')).toHaveTextContent('not-configured'); + }); + // First add a credential fireEvent.click(screen.getByText('Add GitHub')); expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token'); @@ -104,13 +131,17 @@ describe('GitSettingsProvider', () => { expect(screen.getByTestId('github-creds')).toHaveTextContent('git:updated-token'); }); - it('can remove credentials', () => { + it('can remove credentials', async () => { render( ); + await waitFor(() => { + expect(screen.getByTestId('configured')).toHaveTextContent('not-configured'); + }); + // First add a credential fireEvent.click(screen.getByText('Add GitHub')); expect(screen.getByTestId('configured')).toHaveTextContent('configured'); @@ -122,29 +153,39 @@ describe('GitSettingsProvider', () => { expect(screen.getByTestId('count')).toHaveTextContent('0'); }); - it('persists settings to localStorage', () => { + it('persists settings to VFS', async () => { + const { writeGitSettings } = await import('@/lib/configUtils'); + render( ); + await waitFor(() => { + expect(screen.getByTestId('configured')).toHaveTextContent('not-configured'); + }); + fireEvent.click(screen.getByText('Add GitHub')); - // Check that settings were saved to localStorage - const stored = localStorage.getItem('git-settings'); - expect(stored).toBeTruthy(); - - const parsed = JSON.parse(stored!); - expect(parsed.credentials['https://github.com']).toEqual({ - username: 'git', - password: 'test-token', + // Check that settings were saved to VFS + await waitFor(() => { + expect(writeGitSettings).toHaveBeenCalledWith( + expect.anything(), // fs instance + expect.objectContaining({ + credentials: { + 'https://github.com': { + username: 'git', + password: 'test-token', + } + }, + corsProxy: 'https://cors.isomorphic-git.org' + }) + ); }); - expect(parsed.corsProxy).toBe('https://cors.isomorphic-git.org'); }); - it('loads settings from localStorage', () => { - // Pre-populate localStorage + it('loads settings from VFS', async () => { const settings = { credentials: { 'https://gitlab.com': { @@ -154,7 +195,9 @@ describe('GitSettingsProvider', () => { }, corsProxy: 'https://custom-cors.example.com', }; - localStorage.setItem('git-settings', JSON.stringify(settings)); + + const { readGitSettings } = await import('@/lib/configUtils'); + vi.mocked(readGitSettings).mockResolvedValue(settings); render( @@ -162,29 +205,35 @@ describe('GitSettingsProvider', () => { ); - expect(screen.getByTestId('configured')).toHaveTextContent('configured'); - expect(screen.getByTestId('count')).toHaveTextContent('1'); - expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com'); + await waitFor(() => { + expect(screen.getByTestId('configured')).toHaveTextContent('configured'); + expect(screen.getByTestId('count')).toHaveTextContent('1'); + expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com'); + }); }); - it('provides default CORS proxy', () => { + it('provides default CORS proxy', async () => { render( ); - expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org'); + await waitFor(() => { + expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org'); + }); }); - it('can update CORS proxy', () => { + it('can update CORS proxy', async () => { render( ); - expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org'); + await waitFor(() => { + expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org'); + }); fireEvent.click(screen.getByText('Update CORS Proxy')); diff --git a/src/components/GitSettingsProvider.tsx b/src/components/GitSettingsProvider.tsx index 61e32d07..3f49fbf3 100644 --- a/src/components/GitSettingsProvider.tsx +++ b/src/components/GitSettingsProvider.tsx @@ -1,5 +1,7 @@ import { ReactNode, useState, useEffect } from 'react'; import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext'; +import { useFS } from '@/hooks/useFS'; +import { readGitSettings, writeGitSettings } from '@/lib/configUtils'; interface GitSettingsProviderProps { children: ReactNode; @@ -10,31 +12,42 @@ const DEFAULT_SETTINGS: GitSettings = { corsProxy: 'https://cors.isomorphic-git.org', }; -const STORAGE_KEY = 'git-settings'; - export function GitSettingsProvider({ children }: GitSettingsProviderProps) { - const [settings, setSettings] = useState(() => { - const stored = localStorage.getItem(STORAGE_KEY); - if (stored) { - try { - const parsed = JSON.parse(stored); - if (parsed && typeof parsed === 'object' && 'credentials' in parsed) { - const settings = parsed as Partial; - return { - credentials: settings.credentials || {}, - corsProxy: settings.corsProxy || DEFAULT_SETTINGS.corsProxy, - }; - } - } catch { - return DEFAULT_SETTINGS; - } - } - return DEFAULT_SETTINGS; - }); + const { fs } = useFS(); + const [settings, setSettings] = useState(DEFAULT_SETTINGS); + const [isInitialized, setIsInitialized] = useState(false); + // Initialize settings from VFS on mount useEffect(() => { - localStorage.setItem(STORAGE_KEY, JSON.stringify(settings)); - }, [settings]); + const initializeSettings = async () => { + try { + const settings = await readGitSettings(fs); + setSettings(settings); + } catch (error) { + console.error('Failed to initialize Git settings:', error); + setSettings(DEFAULT_SETTINGS); + } finally { + setIsInitialized(true); + } + }; + + initializeSettings(); + }, [fs]); + + // Save settings to VFS whenever they change (but not during initialization) + useEffect(() => { + if (!isInitialized) return; + + const saveSettings = async () => { + try { + await writeGitSettings(fs, settings); + } catch (error) { + console.error('Failed to save Git settings:', error); + } + }; + + saveSettings(); + }, [fs, settings, isInitialized]); const updateSettings = (newSettings: Partial) => { setSettings(prev => ({ ...prev, ...newSettings })); diff --git a/src/lib/configUtils.test.ts b/src/lib/configUtils.test.ts new file mode 100644 index 00000000..f406a371 --- /dev/null +++ b/src/lib/configUtils.test.ts @@ -0,0 +1,231 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { + readAISettings, + writeAISettings, + readGitSettings, + writeGitSettings +} from './configUtils'; +import type { JSRuntimeFS } from './JSRuntime'; +import type { AISettings } from '@/contexts/AISettingsContext'; +import type { GitSettings } from '@/contexts/GitSettingsContext'; + +// Mock filesystem +const createMockFS = (): JSRuntimeFS => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + mkdir: vi.fn(), + stat: vi.fn(), + readdir: vi.fn(), + rmdir: vi.fn(), + unlink: vi.fn(), + lstat: vi.fn(), + rename: vi.fn(), + readlink: vi.fn(), + symlink: vi.fn(), +}); + +// Mock localStorage +const createMockLocalStorage = () => { + const storage: Record = {}; + return { + getItem: vi.fn((key: string) => storage[key] || null), + setItem: vi.fn((key: string, value: string) => { storage[key] = value; }), + removeItem: vi.fn((key: string) => { delete storage[key]; }), + clear: vi.fn(() => { Object.keys(storage).forEach(key => delete storage[key]); }), + length: 0, + key: vi.fn(), + }; +}; + +describe('configUtils', () => { + let mockFS: JSRuntimeFS; + let mockLocalStorage: ReturnType; + + beforeEach(() => { + mockFS = createMockFS(); + mockLocalStorage = createMockLocalStorage(); + + // Replace global localStorage + Object.defineProperty(window, 'localStorage', { + value: mockLocalStorage, + writable: true, + }); + }); + + describe('AI Settings', () => { + const sampleAISettings: AISettings = { + providers: { + 'openai': { + baseURL: 'https://api.openai.com/v1', + apiKey: 'sk-test123', + }, + }, + recentlyUsedModels: ['gpt-4', 'gpt-3.5-turbo'], + }; + + describe('readAISettings', () => { + it('should read AI settings from VFS', async () => { + vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(sampleAISettings)); + + const result = await readAISettings(mockFS); + + expect(mockFS.readFile).toHaveBeenCalledWith('/config/ai.json', 'utf8'); + expect(result).toEqual(sampleAISettings); + }); + + it('should return default settings if file does not exist and no localStorage data', async () => { + vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found')); + mockLocalStorage.getItem.mockReturnValue(null); + + const result = await readAISettings(mockFS); + + expect(result).toEqual({ + providers: {}, + recentlyUsedModels: [], + }); + }); + + it('should return default settings if JSON is invalid and no localStorage data', async () => { + vi.mocked(mockFS.readFile).mockResolvedValue('invalid json'); + mockLocalStorage.getItem.mockReturnValue(null); + + const result = await readAISettings(mockFS); + + expect(result).toEqual({ + providers: {}, + recentlyUsedModels: [], + }); + }); + + it('should migrate from localStorage if VFS file does not exist', async () => { + vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found')); + vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found')); + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleAISettings)); + + const result = await readAISettings(mockFS); + + expect(result).toEqual(sampleAISettings); + expect(mockLocalStorage.getItem).toHaveBeenCalledWith('ai-settings'); + expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('ai-settings'); + expect(mockFS.writeFile).toHaveBeenCalledWith( + '/config/ai.json', + JSON.stringify(sampleAISettings, null, 2), + 'utf8' + ); + }); + }); + + describe('writeAISettings', () => { + it('should write AI settings to VFS', async () => { + vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found')); + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + await writeAISettings(mockFS, sampleAISettings); + + expect(mockFS.mkdir).toHaveBeenCalledWith('/config', { recursive: true }); + expect(mockFS.writeFile).toHaveBeenCalledWith( + '/config/ai.json', + JSON.stringify(sampleAISettings, null, 2), + 'utf8' + ); + }); + + it('should not create directory if it already exists', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + await writeAISettings(mockFS, sampleAISettings); + + expect(mockFS.mkdir).not.toHaveBeenCalled(); + expect(mockFS.writeFile).toHaveBeenCalledWith( + '/config/ai.json', + JSON.stringify(sampleAISettings, null, 2), + 'utf8' + ); + }); + }); + + + }); + + describe('Git Settings', () => { + const sampleGitSettings: GitSettings = { + credentials: { + 'github.com': { + username: 'user', + password: 'token123', + }, + }, + corsProxy: 'https://cors.isomorphic-git.org', + }; + + describe('readGitSettings', () => { + it('should read Git settings from VFS', async () => { + vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(sampleGitSettings)); + + const result = await readGitSettings(mockFS); + + expect(mockFS.readFile).toHaveBeenCalledWith('/config/git.json', 'utf8'); + expect(result).toEqual(sampleGitSettings); + }); + + it('should return default settings if file does not exist and no localStorage data', async () => { + vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found')); + mockLocalStorage.getItem.mockReturnValue(null); + + const result = await readGitSettings(mockFS); + + expect(result).toEqual({ + credentials: {}, + corsProxy: 'https://cors.isomorphic-git.org', + }); + }); + + it('should migrate from localStorage if VFS file does not exist', async () => { + vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found')); + vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found')); + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleGitSettings)); + + const result = await readGitSettings(mockFS); + + expect(result).toEqual(sampleGitSettings); + expect(mockLocalStorage.getItem).toHaveBeenCalledWith('git-settings'); + expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('git-settings'); + expect(mockFS.writeFile).toHaveBeenCalledWith( + '/config/git.json', + JSON.stringify(sampleGitSettings, null, 2), + 'utf8' + ); + }); + }); + + describe('writeGitSettings', () => { + it('should write Git settings to VFS', async () => { + vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found')); + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + await writeGitSettings(mockFS, sampleGitSettings); + + expect(mockFS.mkdir).toHaveBeenCalledWith('/config', { recursive: true }); + expect(mockFS.writeFile).toHaveBeenCalledWith( + '/config/git.json', + JSON.stringify(sampleGitSettings, null, 2), + 'utf8' + ); + }); + }); + + + }); +}); \ No newline at end of file diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts new file mode 100644 index 00000000..95b7c2d0 --- /dev/null +++ b/src/lib/configUtils.ts @@ -0,0 +1,159 @@ +import type { JSRuntimeFS } from '@/lib/JSRuntime'; +import type { AISettings } from '@/contexts/AISettingsContext'; +import type { GitSettings } from '@/contexts/GitSettingsContext'; + +const CONFIG_DIR = '/config'; +const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`; +const GIT_CONFIG_PATH = `${CONFIG_DIR}/git.json`; + +/** + * Ensures the config directory exists + */ +async function ensureConfigDir(fs: JSRuntimeFS): Promise { + try { + await fs.stat(CONFIG_DIR); + } catch { + await fs.mkdir(CONFIG_DIR, { recursive: true }); + } +} + +/** + * Migrate AI settings from localStorage to VFS (internal function) + */ +async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise { + // If not in VFS, try to migrate from localStorage + const stored = localStorage.getItem('ai-settings'); + if (stored) { + try { + const parsed = JSON.parse(stored); + if (parsed && typeof parsed === 'object' && 'providers' in parsed) { + const settings: AISettings = { + providers: parsed.providers || {}, + recentlyUsedModels: parsed.recentlyUsedModels || [], + }; + + // Write to VFS and remove from localStorage + await writeAISettings(fs, settings); + localStorage.removeItem('ai-settings'); + + return settings; + } + } catch { + // If parsing fails, return null + } + } + + return null; +} + +/** + * Read AI settings from VFS (with automatic migration from localStorage) + */ +export async function readAISettings(fs: JSRuntimeFS): Promise { + const defaultSettings: AISettings = { + providers: {}, + recentlyUsedModels: [], + }; + + // Try to read from VFS first + try { + const content = await fs.readFile(AI_CONFIG_PATH, 'utf8'); + const parsed = JSON.parse(content); + + if (parsed && typeof parsed === 'object' && 'providers' in parsed) { + return { + providers: parsed.providers || {}, + recentlyUsedModels: parsed.recentlyUsedModels || [], + }; + } + } catch { + // File doesn't exist or is invalid, try migration + } + + // If not in VFS, try to migrate from localStorage + const migratedSettings = await migrateAISettingsFromLocalStorage(fs); + if (migratedSettings) { + return migratedSettings; + } + + return defaultSettings; +} + +/** + * Write AI settings to VFS + */ +export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Promise { + await ensureConfigDir(fs); + await fs.writeFile(AI_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8'); +} + +/** + * Migrate Git settings from localStorage to VFS (internal function) + */ +async function migrateGitSettingsFromLocalStorage(fs: JSRuntimeFS): Promise { + // If not in VFS, try to migrate from localStorage + const stored = localStorage.getItem('git-settings'); + if (stored) { + try { + const parsed = JSON.parse(stored); + if (parsed && typeof parsed === 'object' && 'credentials' in parsed) { + const settings: GitSettings = { + credentials: parsed.credentials || {}, + corsProxy: parsed.corsProxy || 'https://cors.isomorphic-git.org', + }; + + // Write to VFS and remove from localStorage + await writeGitSettings(fs, settings); + localStorage.removeItem('git-settings'); + + return settings; + } + } catch { + // If parsing fails, return null + } + } + + return null; +} + +/** + * Read Git settings from VFS (with automatic migration from localStorage) + */ +export async function readGitSettings(fs: JSRuntimeFS): Promise { + const defaultSettings: GitSettings = { + credentials: {}, + corsProxy: 'https://cors.isomorphic-git.org', + }; + + // Try to read from VFS first + try { + const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8'); + const parsed = JSON.parse(content); + + if (parsed && typeof parsed === 'object' && 'credentials' in parsed) { + return { + credentials: parsed.credentials || {}, + corsProxy: parsed.corsProxy || 'https://cors.isomorphic-git.org', + }; + } + } catch { + // File doesn't exist or is invalid, try migration + } + + // If not in VFS, try to migrate from localStorage + const migratedSettings = await migrateGitSettingsFromLocalStorage(fs); + if (migratedSettings) { + return migratedSettings; + } + + return defaultSettings; +} + +/** + * Write Git settings to VFS + */ +export async function writeGitSettings(fs: JSRuntimeFS, settings: GitSettings): Promise { + await ensureConfigDir(fs); + await fs.writeFile(GIT_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8'); +} +