diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index b134e789..86a8bb9e 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -1,4 +1,5 @@ import { useState, useRef, useEffect } from 'react'; +import { useSearchParams } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; @@ -40,6 +41,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { const { isConfigured } = useAISettings(); const { fs: browserFS } = useFS(); const { runtime } = useJSRuntime(); + const [searchParams, setSearchParams] = useSearchParams(); // Initialize AI chat with tools const cwd = `/projects/${projectId}`; @@ -94,6 +96,7 @@ When creating new components or pages, follow the existing patterns in the codeb streamingMessage, isLoading, sendMessage, + startGeneration, stopGeneration, startNewSession, } = useAIChat({ @@ -107,6 +110,26 @@ When creating new components or pages, follow the existing patterns in the codeb } }); + // Check for autostart parameter and trigger AI generation + useEffect(() => { + const autostart = searchParams.get('autostart'); + + if (autostart === 'true' && isConfigured && messages.length > 0 && !isLoading) { + const lastMessage = messages[messages.length - 1]; + + // If the last message is from the user, auto-start the AI + if (lastMessage.role === 'user') { + // Clear the autostart parameter so it doesn't trigger again + const newSearchParams = new URLSearchParams(searchParams); + newSearchParams.delete('autostart'); + setSearchParams(newSearchParams, { replace: true }); + + // Start AI generation + startGeneration(providerModel.trim() || undefined); + } + } + }, [searchParams, setSearchParams, isConfigured, messages, isLoading, startGeneration, providerModel]); + // Keep-alive functionality to prevent tab throttling during AI processing const { updateMetadata } = useKeepAlive({ enabled: isLoading || isBuildLoading || isDeployLoading, diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index aa45461e..c450ae9d 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -62,53 +62,21 @@ export function useAIChat({ }); }, [saveMessagesToHistory]); - // Load message history when component mounts or projectId changes - useEffect(() => { - const loadMessageHistory = async () => { - try { - const dotAI = new DotAI(fs, `/projects/${projectId}`); - const lastSession = await dotAI.readLastSessionHistory(); + const startGeneration = useCallback(async (providerModel?: string) => { + if (!isConfigured || isLoading || messages.length === 0) return; - if (lastSession) { - setMessages(lastSession.messages); - setSessionName(lastSession.sessionName); - } else { - // No history to load, start fresh - setMessages([]); - setSessionName(DotAI.generateSessionName()); - } - } catch (error) { - console.warn('Failed to load message history:', error); - // Start fresh on any error - setMessages([]); - setSessionName(DotAI.generateSessionName()); - } - }; + // Get the last message - it should be a user message + const lastMessage = messages[messages.length - 1]; + if (lastMessage.role !== 'user') return; - loadMessageHistory(); - }, [projectId, fs]); - - const sendMessage = useCallback(async (content: string, providerModel?: string) => { - if (!isConfigured || isLoading) return; - - // Add user message - const userMessage: AIMessage = { - role: 'user', - content - }; - - addMessage(userMessage); setIsLoading(true); try { // Create abort controller for this request abortControllerRef.current = new AbortController(); - // Get all messages including the new user message - const allMessages = [...messages, userMessage]; - - // Use messages directly as they're already in OpenAI format - const modelMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = allMessages; + // Use all existing messages + const modelMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [...messages]; // Add system message if provided if (systemPrompt) { @@ -375,6 +343,49 @@ export function useAIChat({ } }, [isConfigured, isLoading, addMessage, messages, settings.providers, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps]); + // Load message history when component mounts or projectId changes + useEffect(() => { + const loadMessageHistory = async () => { + try { + const dotAI = new DotAI(fs, `/projects/${projectId}`); + const lastSession = await dotAI.readLastSessionHistory(); + + if (lastSession) { + setMessages(lastSession.messages); + setSessionName(lastSession.sessionName); + } else { + // No history to load, start fresh + setMessages([]); + setSessionName(DotAI.generateSessionName()); + } + } catch (error) { + console.warn('Failed to load message history:', error); + // Start fresh on any error + setMessages([]); + setSessionName(DotAI.generateSessionName()); + } + }; + + loadMessageHistory(); + }, [projectId, fs]); + + const sendMessage = useCallback(async (content: string, providerModel?: string) => { + if (!isConfigured || isLoading) return; + + // Add user message + const userMessage: AIMessage = { + role: 'user', + content + }; + + addMessage(userMessage); + + // Use setTimeout to ensure the message is added before starting generation + setTimeout(() => { + startGeneration(providerModel); + }, 0); + }, [isConfigured, isLoading, addMessage, startGeneration]); + const stopGeneration = useCallback(() => { if (abortControllerRef.current) { abortControllerRef.current.abort(); @@ -400,6 +411,7 @@ export function useAIChat({ streamingMessage, isLoading, sendMessage, + startGeneration, stopGeneration, clearMessages, startNewSession, diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts new file mode 100644 index 00000000..3d2f3a0d --- /dev/null +++ b/src/hooks/useAIProjectId.test.ts @@ -0,0 +1,92 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { renderHook } from '@testing-library/react'; +import { useAIProjectId } from './useAIProjectId'; +import { useAISettings } from './useAISettings'; + +// Mock the useAISettings hook +vi.mock('./useAISettings'); + +describe('useAIProjectId', () => { + const mockUseAISettings = vi.mocked(useAISettings); + + beforeEach(() => { + vi.clearAllMocks(); + + // Mock fetch globally + global.fetch = vi.fn(); + }); + + it('should return not configured when AI settings are not configured', () => { + mockUseAISettings.mockReturnValue({ + settings: { providers: {} }, + isConfigured: false, + updateSettings: vi.fn(), + addProvider: vi.fn(), + removeProvider: vi.fn(), + updateProvider: vi.fn(), + }); + + const { result } = renderHook(() => useAIProjectId()); + + expect(result.current.isConfigured).toBe(false); + expect(result.current.isLoading).toBe(false); + }); + + it('should throw error when trying to generate ID without configuration', async () => { + mockUseAISettings.mockReturnValue({ + settings: { providers: {} }, + isConfigured: false, + updateSettings: vi.fn(), + addProvider: vi.fn(), + removeProvider: vi.fn(), + updateProvider: vi.fn(), + }); + + const { result } = renderHook(() => useAIProjectId()); + + await expect(result.current.generateProjectId('test prompt')).rejects.toThrow( + 'AI settings not configured' + ); + }); + + it('should throw error when prompt is empty', async () => { + mockUseAISettings.mockReturnValue({ + settings: { + providers: { + openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + } + }, + isConfigured: true, + updateSettings: vi.fn(), + addProvider: vi.fn(), + removeProvider: vi.fn(), + updateProvider: vi.fn(), + }); + + const { result } = renderHook(() => useAIProjectId()); + + await expect(result.current.generateProjectId('')).rejects.toThrow( + 'Prompt cannot be empty' + ); + }); + + it('should have configured status when providers are available', () => { + mockUseAISettings.mockReturnValue({ + settings: { + providers: { + openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + } + }, + isConfigured: true, + updateSettings: vi.fn(), + addProvider: vi.fn(), + removeProvider: vi.fn(), + updateProvider: vi.fn(), + }); + + const { result } = renderHook(() => useAIProjectId()); + + expect(result.current.isConfigured).toBe(true); + expect(result.current.isLoading).toBe(false); + }); +}); \ No newline at end of file diff --git a/src/hooks/useAIProjectId.ts b/src/hooks/useAIProjectId.ts new file mode 100644 index 00000000..291c6da6 --- /dev/null +++ b/src/hooks/useAIProjectId.ts @@ -0,0 +1,94 @@ +import { useState, useCallback } from 'react'; +import OpenAI from 'openai'; +import { useAISettings } from '@/hooks/useAISettings'; + +interface UseAIProjectIdOptions { + onError?: (error: string) => void; +} + +export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) { + const [isLoading, setIsLoading] = useState(false); + const { settings, isConfigured } = useAISettings(); + + const generateProjectId = useCallback(async (prompt: string): Promise => { + if (!isConfigured) { + throw new Error('AI settings not configured'); + } + + if (!prompt.trim()) { + throw new Error('Prompt cannot be empty'); + } + + setIsLoading(true); + + try { + // Use first available provider as fallback + const providers = settings.providers || {}; + const firstProvider = Object.keys(providers)[0]; + if (!firstProvider || !providers[firstProvider]?.apiKey) { + throw new Error('No configured AI providers available'); + } + + const connectionConfig = providers[firstProvider]; + 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 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. + +Rules: +- Use only lowercase letters, numbers, and hyphens +- Keep it between 2-4 words +- Make it descriptive but concise +- No spaces, underscores, or special characters except hyphens +- Examples: + - "farming equipment marketplace" → "farming-marketplace" + - "social media for artists" → "artist-social-app" + - "crypto trading dashboard" → "crypto-dashboard" + - "recipe sharing platform" → "recipe-platform" + +Respond with ONLY the project ID, no explanation or additional text.`; + + const completion = await openai.chat.completions.create({ + model: modelName, + messages: [ + { role: 'system', content: systemPrompt }, + { role: 'user', content: prompt } + ], + max_tokens: 20, + temperature: 0.3, + }); + + const projectId = completion.choices[0]?.message?.content?.trim(); + + if (!projectId) { + throw new Error('Failed to generate project ID'); + } + + // Validate the generated ID + const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/; + if (!validIdRegex.test(projectId)) { + throw new Error('Generated project ID is invalid'); + } + + return projectId; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID'; + onError?.(errorMessage); + throw new Error(errorMessage); + } finally { + setIsLoading(false); + } + }, [isConfigured, settings, onError]); + + return { + generateProjectId, + isLoading, + isConfigured + }; +} \ No newline at end of file diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 8aa66751..bd55f7ab 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -36,11 +36,11 @@ export class ProjectsManager { } } - async createProject(name: string): Promise { - const project = await this.cloneProject(name, GIT_TEMPLATE_URL); + async createProject(name: string, customId?: string): Promise { + const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId); try { - await this.fs.mkdir(this.dir + `/${name}/.ai/history`, { recursive: true }); + await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true }); } catch { // Directory might already exist } @@ -48,9 +48,15 @@ export class ProjectsManager { return project; } - async cloneProject(name: string, repoUrl: string): Promise { + async cloneProject(name: string, repoUrl: string, customId?: string): Promise { const url = new URL(repoUrl); - const id = await this.generateUniqueProjectId(name); + const id = customId || await this.generateUniqueProjectId(name); + + // Check if project with this ID already exists when using custom ID + if (customId && await this.projectExists(id)) { + throw new Error(`Project with ID "${id}" already exists`); + } + const projectPath = `${this.dir}/${id}`; await this.fs.mkdir(projectPath); diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 3f2a64de..14449b04 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -1,9 +1,13 @@ import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useProjectsManager } from '@/hooks/useProjectsManager'; +import { useAIProjectId } from '@/hooks/useAIProjectId'; +import { useFS } from '@/hooks/useFS'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { AppLayout } from '@/components/AppLayout'; +import { DotAI } from '@/lib/DotAI'; +import type { AIMessage } from '@/hooks/useAIChat'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; @@ -16,7 +20,9 @@ export default function Index() { const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', ''); const navigate = useNavigate(); const projectsManager = useProjectsManager(); + const { fs } = useFS(); const { user: _user } = useCurrentUser(); + const { generateProjectId, isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId(); useSeoMeta({ title: 'Shakespeare - AI-Powered Nostr Development', @@ -45,8 +51,40 @@ export default function Index() { setIsCreating(true); try { - const project = await projectsManager.createProject(prompt.trim()); - navigate(`/project/${project.id}`); + let projectId: string; + + if (isAIConfigured) { + // Use AI to generate project ID + try { + projectId = await generateProjectId(prompt.trim()); + } catch (error) { + console.error('Failed to generate AI project ID:', error); + // Fallback to manual project creation if AI fails + const project = await projectsManager.createProject(prompt.trim()); + navigate(`/project/${project.id}`); + return; + } + } else { + // Fallback to manual project creation if AI not configured + const project = await projectsManager.createProject(prompt.trim()); + navigate(`/project/${project.id}`); + return; + } + + // Create project with AI-generated ID + const project = await projectsManager.createProject(prompt.trim(), projectId); + + // Store the initial message in chat history using DotAI + const dotAI = new DotAI(fs, `/projects/${project.id}`); + const sessionName = DotAI.generateSessionName(); + const initialMessage: AIMessage = { + role: 'user', + content: prompt.trim() + }; + await dotAI.setHistory(sessionName, [initialMessage]); + + // Navigate to the project with autostart parameter + navigate(`/project/${project.id}?autostart=true`); } catch (error) { console.error('Failed to create project:', error); } finally { @@ -78,7 +116,7 @@ export default function Index() { value={prompt} onChange={handlePromptChange} className="min-h-[120px] max-h-64 resize-none border-0 bg-transparent px-4 py-3 pb-16 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground" - disabled={isCreating} + disabled={isCreating || isGeneratingId} rows={4} style={{ height: 'auto', @@ -95,14 +133,14 @@ export default function Index() {