Make Nostr Auth work

This commit is contained in:
Alex Gleason committed 2025-09-11 17:53:36 -05:00
1 parent d7807f3911
commit bd0ed0a10f
13 files changed
+152 -113

No files matched your search

+5 -26
View File
@@ -1,6 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { AISettingsProvider } from './AISettingsProvider';
import { useAISettings } from '@/hooks/useAISettings';
import { TestApp } from '@/test/TestApp';
@@ -24,11 +23,7 @@ describe('AISettingsProvider', () => {
it('should initialize with empty recentlyUsedModels array', () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
expect(result.current.settings.recentlyUsedModels).toEqual([]);
@@ -36,11 +31,7 @@ describe('AISettingsProvider', () => {
it('should add recently used models correctly', () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
act(() => {
@@ -54,11 +45,7 @@ describe('AISettingsProvider', () => {
it('should move existing model to front when used again', () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
// Add multiple models
@@ -88,11 +75,7 @@ describe('AISettingsProvider', () => {
it('should limit recently used models to 10 items', () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
// Add 12 models
@@ -121,11 +104,7 @@ describe('AISettingsProvider', () => {
localStorageMock.getItem.mockReturnValue(JSON.stringify(oldSettings));
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<AISettingsProvider>{children}</AISettingsProvider>
</TestApp>
),
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
expect(result.current.settings.recentlyUsedModels).toEqual([]);
+7 -27
View File
@@ -12,39 +12,19 @@ const DEFAULT_SETTINGS: AISettings = {
const STORAGE_KEY = 'ai-settings';
function migrateOldSettings(stored: unknown): AISettings {
// Handle migration from old single-provider format
if (stored && typeof stored === 'object' && 'apiKey' in stored && 'baseUrl' in stored) {
const oldSettings = stored as { apiKey?: string; baseUrl?: string };
return {
providers: {
openrouter: {
baseURL: oldSettings.baseUrl || 'https://openrouter.ai/api/v1',
apiKey: oldSettings.apiKey || '',
},
},
recentlyUsedModels: [],
};
}
// If it's already the new format or invalid, return as AISettings or default
if (stored && typeof stored === 'object' && 'providers' in stored) {
const settings = stored as Partial<AISettings>;
return {
providers: settings.providers || {},
recentlyUsedModels: settings.recentlyUsedModels || [],
};
}
return DEFAULT_SETTINGS;
}
export function AISettingsProvider({ children }: AISettingsProviderProps) {
const [settings, setSettings] = useState<AISettings>(() => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
const parsed = JSON.parse(stored);
const migrated = migrateOldSettings(parsed);
return { ...DEFAULT_SETTINGS, ...migrated };
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;
}
+5 -2
View File
@@ -4,6 +4,7 @@ import { SessionManager } from '@/lib/SessionManager';
import { useFS } from '@/hooks/useFS';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useCurrentUser } from '@/hooks/useCurrentUser';
interface SessionManagerProviderProps {
children: ReactNode;
@@ -16,11 +17,13 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps
const { fs } = useFS();
const { settings } = useAISettings();
const { models } = useProviderModels();
const { user } = useCurrentUser();
const sessionManager = useMemo(() => {
const getProviderModels = () => models;
return new SessionManager(fs, settings, getProviderModels);
}, [fs, settings, models]);
const getCurrentUser = () => user;
return new SessionManager(fs, settings, getProviderModels, getCurrentUser);
}, [fs, settings, models, user]);
// Cleanup on unmount
useEffect(() => {
+64 -17
View File
@@ -8,6 +8,7 @@ import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useAISettings } from '@/hooks/useAISettings';
import type { AIConnection } from '@/contexts/AISettingsContext';
@@ -78,12 +79,14 @@ export function AISettingsDialog({ open: controlledOpen, onOpenChange }: AISetti
const [customProviderName, setCustomProviderName] = useState('');
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
const handleCancel = () => {
setCustomProviderName('');
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
setPresetApiKeys({});
setOpen(false);
};
@@ -112,7 +115,8 @@ export function AISettingsDialog({ open: controlledOpen, onOpenChange }: AISetti
const newProvider: AIConnection = {
baseURL: customBaseURL.trim(),
apiKey: customApiKey.trim(),
apiKey: customAuthMethod === 'nostr' ? undefined : customApiKey.trim(),
nostr: customAuthMethod === 'nostr' || undefined,
};
// Auto-save: Add provider immediately to persistent storage
@@ -121,6 +125,7 @@ export function AISettingsDialog({ open: controlledOpen, onOpenChange }: AISetti
setCustomProviderName('');
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
};
const handleRemoveProvider = (name: string) => {
@@ -204,15 +209,35 @@ export function AISettingsDialog({ open: controlledOpen, onOpenChange }: AISetti
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`${providerId}-apiKey`}>API Key</Label>
<Input
id={`${providerId}-apiKey`}
type="password"
placeholder="Enter your API key"
value={provider?.apiKey || ''}
onChange={(e) => handleUpdateProvider(providerId, { apiKey: e.target.value })}
/>
<Label htmlFor={`${providerId}-auth`}>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">API Key</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
</SelectContent>
</Select>
</div>
{!provider?.nostr && (
<div className="grid gap-2">
<Label htmlFor={`${providerId}-apiKey`}>API Key</Label>
<Input
id={`${providerId}-apiKey`}
type="password"
placeholder="Enter your API key"
value={provider?.apiKey || ''}
onChange={(e) => handleUpdateProvider(providerId, { apiKey: e.target.value })}
/>
</div>
)}
</div>
</AccordionContent>
</AccordionItem>
@@ -299,15 +324,37 @@ export function AISettingsDialog({ open: controlledOpen, onOpenChange }: AISetti
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-apikey">API Key</Label>
<Input
id="custom-apikey"
type="password"
placeholder="Enter your API key (optional)"
value={customApiKey}
onChange={(e) => setCustomApiKey(e.target.value)}
/>
<Label htmlFor="custom-auth">Authentication</Label>
<Select
value={customAuthMethod}
onValueChange={(value: 'api-key' | 'nostr') => {
setCustomAuthMethod(value);
if (value === 'nostr') {
setCustomApiKey(''); // Clear API key when switching to Nostr auth
}
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="api-key">API Key</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
</SelectContent>
</Select>
</div>
{customAuthMethod === 'api-key' && (
<div className="grid gap-2">
<Label htmlFor="custom-apikey">API Key</Label>
<Input
id="custom-apikey"
type="password"
placeholder="Enter your API key (optional)"
value={customApiKey}
onChange={(e) => setCustomApiKey(e.target.value)}
/>
</div>
)}
<Button
onClick={handleAddCustomProvider}
disabled={
+1
View File
@@ -3,6 +3,7 @@ import { createContext } from 'react';
export interface AIConnection {
baseURL: string;
apiKey?: string;
nostr?: boolean;
}
export interface AISettings {
+10 -1
View File
@@ -2,18 +2,27 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook } from '@testing-library/react';
import { useAIProjectId } from './useAIProjectId';
import { useAISettings } from './useAISettings';
import { useCurrentUser } from './useCurrentUser';
// Mock the useAISettings hook
// Mock the hooks
vi.mock('./useAISettings');
vi.mock('./useCurrentUser');
describe('useAIProjectId', () => {
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseCurrentUser = vi.mocked(useCurrentUser);
beforeEach(() => {
vi.clearAllMocks();
// Mock fetch globally
global.fetch = vi.fn();
// Mock useCurrentUser to return undefined user by default
mockUseCurrentUser.mockReturnValue({
user: undefined,
users: [],
});
});
it('should return not configured when AI settings are not configured', () => {
+5 -7
View File
@@ -1,6 +1,7 @@
import { useState, useCallback } from 'react';
import OpenAI from 'openai';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { createAIClient } from '@/lib/ai-client';
interface UseAIProjectIdOptions {
onError?: (error: string) => void;
@@ -9,6 +10,7 @@ interface UseAIProjectIdOptions {
export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
const [isLoading, setIsLoading] = useState(false);
const { settings, isConfigured } = useAISettings();
const { user } = useCurrentUser();
const generateProjectId = useCallback(async (prompt: string): Promise<string> => {
if (!isConfigured) {
@@ -33,11 +35,7 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
const modelName = 'gpt-3.5-turbo'; // Use a fast, cheap model for ID generation
// Initialize OpenAI client
const openai = new OpenAI({
baseURL: connectionConfig.baseURL,
apiKey: connectionConfig.apiKey,
dangerouslyAllowBrowser: true
});
const openai = createAIClient(connectionConfig, user);
const systemPrompt = `You are a project ID generator. Given a user's description of what they want to build, generate a short, descriptive, kebab-case project ID that captures the essence of their project.
@@ -84,7 +82,7 @@ Respond with ONLY the project ID, no explanation or additional text.`;
} finally {
setIsLoading(false);
}
}, [isConfigured, settings, onError]);
}, [isConfigured, settings, onError, user]);
return {
generateProjectId,
+5
View File
@@ -25,6 +25,11 @@ export function useCurrentUser() {
const users = useMemo(() => {
const users: NUser[] = [];
// Safeguard against undefined or null logins
if (!logins || !Array.isArray(logins)) {
return users;
}
for (const login of logins) {
try {
const user = loginToUser(login);
+6 -13
View File
@@ -1,8 +1,9 @@
import { Decimal } from 'decimal.js';
import { useState, useCallback } from 'react';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import OpenAI from 'openai';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { createAIClient } from '@/lib/ai-client';
interface ProviderModel {
id: string;
@@ -29,12 +30,13 @@ interface ModelFetchResult {
export function useProviderModels(): ModelFetchResult {
const { settings } = useAISettings();
const { user } = useCurrentUser();
const [error, setError] = useState<string | null>(null);
const {
data: models = [],
isLoading,
refetch: queryRefetch,
refetch,
} = useQuery({
queryKey: ['provider-models', settings.providers],
queryFn: async () => {
@@ -44,11 +46,7 @@ export function useProviderModels(): ModelFetchResult {
// Fetch models from each configured provider
for (const [providerKey, connection] of Object.entries(settings.providers)) {
try {
const openai = new OpenAI({
baseURL: connection.baseURL,
apiKey: connection.apiKey,
dangerouslyAllowBrowser: true,
});
const openai = createAIClient(connection, user);
// Fetch models with timeout
try {
@@ -126,11 +124,6 @@ export function useProviderModels(): ModelFetchResult {
retry: false, // Don't retry on failure
});
const refetch = useCallback(() => {
setError(null);
queryRefetch();
}, [queryRefetch]);
return {
models,
isLoading,
+10 -8
View File
@@ -2,7 +2,9 @@ import OpenAI from 'openai';
import type { JSRuntimeFS } from './JSRuntime';
import { DotAI } from './DotAI';
import { parseProviderModel } from './parseProviderModel';
import { createAIClient } from './ai-client';
import type { Tool } from './tools/Tool';
import type { NUser } from '@nostrify/react/login';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
@@ -44,17 +46,20 @@ 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 }> };
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> };
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 }> },
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>
aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> },
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getCurrentUser?: () => NUser | undefined
) {
this.fs = fs;
this.aiSettings = aiSettings;
this.getProviderModels = getProviderModels;
this.getCurrentUser = getCurrentUser;
}
/**
@@ -195,11 +200,8 @@ export class SessionManager {
const modelName = parsed.model;
// Initialize OpenAI client
const openai = new OpenAI({
baseURL: connectionConfig.baseURL,
apiKey: connectionConfig.apiKey,
dangerouslyAllowBrowser: true
});
const currentUser = this.getCurrentUser?.();
const openai = createAIClient(connectionConfig, currentUser);
let stepCount = 0;
const maxSteps = session.maxSteps || 50;
+30
View File
@@ -0,0 +1,30 @@
import OpenAI from 'openai';
import { NIP98Client } from './NIP98Client';
import type { AIConnection } from '@/contexts/AISettingsContext';
import type { NUser } from '@nostrify/react/login';
/**
* Create an OpenAI client instance with the appropriate configuration.
* If the connection requires Nostr authentication (NIP-98), it will use
* the NIP98Client for authenticated requests.
*/
export function createAIClient(connection: AIConnection, user?: NUser): OpenAI {
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
baseURL: connection.baseURL,
apiKey: connection.apiKey ?? '',
dangerouslyAllowBrowser: true,
};
// If Nostr authentication is required and we have a user, use NIP-98
if (connection.nostr && user?.signer) {
const nip98Client = new NIP98Client(user.signer);
return new OpenAI({
...baseConfig,
fetch: (input, init) => nip98Client.fetch(input, init),
});
}
// Standard OpenAI client
return new OpenAI(baseConfig);
}
+4 -8
View File
@@ -24,7 +24,7 @@ describe('parseProviderModel', () => {
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);
@@ -32,7 +32,7 @@ describe('parseProviderModel', () => {
it('should parse complex model names with slashes', () => {
const result = parseProviderModel('openrouter/anthropic/claude-sonnet-4', mockProviders);
expect(result.provider).toBe('openrouter');
expect(result.model).toBe('anthropic/claude-sonnet-4');
expect(result.connection).toEqual(mockProviders.openrouter);
@@ -40,7 +40,7 @@ describe('parseProviderModel', () => {
it('should handle model names with multiple slashes', () => {
const result = parseProviderModel('openrouter/meta/llama-3.1-405b-instruct', mockProviders);
expect(result.provider).toBe('openrouter');
expect(result.model).toBe('meta/llama-3.1-405b-instruct');
expect(result.connection).toEqual(mockProviders.openrouter);
@@ -70,9 +70,5 @@ describe('parseProviderModel', () => {
}).toThrow('Provider "unknown" not found. Available providers: openai, openrouter, anthropic, unconfigured');
});
it('should throw error for provider without API key', () => {
expect(() => {
parseProviderModel('unconfigured/some-model', mockProviders);
}).toThrow('Provider "unconfigured" is not configured with an API key');
});
});
-4
View File
@@ -33,10 +33,6 @@ export function parseProviderModel(
throw new Error(`Provider "${provider}" not found. Available providers: ${Object.keys(providers).join(', ')}`);
}
if (!connection.apiKey) {
throw new Error(`Provider "${provider}" is not configured with an API key`);
}
return {
provider,
model,