mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Migrate AI settings and git settings to the VFS
This commit is contained in:
7 files changed
+597
-91
No files matched your search
@@ -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 }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
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 }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
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 }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
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 }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
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 }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
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']
|
||||
|
||||
@@ -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<AISettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
const [settings, setSettings] = useState<AISettings>(() => {
|
||||
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<AISettings>;
|
||||
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<AISettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
|
||||
@@ -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 (
|
||||
<GitSettingsProvider>
|
||||
{children}
|
||||
</GitSettingsProvider>
|
||||
<TestApp>
|
||||
<GitSettingsProvider>
|
||||
{children}
|
||||
</GitSettingsProvider>
|
||||
</TestApp>
|
||||
);
|
||||
}
|
||||
|
||||
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(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestWrapper>
|
||||
@@ -162,29 +205,35 @@ describe('GitSettingsProvider', () => {
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
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'));
|
||||
|
||||
|
||||
@@ -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<GitSettings>(() => {
|
||||
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<GitSettings>;
|
||||
return {
|
||||
credentials: settings.credentials || {},
|
||||
corsProxy: settings.corsProxy || DEFAULT_SETTINGS.corsProxy,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
}
|
||||
return DEFAULT_SETTINGS;
|
||||
});
|
||||
const { fs } = useFS();
|
||||
const [settings, setSettings] = useState<GitSettings>(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<GitSettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
|
||||
Reference in new issue
Block a user