mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Convert AI providers into array instead of object, allow dragging to change their order
This commit is contained in:
27 files changed
+556
-283
No files matched your search
Generated
+56
@@ -8,6 +8,9 @@
|
||||
"name": "mkstack",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^6.0.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
@@ -347,6 +350,59 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/core": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/sortable": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
|
||||
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@dnd-kit/core": "^6.3.0",
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/utilities": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.5",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz",
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^6.0.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
|
||||
@@ -31,7 +31,7 @@ describe('AISettingsProvider', () => {
|
||||
// Mock the read function to return default settings
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue({
|
||||
providers: {},
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
@@ -122,12 +122,13 @@ describe('AISettingsProvider', () => {
|
||||
|
||||
it('should migrate old settings without recentlyUsedModels', async () => {
|
||||
const oldSettings = {
|
||||
providers: {
|
||||
openrouter: {
|
||||
providers: [
|
||||
{
|
||||
id: 'openrouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
},
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
};
|
||||
|
||||
@@ -169,12 +170,13 @@ describe('AISettingsProvider', () => {
|
||||
|
||||
act(() => {
|
||||
result.current.updateSettings({
|
||||
providers: {
|
||||
'test-provider': {
|
||||
providers: [
|
||||
{
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { AISettingsContext, type AISettings, type AIConnection, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||
|
||||
@@ -9,7 +9,7 @@ interface AISettingsProviderProps {
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: AISettings = {
|
||||
providers: {},
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
};
|
||||
|
||||
@@ -60,38 +60,40 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const addProvider = (name: string, connection: AIConnection) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers: {
|
||||
...prev.providers,
|
||||
[name]: connection,
|
||||
},
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
|
||||
const removeProvider = (name: string) => {
|
||||
const setProvider = (provider: AIProvider) => {
|
||||
setSettings(prev => {
|
||||
const { [name]: removed, ...rest } = prev.providers;
|
||||
return {
|
||||
...prev,
|
||||
providers: rest,
|
||||
};
|
||||
const existingIndex = prev.providers.findIndex(p => p.id === provider.id);
|
||||
if (existingIndex >= 0) {
|
||||
// Update existing provider
|
||||
return {
|
||||
...prev,
|
||||
providers: prev.providers.map(p =>
|
||||
p.id === provider.id ? provider : p
|
||||
),
|
||||
};
|
||||
} else {
|
||||
// Add new provider
|
||||
return {
|
||||
...prev,
|
||||
providers: [...prev.providers, provider],
|
||||
};
|
||||
}
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
|
||||
const updateProvider = (name: string, connection: Partial<AIConnection>) => {
|
||||
const removeProvider = (id: string) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers: {
|
||||
...prev.providers,
|
||||
[name]: {
|
||||
...prev.providers[name],
|
||||
...connection,
|
||||
},
|
||||
},
|
||||
providers: prev.providers.filter(provider => provider.id !== id),
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
|
||||
const setProviders = (providers: AIProvider[]) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers,
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
@@ -120,14 +122,14 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
});
|
||||
};
|
||||
|
||||
const isConfigured = Object.entries(settings.providers).length > 0;
|
||||
const isConfigured = settings.providers.length > 0;
|
||||
|
||||
const contextValue: AISettingsContextType = {
|
||||
settings,
|
||||
updateSettings,
|
||||
addProvider,
|
||||
setProvider,
|
||||
removeProvider,
|
||||
updateProvider,
|
||||
setProviders,
|
||||
addRecentlyUsedModel,
|
||||
isConfigured,
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { CreditsBadge } from './CreditsBadge';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
|
||||
// Mock the useAICredits hook
|
||||
vi.mock('@/hooks/useAICredits', () => ({
|
||||
@@ -16,7 +16,7 @@ vi.mock('@/hooks/useAICredits', () => ({
|
||||
// Mock the fetch function
|
||||
global.fetch = vi.fn();
|
||||
|
||||
const mockConnection: AIConnection = {
|
||||
const mockConnection = {
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface CreditsBadgeProps {
|
||||
providerId: string;
|
||||
connection: AIConnection;
|
||||
connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
};
|
||||
className?: string;
|
||||
onOpenDialog?: () => void;
|
||||
}
|
||||
|
||||
@@ -2,12 +2,12 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
|
||||
// Mock the fetch function
|
||||
global.fetch = vi.fn();
|
||||
|
||||
const mockConnection: AIConnection = {
|
||||
const mockConnection = {
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
@@ -13,13 +13,15 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface CreditsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
providerId: string;
|
||||
connection: AIConnection;
|
||||
connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
interface Payment {
|
||||
|
||||
@@ -34,13 +34,14 @@ describe('ModelSelector', () => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {}, recentlyUsedModels: [] },
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
@@ -69,13 +70,14 @@ describe('ModelSelector', () => {
|
||||
});
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {}, recentlyUsedModels },
|
||||
settings: { providers: [], recentlyUsedModels },
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -115,13 +117,14 @@ describe('ModelSelector', () => {
|
||||
});
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {}, recentlyUsedModels },
|
||||
settings: { providers: [], recentlyUsedModels },
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -163,13 +166,14 @@ describe('ModelSelector', () => {
|
||||
});
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {}, recentlyUsedModels },
|
||||
settings: { providers: [], recentlyUsedModels },
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -205,13 +209,14 @@ describe('ModelSelector', () => {
|
||||
});
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {}, recentlyUsedModels: [] }, // No recently used models
|
||||
settings: { providers: [], recentlyUsedModels: [] }, // No recently used models
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
render(
|
||||
|
||||
@@ -6,9 +6,14 @@ import { TestApp } from '@/test/TestApp';
|
||||
// Mock the hooks
|
||||
vi.mock('@/hooks/useAISettings', () => ({
|
||||
useAISettings: () => ({
|
||||
settings: { providers: {}, recentlyUsedModels: [] },
|
||||
addProvider: vi.fn(),
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
isConfigured: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
|
||||
@@ -14,8 +14,6 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { CreditsDialog } from '@/components/CreditsDialog';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface OnboardingDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
@@ -23,7 +21,8 @@ interface OnboardingDialogProps {
|
||||
|
||||
type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion';
|
||||
|
||||
const SHAKESPEARE_PROVIDER: AIConnection = {
|
||||
const SHAKESPEARE_PROVIDER = {
|
||||
id: "shakespeare",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
nostr: true,
|
||||
};
|
||||
@@ -34,7 +33,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
const [isSettingUp, setIsSettingUp] = useState(false);
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const { addProvider, addRecentlyUsedModel } = useAISettings();
|
||||
const { setProvider, addRecentlyUsedModel } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const login = useLoginActions();
|
||||
const { models, isLoading: isLoadingModels } = useProviderModels();
|
||||
@@ -54,7 +53,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
}
|
||||
|
||||
// Add Shakespeare provider to their config
|
||||
addProvider('shakespeare', SHAKESPEARE_PROVIDER);
|
||||
setProvider(SHAKESPEARE_PROVIDER);
|
||||
|
||||
// Move to model selection
|
||||
setStep('model-selection');
|
||||
|
||||
@@ -8,10 +8,15 @@ vi.mock('@/hooks/useAISettings', () => ({
|
||||
useAISettings: () => ({
|
||||
isConfigured: true,
|
||||
settings: {
|
||||
providers: {},
|
||||
providers: [],
|
||||
recentlyUsedModels: ['gpt-4'],
|
||||
},
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface AIConnection {
|
||||
export interface AIProvider {
|
||||
id: string;
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
}
|
||||
|
||||
export interface AISettings {
|
||||
providers: Record<string, AIConnection>;
|
||||
providers: AIProvider[];
|
||||
recentlyUsedModels: string[];
|
||||
}
|
||||
|
||||
export interface AISettingsContextType {
|
||||
settings: AISettings;
|
||||
updateSettings: (settings: Partial<AISettings>) => void;
|
||||
addProvider: (name: string, connection: AIConnection) => void;
|
||||
removeProvider: (name: string) => void;
|
||||
updateProvider: (name: string, connection: Partial<AIConnection>) => void;
|
||||
setProvider: (provider: AIProvider) => void;
|
||||
removeProvider: (id: string) => void;
|
||||
setProviders: (providers: AIProvider[]) => void;
|
||||
addRecentlyUsedModel: (modelId: string) => void;
|
||||
isConfigured: boolean;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { z } from 'zod';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Zod schemas for the two possible response formats
|
||||
const creditsResponseV1Schema = z.object({
|
||||
@@ -32,7 +31,11 @@ export interface CreditsResponse {
|
||||
* @param connection - The AI connection configuration
|
||||
* @returns Query result with credits information
|
||||
*/
|
||||
export function useAICredits(providerId: string, connection: AIConnection) {
|
||||
export function useAICredits(providerId: string, connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
}) {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useQuery({
|
||||
|
||||
@@ -63,12 +63,12 @@ describe('useAIProjectId', () => {
|
||||
|
||||
it('should return not configured when AI settings are not configured', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {}, recentlyUsedModels: [] },
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -80,12 +80,13 @@ describe('useAIProjectId', () => {
|
||||
|
||||
it('should throw error when trying to generate ID without configuration', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {}, recentlyUsedModels: [] },
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -99,16 +100,17 @@ describe('useAIProjectId', () => {
|
||||
it('should throw error when prompt is empty', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -122,16 +124,17 @@ describe('useAIProjectId', () => {
|
||||
it('should have configured status when providers are available', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -144,16 +147,17 @@ describe('useAIProjectId', () => {
|
||||
it('should successfully generate project ID', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -162,9 +166,9 @@ describe('useAIProjectId', () => {
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('test-project-name');
|
||||
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
});
|
||||
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
]);
|
||||
expect(mockCreateAIClient).toHaveBeenCalledWith(
|
||||
{ apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
undefined
|
||||
@@ -174,16 +178,17 @@ describe('useAIProjectId', () => {
|
||||
it('should fallback to untitled when project exists', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -226,16 +231,17 @@ describe('useAIProjectId', () => {
|
||||
it('should fallback to untitled-1 when untitled exists', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -280,16 +286,17 @@ describe('useAIProjectId', () => {
|
||||
it('should fallback to untitled when AI generates too long name', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -329,16 +336,17 @@ describe('useAIProjectId', () => {
|
||||
it('should fallback to untitled when AI generates invalid name', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -378,16 +386,17 @@ describe('useAIProjectId', () => {
|
||||
it('should fallback to untitled-2 when untitled and untitled-1 exist', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -434,16 +443,17 @@ describe('useAIProjectId', () => {
|
||||
it('should handle loading state correctly', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
|
||||
@@ -39,12 +39,13 @@ export function useProviderModels(): ModelFetchResult {
|
||||
isLoading,
|
||||
refetch,
|
||||
} = useQuery({
|
||||
queryKey: ['provider-models'],
|
||||
queryKey: ['provider-models', settings.providers],
|
||||
queryFn: async () => {
|
||||
const errors: string[] = [];
|
||||
|
||||
// Fetch models from each configured provider in parallel
|
||||
const providerPromises = Object.entries(settings.providers).map(async ([providerKey, connection]) => {
|
||||
const providerPromises = settings.providers.map(async (provider) => {
|
||||
const { id: providerKey, ...connection } = provider;
|
||||
try {
|
||||
const openai = createAIClient(connection, user);
|
||||
|
||||
@@ -126,7 +127,7 @@ export function useProviderModels(): ModelFetchResult {
|
||||
|
||||
return allModels;
|
||||
},
|
||||
enabled: Object.keys(settings.providers).length > 0,
|
||||
enabled: settings.providers.length > 0,
|
||||
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
|
||||
retry: false, // Don't retry on failure
|
||||
});
|
||||
|
||||
@@ -25,12 +25,13 @@ const mockFS: JSRuntimeFS = {
|
||||
describe('SessionManager', () => {
|
||||
let sessionManager: SessionManager;
|
||||
const mockAISettings = {
|
||||
providers: {
|
||||
'test-provider': {
|
||||
providers: [
|
||||
{
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { parseProviderModel } from './parseProviderModel';
|
||||
import { createAIClient } from './ai-client';
|
||||
import type { Tool } from './tools/Tool';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
role: 'assistant';
|
||||
@@ -52,13 +53,13 @@ export class SessionManager {
|
||||
private sessions = new Map<string, SessionState>();
|
||||
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
|
||||
private fs: JSRuntimeFS;
|
||||
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> };
|
||||
private aiSettings: { providers: AIProvider[] };
|
||||
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
|
||||
private getCurrentUser?: () => NUser | undefined;
|
||||
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> },
|
||||
aiSettings: { providers: AIProvider[] },
|
||||
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
|
||||
getCurrentUser?: () => NUser | undefined
|
||||
) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import OpenAI from 'openai';
|
||||
import { NIP98Client } from '@nostrify/nostrify';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
|
||||
/**
|
||||
@@ -8,7 +7,11 @@ import type { NUser } from '@nostrify/react/login';
|
||||
* If the connection requires Nostr authentication (NIP-98), it will use
|
||||
* the NIP98Client for authenticated requests.
|
||||
*/
|
||||
export function createAIClient(connection: AIConnection, user?: NUser): OpenAI {
|
||||
export function createAIClient(connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
}, user?: NUser): OpenAI {
|
||||
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
|
||||
baseURL: connection.baseURL,
|
||||
apiKey: connection.apiKey ?? '',
|
||||
|
||||
@@ -54,12 +54,13 @@ describe('configUtils', () => {
|
||||
|
||||
describe('AI Settings', () => {
|
||||
const sampleAISettings: AISettings = {
|
||||
providers: {
|
||||
'openai': {
|
||||
providers: [
|
||||
{
|
||||
id: 'openai',
|
||||
baseURL: 'https://api.openai.com/v1',
|
||||
apiKey: 'sk-test123',
|
||||
},
|
||||
},
|
||||
],
|
||||
recentlyUsedModels: ['gpt-4', 'gpt-3.5-turbo'],
|
||||
};
|
||||
|
||||
@@ -80,7 +81,7 @@ describe('configUtils', () => {
|
||||
const result = await readAISettings(mockFS);
|
||||
|
||||
expect(result).toEqual({
|
||||
providers: {},
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
@@ -92,7 +93,7 @@ describe('configUtils', () => {
|
||||
const result = await readAISettings(mockFS);
|
||||
|
||||
expect(result).toEqual({
|
||||
providers: {},
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
+40
-4
@@ -1,5 +1,5 @@
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||
import type { AISettings, AIProvider } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||
|
||||
const CONFIG_DIR = '/config';
|
||||
@@ -27,8 +27,22 @@ async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise<AISet
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
const settings: AISettings = {
|
||||
providers: parsed.providers || {},
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
|
||||
@@ -51,7 +65,7 @@ async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise<AISet
|
||||
*/
|
||||
export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
|
||||
const defaultSettings: AISettings = {
|
||||
providers: {},
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
};
|
||||
|
||||
@@ -61,8 +75,30 @@ export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
|
||||
const parsed = JSON.parse(content);
|
||||
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
|
||||
// Write back the migrated format
|
||||
const migratedSettings: AISettings = {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
await writeAISettings(fs, migratedSettings);
|
||||
return migratedSettings;
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
return {
|
||||
providers: parsed.providers || {},
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,8 +17,6 @@ export class Git {
|
||||
this.corsProxy = corsProxy;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Repository initialization and configuration
|
||||
async init(options: Omit<Parameters<typeof git.init>[0], 'fs'>) {
|
||||
return git.init({
|
||||
|
||||
@@ -1,33 +1,41 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseProviderModel } from './parseProviderModel';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
describe('parseProviderModel', () => {
|
||||
const mockProviders: Record<string, AIConnection> = {
|
||||
openai: {
|
||||
const mockProviders: AIProvider[] = [
|
||||
{
|
||||
id: 'openai',
|
||||
baseURL: 'https://api.openai.com/v1',
|
||||
apiKey: 'sk-test-key',
|
||||
},
|
||||
openrouter: {
|
||||
{
|
||||
id: 'openrouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'sk-or-test-key',
|
||||
},
|
||||
anthropic: {
|
||||
{
|
||||
id: 'anthropic',
|
||||
baseURL: 'https://api.anthropic.com',
|
||||
apiKey: 'sk-ant-test-key',
|
||||
},
|
||||
unconfigured: {
|
||||
{
|
||||
id: 'unconfigured',
|
||||
baseURL: 'https://example.com/v1',
|
||||
apiKey: '',
|
||||
},
|
||||
};
|
||||
];
|
||||
|
||||
it('should parse simple provider/model format', () => {
|
||||
const result = parseProviderModel('openai/gpt-4o', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openai');
|
||||
expect(result.model).toBe('gpt-4o');
|
||||
expect(result.connection).toEqual(mockProviders.openai);
|
||||
expect(result.connection).toEqual({
|
||||
baseURL: mockProviders[0].baseURL,
|
||||
apiKey: mockProviders[0].apiKey,
|
||||
nostr: mockProviders[0].nostr,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse complex model names with slashes', () => {
|
||||
@@ -35,7 +43,11 @@ describe('parseProviderModel', () => {
|
||||
|
||||
expect(result.provider).toBe('openrouter');
|
||||
expect(result.model).toBe('anthropic/claude-sonnet-4');
|
||||
expect(result.connection).toEqual(mockProviders.openrouter);
|
||||
expect(result.connection).toEqual({
|
||||
baseURL: mockProviders[1].baseURL,
|
||||
apiKey: mockProviders[1].apiKey,
|
||||
nostr: mockProviders[1].nostr,
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle model names with multiple slashes', () => {
|
||||
@@ -43,7 +55,11 @@ describe('parseProviderModel', () => {
|
||||
|
||||
expect(result.provider).toBe('openrouter');
|
||||
expect(result.model).toBe('meta/llama-3.1-405b-instruct');
|
||||
expect(result.connection).toEqual(mockProviders.openrouter);
|
||||
expect(result.connection).toEqual({
|
||||
baseURL: mockProviders[1].baseURL,
|
||||
apiKey: mockProviders[1].apiKey,
|
||||
nostr: mockProviders[1].nostr,
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw error for invalid format without slash', () => {
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
export interface ParsedProviderModel {
|
||||
provider: string;
|
||||
model: string;
|
||||
connection: AIConnection;
|
||||
connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -13,29 +17,33 @@ export interface ParsedProviderModel {
|
||||
*/
|
||||
export function parseProviderModel(
|
||||
providerModelString: string,
|
||||
providers: Record<string, AIConnection>
|
||||
providers: AIProvider[]
|
||||
): ParsedProviderModel {
|
||||
const firstSlashIndex = providerModelString.indexOf('/');
|
||||
|
||||
|
||||
if (firstSlashIndex === -1) {
|
||||
throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")');
|
||||
}
|
||||
|
||||
|
||||
const provider = providerModelString.substring(0, firstSlashIndex);
|
||||
const model = providerModelString.substring(firstSlashIndex + 1);
|
||||
|
||||
|
||||
if (!provider || !model) {
|
||||
throw new Error('Invalid format. Both provider and model must be specified');
|
||||
}
|
||||
|
||||
const connection = providers[provider];
|
||||
if (!connection) {
|
||||
throw new Error(`Provider "${provider}" not found. Available providers: ${Object.keys(providers).join(', ')}`);
|
||||
|
||||
const providerObj = providers.find(p => p.id === provider);
|
||||
if (!providerObj) {
|
||||
throw new Error(`Provider "${provider}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`);
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
connection,
|
||||
connection: {
|
||||
baseURL: providerObj.baseURL,
|
||||
apiKey: providerObj.apiKey,
|
||||
nostr: providerObj.nostr,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -11,10 +11,13 @@ vi.mock('@/hooks/useCurrentUser', () => ({
|
||||
|
||||
vi.mock('@/hooks/useAISettings', () => ({
|
||||
useAISettings: vi.fn(() => ({
|
||||
settings: { providers: {} },
|
||||
addProvider: vi.fn(),
|
||||
settings: { providers: [] },
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
isConfigured: false,
|
||||
})),
|
||||
}));
|
||||
|
||||
|
||||
+215
-106
@@ -1,6 +1,25 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check, Bot, ArrowLeft, Trash2 } from 'lucide-react';
|
||||
import { Check, Bot, ArrowLeft, Trash2, GripVertical } from 'lucide-react';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import {
|
||||
useSortable,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
@@ -13,7 +32,7 @@ import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface PresetProvider {
|
||||
id: string;
|
||||
@@ -80,9 +99,125 @@ const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
},
|
||||
];
|
||||
|
||||
interface SortableProviderItemProps {
|
||||
provider: AIProvider;
|
||||
preset?: PresetProvider;
|
||||
onRemove: (id: string) => void;
|
||||
onSetProvider: (provider: AIProvider) => void;
|
||||
onOpenCreditsDialog: (providerId: string) => void;
|
||||
showDragHandle: boolean;
|
||||
}
|
||||
|
||||
function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpenCreditsDialog, showDragHandle }: SortableProviderItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id: provider.id });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
return (
|
||||
<AccordionItem
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
value={provider.id}
|
||||
className="border rounded-lg"
|
||||
>
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center justify-between w-full mr-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{showDragHandle && (
|
||||
<div
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
className="cursor-grab active:cursor-grabbing p-1 -ml-1 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<GripVertical className="h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
<span className="font-medium">
|
||||
{preset?.name || provider.id}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditsBadge
|
||||
providerId={provider.id}
|
||||
connection={{ baseURL: provider.baseURL, apiKey: provider.apiKey, nostr: provider.nostr }}
|
||||
onOpenDialog={() => onOpenCreditsDialog(provider.id)}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRemove(provider.id);
|
||||
}}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${provider.id}-baseURL`}>{t('baseUrl')}</Label>
|
||||
<Input
|
||||
id={`${provider.id}-baseURL`}
|
||||
placeholder="https://api.example.com/v1"
|
||||
value={provider.baseURL || ''}
|
||||
onChange={(e) => onSetProvider({ ...provider, baseURL: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${provider.id}-auth`}>{t('authentication')}</Label>
|
||||
<Select
|
||||
value={provider.nostr ? 'nostr' : 'api-key'}
|
||||
onValueChange={(value: 'api-key' | 'nostr') => onSetProvider({
|
||||
...provider,
|
||||
nostr: value === 'nostr' || undefined,
|
||||
apiKey: value === 'nostr' ? undefined : provider.apiKey
|
||||
})}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
|
||||
<SelectItem value="nostr">Nostr</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{!provider.nostr && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${provider.id}-apiKey`}>{t('apiKey')}</Label>
|
||||
<PasswordInput
|
||||
id={`${provider.id}-apiKey`}
|
||||
placeholder={t('enterApiKey')}
|
||||
value={provider.apiKey || ''}
|
||||
onChange={(e) => onSetProvider({ ...provider, apiKey: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
);
|
||||
}
|
||||
|
||||
export function AISettings() {
|
||||
const { t } = useTranslation();
|
||||
const { settings, addProvider, removeProvider, updateProvider } = useAISettings();
|
||||
const { settings, setProvider, removeProvider, setProviders } = useAISettings();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const { user } = useCurrentUser();
|
||||
@@ -93,10 +228,18 @@ export function AISettings() {
|
||||
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
|
||||
const [activeCreditsDialog, setActiveCreditsDialog] = useState<string | null>(null);
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor),
|
||||
useSensor(KeyboardSensor, {
|
||||
coordinateGetter: sortableKeyboardCoordinates,
|
||||
})
|
||||
);
|
||||
|
||||
const handleAddPresetProvider = (preset: PresetProvider) => {
|
||||
const apiKey = presetApiKeys[preset.id] as string | undefined;
|
||||
|
||||
const newProvider: AIConnection = {
|
||||
const newProvider: AIProvider = {
|
||||
id: preset.id,
|
||||
baseURL: preset.baseURL,
|
||||
};
|
||||
|
||||
@@ -108,7 +251,7 @@ export function AISettings() {
|
||||
}
|
||||
|
||||
// Auto-save: Add provider immediately to persistent storage
|
||||
addProvider(preset.id, newProvider);
|
||||
setProvider(newProvider);
|
||||
|
||||
// Clear the API key input for this preset
|
||||
setPresetApiKeys(prev => ({
|
||||
@@ -120,14 +263,15 @@ export function AISettings() {
|
||||
const handleAddCustomProvider = () => {
|
||||
if (!customProviderName.trim() || !customBaseURL.trim()) return;
|
||||
|
||||
const newProvider: AIConnection = {
|
||||
const newProvider: AIProvider = {
|
||||
id: customProviderName.trim(),
|
||||
baseURL: customBaseURL.trim(),
|
||||
apiKey: customAuthMethod === 'nostr' ? undefined : customApiKey.trim(),
|
||||
nostr: customAuthMethod === 'nostr' || undefined,
|
||||
};
|
||||
|
||||
// Auto-save: Add provider immediately to persistent storage
|
||||
addProvider(customProviderName.trim(), newProvider);
|
||||
setProvider(newProvider);
|
||||
|
||||
setCustomProviderName('');
|
||||
setCustomBaseURL('');
|
||||
@@ -135,14 +279,14 @@ export function AISettings() {
|
||||
setCustomAuthMethod('api-key');
|
||||
};
|
||||
|
||||
const handleRemoveProvider = (name: string) => {
|
||||
const handleRemoveProvider = (id: string) => {
|
||||
// Auto-save: Remove provider immediately from persistent storage
|
||||
removeProvider(name);
|
||||
removeProvider(id);
|
||||
};
|
||||
|
||||
const handleUpdateProvider = (name: string, connection: Partial<AIConnection>) => {
|
||||
const handleSetProvider = (provider: AIProvider) => {
|
||||
// Auto-save: Update provider immediately in persistent storage
|
||||
updateProvider(name, connection);
|
||||
setProvider(provider);
|
||||
};
|
||||
|
||||
const handleOpenCreditsDialog = (providerId: string) => {
|
||||
@@ -153,7 +297,21 @@ export function AISettings() {
|
||||
setActiveCreditsDialog(null);
|
||||
};
|
||||
|
||||
const configuredProviderIds = Object.keys(settings.providers);
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
|
||||
if (active.id !== over?.id) {
|
||||
const oldIndex = settings.providers.findIndex(provider => provider.id === active.id);
|
||||
const newIndex = settings.providers.findIndex(provider => provider.id === over?.id);
|
||||
|
||||
if (oldIndex !== -1 && newIndex !== -1) {
|
||||
const newProviders = arrayMove(settings.providers, oldIndex, newIndex);
|
||||
setProviders(newProviders);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const configuredProviderIds = settings.providers.map(p => p.id);
|
||||
const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id));
|
||||
|
||||
return (
|
||||
@@ -195,89 +353,37 @@ export function AISettings() {
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* Configured Providers */}
|
||||
{configuredProviderIds.length > 0 && (
|
||||
{settings.providers.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium">{t('configuredProviders')}</h4>
|
||||
<Accordion type="multiple" className="w-full space-y-2">
|
||||
{configuredProviderIds.map((providerId) => {
|
||||
const preset = PRESET_PROVIDERS.find(p => p.id === providerId);
|
||||
const provider = settings.providers[providerId];
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext
|
||||
items={settings.providers.map(p => p.id)}
|
||||
strategy={verticalListSortingStrategy}
|
||||
>
|
||||
<Accordion type="multiple" className="w-full space-y-2">
|
||||
{settings.providers.map((provider) => {
|
||||
const preset = PRESET_PROVIDERS.find(p => p.id === provider.id);
|
||||
|
||||
return (
|
||||
<AccordionItem key={providerId} value={providerId} className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center justify-between w-full mr-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">
|
||||
{preset?.name || providerId}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditsBadge
|
||||
providerId={providerId}
|
||||
connection={provider}
|
||||
onOpenDialog={() => handleOpenCreditsDialog(providerId)}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleRemoveProvider(providerId);
|
||||
}}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${providerId}-baseURL`}>{t('baseUrl')}</Label>
|
||||
<Input
|
||||
id={`${providerId}-baseURL`}
|
||||
placeholder="https://api.example.com/v1"
|
||||
value={provider?.baseURL || ''}
|
||||
onChange={(e) => handleUpdateProvider(providerId, { baseURL: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${providerId}-auth`}>{t('authentication')}</Label>
|
||||
<Select
|
||||
value={provider?.nostr ? 'nostr' : 'api-key'}
|
||||
onValueChange={(value: 'api-key' | 'nostr') => handleUpdateProvider(providerId, {
|
||||
nostr: value === 'nostr' || undefined,
|
||||
apiKey: value === 'nostr' ? undefined : provider?.apiKey
|
||||
})}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
|
||||
<SelectItem value="nostr">Nostr</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{!provider?.nostr && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${providerId}-apiKey`}>{t('apiKey')}</Label>
|
||||
<PasswordInput
|
||||
id={`${providerId}-apiKey`}
|
||||
placeholder={t('enterApiKey')}
|
||||
value={provider?.apiKey || ''}
|
||||
onChange={(e) => handleUpdateProvider(providerId, { apiKey: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
);
|
||||
})}
|
||||
</Accordion>
|
||||
return (
|
||||
<SortableProviderItem
|
||||
key={provider.id}
|
||||
provider={provider}
|
||||
preset={preset}
|
||||
onRemove={handleRemoveProvider}
|
||||
onSetProvider={handleSetProvider}
|
||||
onOpenCreditsDialog={handleOpenCreditsDialog}
|
||||
showDragHandle={settings.providers.length > 1}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Accordion>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -417,14 +523,14 @@ export function AISettings() {
|
||||
disabled={
|
||||
!customProviderName.trim() ||
|
||||
!customBaseURL.trim() ||
|
||||
customProviderName.trim() in settings.providers
|
||||
settings.providers.some(p => p.id === customProviderName.trim())
|
||||
}
|
||||
className="gap-2 ml-auto"
|
||||
>
|
||||
<Check className="h-4 w-4" />
|
||||
{t('addCustomProviderButton')}
|
||||
</Button>
|
||||
{customProviderName.trim() in settings.providers && (
|
||||
{settings.providers.some(p => p.id === customProviderName.trim()) && (
|
||||
<p className="text-sm text-destructive">
|
||||
{t('providerExists')}
|
||||
</p>
|
||||
@@ -437,18 +543,21 @@ export function AISettings() {
|
||||
</div>
|
||||
|
||||
{/* Render credits dialog outside of accordion structure */}
|
||||
{activeCreditsDialog && (
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
handleCloseCreditsDialog();
|
||||
}
|
||||
}}
|
||||
providerId={activeCreditsDialog}
|
||||
connection={settings.providers[activeCreditsDialog]}
|
||||
/>
|
||||
)}
|
||||
{activeCreditsDialog && (() => {
|
||||
const provider = settings.providers.find(p => p.id === activeCreditsDialog);
|
||||
return provider && (
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
handleCloseCreditsDialog();
|
||||
}
|
||||
}}
|
||||
providerId={activeCreditsDialog}
|
||||
connection={{ baseURL: provider.baseURL, apiKey: provider.apiKey, nostr: provider.nostr }}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ export default function Index() {
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
|
||||
// Check if any providers are configured
|
||||
const hasProvidersConfigured = Object.keys(settings.providers).length > 0;
|
||||
const hasProvidersConfigured = settings.providers.length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||
|
||||
Reference in new issue
Block a user