From caa4dce6f0234c1cc1c96689641f155488932e36 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 16 Jul 2025 16:02:41 -0500 Subject: [PATCH] Add AI settings --- package-lock.json | 10 +- package.json | 2 +- src/App.tsx | 17 +- src/AppRouter.tsx | 2 +- src/components/Shakespeare/ChatPane.tsx | 234 +++++++++++++++++++++++- src/components/ai/AISettingsDialog.tsx | 88 +++++++++ src/contexts/AISettingsContext.tsx | 63 +++++++ src/hooks/useChat.ts | 81 ++++++++ src/lib/debug-fs.ts | 28 +++ src/lib/fs.ts | 2 +- src/pages/ProjectView.tsx | 38 ++-- src/pages/ShakespeareHome.tsx | 2 +- 12 files changed, 527 insertions(+), 40 deletions(-) create mode 100644 src/components/ai/AISettingsDialog.tsx create mode 100644 src/contexts/AISettingsContext.tsx create mode 100644 src/hooks/useChat.ts create mode 100644 src/lib/debug-fs.ts diff --git a/package-lock.json b/package-lock.json index 367bf0dc..16fccb77 100644 --- a/package-lock.json +++ b/package-lock.json @@ -52,7 +52,7 @@ "embla-carousel-react": "^8.3.0", "input-otp": "^1.2.4", "isomorphic-git": "^1.32.1", - "lucide-react": "^0.462.0", + "lucide-react": "^0.525.0", "next-themes": "^0.3.0", "nostr-tools": "^2.13.0", "react": "^18.3.1", @@ -6442,12 +6442,12 @@ "license": "ISC" }, "node_modules/lucide-react": { - "version": "0.462.0", - "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.462.0.tgz", - "integrity": "sha512-NTL7EbAao9IFtuSivSZgrAh4fZd09Lr+6MTkqIxuHaH2nnYiYIzXPo06cOxHg9wKLdj6LL8TByG4qpePqwgx/g==", + "version": "0.525.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.525.0.tgz", + "integrity": "sha512-Tm1txJ2OkymCGkvwoHt33Y2JpN5xucVq1slHcgE6Lk0WjDfjgKWor5CdVER8U6DvcfMwh4M8XxmpTiyzfmfDYQ==", "license": "ISC", "peerDependencies": { - "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc" + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "node_modules/lz-string": { diff --git a/package.json b/package.json index 637e0060..65fb421c 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,7 @@ "embla-carousel-react": "^8.3.0", "input-otp": "^1.2.4", "isomorphic-git": "^1.32.1", - "lucide-react": "^0.462.0", + "lucide-react": "^0.525.0", "next-themes": "^0.3.0", "nostr-tools": "^2.13.0", "react": "^18.3.1", diff --git a/src/App.tsx b/src/App.tsx index 7cab8334..08ed0d69 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -12,6 +12,7 @@ import { TooltipProvider } from "@/components/ui/tooltip"; import { NostrLoginProvider } from '@nostrify/react/login'; import { AppProvider } from '@/components/AppProvider'; import { AppConfig } from '@/contexts/AppContext'; +import { AISettingsProvider } from '@/contexts/AISettingsContext'; import AppRouter from './AppRouter'; const head = createHead({ @@ -49,13 +50,15 @@ export function App() { - - - - - - - + + + + + + + + + diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index 28373111..e10097af 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -23,4 +23,4 @@ export function AppRouter() { ); } -export default AppRouter; \ No newline at end of file +export default AppRouter; diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 5ea84d20..611c716b 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -1,11 +1,14 @@ import { useState, useRef, useEffect } from 'react'; -import { createAIChat } from '@/lib/ai-chat'; +import { streamText, tool } from 'ai'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Card } from '@/components/ui/card'; -import { Send, Bot, User } from 'lucide-react'; +import { Send, Bot, User, Settings } from 'lucide-react'; import { cn } from '@/lib/utils'; +import { useAISettings } from '@/contexts/AISettingsContext'; +import { aiTools } from '@/lib/ai-tools'; +import { z } from 'zod'; interface Message { id: string; @@ -25,6 +28,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); const scrollAreaRef = useRef(null); + const { settings, isConfigured } = useAISettings(); useEffect(() => { // Add welcome message @@ -44,6 +48,158 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { } }, [messages]); + const createAIChat = async (projectId: string, messages: any[]) => { + if (!isConfigured) { + throw new Error('AI settings not configured'); + } + + const fileOperationSchema = z.object({ + projectId: z.string(), + filePath: z.string(), + content: z.string().optional(), + }); + + const buildSchema = z.object({ + projectId: z.string(), + }); + + // Create a custom fetch function for the AI provider + const customFetch = async (url: string, options: RequestInit) => { + return fetch(url, { + ...options, + headers: { + ...options.headers, + 'Authorization': `Bearer ${settings.apiKey}`, + }, + }); + }; + + // Import the appropriate provider based on the base URL + const { createOpenAI } = await import('@ai-sdk/openai'); + const openai = createOpenAI({ + baseURL: settings.baseUrl, + apiKey: settings.apiKey, + fetch: settings.baseUrl.includes('openrouter.ai') ? customFetch : undefined, + }); + const provider = openai(settings.model); + + return streamText({ + model: provider, + messages, + tools: { + readFile: tool({ + description: 'Read the contents of a file in the project', + parameters: fileOperationSchema, + execute: async ({ projectId, filePath }) => { + return await aiTools.executeOperation({ + type: 'read', + projectId, + filePath, + }); + }, + }), + writeFile: tool({ + description: 'Write content to a file in the project', + parameters: fileOperationSchema, + execute: async ({ projectId, filePath, content }) => { + return await aiTools.executeOperation({ + type: 'write', + projectId, + filePath, + content: content || '', + }); + }, + }), + deleteFile: tool({ + description: 'Delete a file from the project', + parameters: fileOperationSchema, + execute: async ({ projectId, filePath }) => { + return await aiTools.executeOperation({ + type: 'delete', + projectId, + filePath, + }); + }, + }), + listFiles: tool({ + description: 'List files in a directory', + parameters: fileOperationSchema, + execute: async ({ projectId, filePath }) => { + return await aiTools.executeOperation({ + type: 'list', + projectId, + filePath, + }); + }, + }), + fileExists: tool({ + description: 'Check if a file exists', + parameters: fileOperationSchema, + execute: async ({ projectId, filePath }) => { + return await aiTools.executeOperation({ + type: 'exists', + projectId, + filePath, + }); + }, + }), + buildProject: tool({ + description: 'Build the project using Vite', + parameters: buildSchema, + execute: async ({ projectId }) => { + return await aiTools.executeOperation({ + type: 'build', + projectId, + }); + }, + }), + getProjectStructure: tool({ + description: 'Get the complete file structure of the project', + parameters: buildSchema, + execute: async ({ projectId }) => { + return await aiTools.getProjectStructure(projectId); + }, + }), + searchFiles: tool({ + description: 'Search for files containing specific text', + parameters: z.object({ + projectId: z.string(), + query: z.string(), + }), + execute: async ({ projectId, query }) => { + return await aiTools.searchFiles(projectId, query); + }, + }), + }, + system: `You are an AI assistant helping users build custom Nostr websites. You have access to tools that allow you to read, write, and manage files in the project, as well as build the project. + +Key capabilities: +- Read and write files in the project +- List directory contents +- Check if files exist +- Build the project using Vite +- Get project structure overview +- Search through files + +Guidelines: +- Always check if files exist before writing to avoid overwriting +- Provide helpful explanations of what you're doing +- Suggest improvements and best practices +- Use modern React patterns and TypeScript +- Follow Nostr protocol standards when relevant +- Ensure the project builds successfully + +The project uses: +- React 18 with TypeScript +- Vite for building +- TailwindCSS for styling +- Nostrify for Nostr integration +- shadcn/ui components + +When creating new components or pages, follow the existing patterns in the codebase.` + }); + }; + const handleSend = async () => { if (!input.trim() || isLoading) return; @@ -96,7 +252,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { const errorMessage: Message = { id: (Date.now() + 1).toString(), role: 'assistant', - content: 'Sorry, I encountered an error. Please try again.', + content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.', timestamp: new Date(), }; setMessages((prev) => [...prev, errorMessage]); @@ -112,11 +268,75 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { } }; + if (!isConfigured) { + return ( +
+
+
+

AI Assistant

+

Chat to build your project

+
+ +
+ +
+
+ +
+

AI Assistant Not Configured

+

+ Please configure your AI settings to start building with AI assistance. +

+ +
+
+
+
+ ); + } + return (
-
-

AI Assistant

-

Chat to build your project

+
+
+

AI Assistant

+

Chat to build your project

+
+
@@ -209,4 +429,4 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
); -} \ No newline at end of file +} diff --git a/src/components/ai/AISettingsDialog.tsx b/src/components/ai/AISettingsDialog.tsx new file mode 100644 index 00000000..2c363f0c --- /dev/null +++ b/src/components/ai/AISettingsDialog.tsx @@ -0,0 +1,88 @@ +import { useState } from 'react'; +import { Settings } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useAISettings } from '@/contexts/AISettingsContext'; + +export function AISettingsDialog() { + const { settings, updateSettings, isConfigured } = useAISettings(); + const [open, setOpen] = useState(false); + const [localSettings, setLocalSettings] = useState(settings); + + const handleSave = () => { + updateSettings(localSettings); + setOpen(false); + }; + + const handleCancel = () => { + setLocalSettings(settings); + setOpen(false); + }; + + return ( + + + + + + + AI Settings + + Configure your AI provider settings. These settings are stored locally in your browser. + + +
+
+ + setLocalSettings({ ...localSettings, apiKey: e.target.value })} + /> + {!localSettings.apiKey && ( +

+ Required for AI functionality +

+ )} +
+
+ + setLocalSettings({ ...localSettings, baseUrl: e.target.value })} + /> +
+
+ + setLocalSettings({ ...localSettings, model: e.target.value })} + /> +
+
+
+ + +
+
+
+ ); +} diff --git a/src/contexts/AISettingsContext.tsx b/src/contexts/AISettingsContext.tsx new file mode 100644 index 00000000..c8c3a8de --- /dev/null +++ b/src/contexts/AISettingsContext.tsx @@ -0,0 +1,63 @@ +import { createContext, useContext, useState, useEffect, ReactNode } from 'react'; + +export interface AISettings { + apiKey: string; + baseUrl: string; + model: string; +} + +interface AISettingsContextType { + settings: AISettings; + updateSettings: (settings: Partial) => void; + isConfigured: boolean; +} + +const AISettingsContext = createContext(undefined); + +const DEFAULT_SETTINGS: AISettings = { + apiKey: '', + baseUrl: 'https://openrouter.ai/api/v1', + model: 'anthropic/claude-sonnet-4', +}; + +const STORAGE_KEY = 'ai-settings'; + +export function AISettingsProvider({ children }: { children: ReactNode }) { + const [settings, setSettings] = useState(() => { + const stored = localStorage.getItem(STORAGE_KEY); + if (stored) { + try { + return { ...DEFAULT_SETTINGS, ...JSON.parse(stored) }; + } catch { + return DEFAULT_SETTINGS; + } + } + return DEFAULT_SETTINGS; + }); + + useEffect(() => { + localStorage.setItem(STORAGE_KEY, JSON.stringify(settings)); + }, [settings]); + + const updateSettings = (newSettings: Partial) => { + setSettings(prev => ({ ...prev, ...newSettings })); + }; + + const isConfigured = Boolean(settings.apiKey); + + return ( + + {children} + + ); +} + + +// eslint-disable-next-line react-refresh/only-export-components +export function useAISettings() { + const context = useContext(AISettingsContext); + if (!context) { + throw new Error('useAISettings must be used within AISettingsProvider'); + } + return context; +} diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts new file mode 100644 index 00000000..f45be401 --- /dev/null +++ b/src/hooks/useChat.ts @@ -0,0 +1,81 @@ +import { useState, useCallback } from 'react'; +import { useAISettings } from '@/contexts/AISettingsContext'; + +export interface Message { + id: string; + role: 'user' | 'assistant'; + content: string; + timestamp: Date; +} + +export function useChat() { + const { settings } = useAISettings(); + const [messages, setMessages] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const sendMessage = useCallback(async (content: string) => { + if (!settings.apiKey) { + setError('API key not configured'); + return; + } + + setIsLoading(true); + setError(null); + + const userMessage: Message = { + id: Date.now().toString(), + role: 'user', + content, + timestamp: new Date(), + }; + + setMessages(prev => [...prev, userMessage]); + + try { + const response = await fetch(`${settings.baseUrl}/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${settings.apiKey}`, + }, + body: JSON.stringify({ + model: settings.model, + messages: [ + ...messages.map(m => ({ role: m.role, content: m.content })), + { role: 'user', content } + ], + stream: false, + max_tokens: 1000, + }), + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data = await response.json(); + const assistantMessage: Message = { + id: (Date.now() + 1).toString(), + role: 'assistant', + content: data.choices[0]?.message?.content || 'No response received', + timestamp: new Date(), + }; + + setMessages(prev => [...prev, assistantMessage]); + } catch (err) { + setError(err instanceof Error ? err.message : 'An error occurred'); + // Remove the user message if there was an error + setMessages(prev => prev.slice(0, -1)); + } finally { + setIsLoading(false); + } + }, [settings, messages]); + + return { + messages, + isLoading, + error, + sendMessage, + }; +} diff --git a/src/lib/debug-fs.ts b/src/lib/debug-fs.ts new file mode 100644 index 00000000..20a1a523 --- /dev/null +++ b/src/lib/debug-fs.ts @@ -0,0 +1,28 @@ +import { fsManager } from './fs'; + +export async function debugProjectFiles(projectId: string) { + console.log('=== Debugging project files ==='); + console.log('Project ID:', projectId); + + try { + const rootFiles = await fsManager.listFiles(projectId, ''); + console.log('Root files:', rootFiles); + + for (const file of rootFiles) { + const filePath = `${fsManager['dir']}/${projectId}/${file}`; + try { + const stat = await fsManager['fs'].promises.stat(filePath); + console.log(`${file}: ${stat.isDirectory() ? 'directory' : 'file'}`); + + if (stat.isDirectory() && file !== '.git') { + const subFiles = await fsManager.listFiles(projectId, file); + console.log(` ${file}/ contents:`, subFiles); + } + } catch (error) { + console.error(`Error accessing ${file}:`, error); + } + } + } catch (error) { + console.error('Error listing files:', error); + } +} \ No newline at end of file diff --git a/src/lib/fs.ts b/src/lib/fs.ts index dc2e5e8e..94d02830 100644 --- a/src/lib/fs.ts +++ b/src/lib/fs.ts @@ -204,7 +204,7 @@ export default defineConfig({ async writeFile(projectId: string, filePath: string, content: string): Promise { const fullPath = `${this.dir}/${projectId}/${filePath}`; const dir = fullPath.split('/').slice(0, -1).join('/'); - await this.fs.promises.mkdir(dir, { recursive: true }); + await this.fs.promises.mkdir(dir); await this.fs.promises.writeFile(fullPath, content); // Update last modified diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index a778b3b0..aaa4ad74 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -4,8 +4,9 @@ import { fsManager, type Project } from '@/lib/fs'; import { ChatPane } from '@/components/Shakespeare/ChatPane'; import { PreviewPane } from '@/components/Shakespeare/PreviewPane'; import { Button } from '@/components/ui/button'; -import { ArrowLeft } from 'lucide-react'; +import { ArrowLeft, Settings } from 'lucide-react'; import { useNavigate } from 'react-router-dom'; +import { AISettingsDialog } from '@/components/ai/AISettingsDialog'; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); @@ -70,21 +71,24 @@ export function ProjectView() { -
- - +
+ +
+ + +
@@ -101,4 +105,4 @@ export function ProjectView() {
); -} \ No newline at end of file +} diff --git a/src/pages/ShakespeareHome.tsx b/src/pages/ShakespeareHome.tsx index 79eaed60..ec772bab 100644 --- a/src/pages/ShakespeareHome.tsx +++ b/src/pages/ShakespeareHome.tsx @@ -149,4 +149,4 @@ export function ShakespeareHome() { ); -} \ No newline at end of file +}