Fix the behavior of the create project textarea

This commit is contained in:
Alex Gleason committed 2025-08-25 16:59:51 -05:00
1 parent 857bea336a
commit 53e07d1f26
6 files changed
+315 -50

No files matched your search

+23
View File
@@ -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,
+51 -39
View File
@@ -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,
+92
View File
@@ -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);
});
});
+94
View File
@@ -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<string> => {
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
};
}
+11 -5
View File
@@ -36,11 +36,11 @@ export class ProjectsManager {
}
}
async createProject(name: string): Promise<Project> {
const project = await this.cloneProject(name, GIT_TEMPLATE_URL);
async createProject(name: string, customId?: string): Promise<Project> {
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<Project> {
async cloneProject(name: string, repoUrl: string, customId?: string): Promise<Project> {
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);
+44 -6
View File
@@ -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() {
<div className="absolute bottom-3 right-3">
<Button
onClick={handleCreateProject}
disabled={!prompt.trim() || isCreating}
disabled={!prompt.trim() || isCreating || isGeneratingId}
size="sm"
className="h-8 rounded-lg"
>
{isCreating ? (
{isCreating || isGeneratingId ? (
<>
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white mr-2"></div>
Creating...
{isGeneratingId ? 'Generating...' : 'Creating...'}
</>
) : (
<>