From 0140e4689491a6f75b580b802249555cccd65998 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Wed, 20 Aug 2025 11:11:39 +0000 Subject: [PATCH] baseline auto-build/deploy --- .gitignore | 1 + src/components/Shakespeare/ChatPane.tsx | 295 +++++++++++++++++++- src/components/ai/AssistantContent.test.tsx | 165 +++++++++++ src/components/ai/AssistantContent.tsx | 59 ++++ src/components/ai/BuildAction.tsx | 110 ++++++++ 5 files changed, 624 insertions(+), 6 deletions(-) create mode 100644 src/components/ai/AssistantContent.test.tsx create mode 100644 src/components/ai/BuildAction.tsx diff --git a/.gitignore b/.gitignore index 2f1999c0..086cb28e 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ dist-ssr .env .env.* !.env.example +.ai/ diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 0ff3dbf1..60452679 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -34,6 +34,8 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { const [isBuildLoading, setIsBuildLoading] = useState(false); const [isDeployLoading, setIsDeployLoading] = useState(false); const scrollAreaRef = useRef(null); + const messagesRef = useRef([]); + const autoFixAttemptsRef = useRef(0); const { settings, isConfigured } = useAISettings(); const { fs: browserFS } = useFS(); const { runtime } = useJSRuntime(); @@ -55,7 +57,9 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { const addMessage = (message: AIMessage) => { setMessages((prev) => { const messageMap = new Map(prev.map(m => [m.id, m])).set(message.id, message); - return Array.from(messageMap.values()); + const newMessages = Array.from(messageMap.values()); + messagesRef.current = newMessages; + return newMessages; }); }; @@ -63,7 +67,9 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { setMessages((prev) => { const messageMap = new Map(prev.map(m => [m.id, m])); newMessages.forEach(msg => messageMap.set(msg.id, msg)); - return Array.from(messageMap.values()); + const updatedMessages = Array.from(messageMap.values()); + messagesRef.current = updatedMessages; + return updatedMessages; }); }; @@ -180,6 +186,9 @@ BASE_DOMAIN=nostrdeploy.com`); throw new Error('AI settings not configured'); } + // Reset auto-fix attempts on new successful AI interaction + autoFixAttemptsRef.current = 0; + // Create a custom fetch function for the AI provider const customFetch = async (url: string, options: RequestInit) => { return fetch(url, { @@ -218,6 +227,169 @@ BASE_DOMAIN=nostrdeploy.com`); updateMetadata('Shakespeare', `Working on ${projectName} - ${toolName}`); } } + + // Check if this is the final step with a successful finish reason + if (stepResult.finishReason === 'stop' && stepResult.response.messages.length > 0) { + console.log('Agent finished successfully, auto-building project...'); + + // Reset auto-fix attempts on successful completion + autoFixAttemptsRef.current = 0; + + // Add a system message to indicate auto-build is starting + const autoBuildMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: 'βœ… Agent completed successfully. Auto-building project and checking deployment preview...', + }; + addMessage(autoBuildMessage); + + // Auto-build the project after a short delay + setTimeout(async () => { + try { + // Check if build is already running to avoid conflicts + if (isBuildLoading || isDeployLoading) { + console.log('Build or deploy already in progress, skipping auto-build'); + const skipMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: '⏸️ Build or deploy already in progress. Skipping auto-build.', + }; + addMessage(skipMessage); + return; + } + + await runBuild(); + + // Dispatch build complete event to refresh preview + const buildCompleteEvent = new CustomEvent('buildComplete', { + detail: { projectId }, + }); + window.dispatchEvent(buildCompleteEvent); + console.log('Dispatched buildComplete event for project:', projectId); + + // Add success message + const buildSuccessMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: 'πŸŽ‰ Project built successfully! Checking deployment preview...', + }; + addMessage(buildSuccessMessage); + + // Switch to preview tab to show the updated deployment + setTimeout(() => { + try { + // Find and click the preview tab button + const previewButtons = Array.from(document.querySelectorAll('button')); + const previewButton = previewButtons.find(button => + button.textContent?.includes('Preview') && + button.getAttribute('variant') === 'default' + ) || previewButtons.find(button => + button.textContent?.includes('Preview') + ); + + if (previewButton) { + previewButton.click(); + console.log('Switched to preview tab'); + + // Add final success message + setTimeout(() => { + const finalMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: 'πŸ‘€ Preview updated! Your changes are now visible in the preview pane.', + }; + addMessage(finalMessage); + }, 1000); + } else { + console.log('Preview tab button not found'); + // Add message about manual preview switch + const manualSwitchMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: 'πŸ“± Project built successfully! Switch to the "Preview" tab to see your changes.', + }; + addMessage(manualSwitchMessage); + } + } catch (switchError) { + console.error('Error switching to preview tab:', switchError); + } + }, 500); + + } catch (error) { + console.error('Auto-build failed:', error); + + // Extract build error details + const errorDetails = error instanceof Error ? error.message : 'Unknown error'; + const buildErrorContent = typeof error === 'object' && error !== null && 'toString' in error ? error.toString() : errorDetails; + + // Add error message to show user what happened + const buildErrorMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: `❌ Auto-build failed. Analyzing error and attempting to fix automatically...`, + }; + addMessage(buildErrorMessage); + + // Feed the build error back to the AI agent as a new problem to solve + const errorFixRequest: AIMessage = { + id: generateId(), + role: 'user', + content: `The build failed with the following error. Please analyze this error and fix the issue: + +\`\`\` +${buildErrorContent} +\`\`\` + +Common issues to check: +- Missing npm dependencies (install with npm_add_package tool) +- TypeScript errors (fix type definitions or imports) +- Missing files (create necessary files) +- Configuration issues (update config files) + +Please fix this issue and ensure the project builds successfully.`, + }; + addMessage(errorFixRequest); + + // Trigger the AI to fix the error + setTimeout(async () => { + // Check if we've exceeded auto-fix attempts + if (autoFixAttemptsRef.current >= 3) { + console.log('Auto-fix attempt limit reached, stopping auto-fix'); + const limitMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: `⚠️ Auto-fix attempt limit reached. Please fix the build error manually: ${errorDetails}`, + }; + addMessage(limitMessage); + return; + } + + autoFixAttemptsRef.current++; + console.log(`Auto-fix attempt ${autoFixAttemptsRef.current}/3`); + + try { + setIsLoading(true); + updateMetadata('Shakespeare', `Fixing build error for ${projectName}...`); + + // Get the current messages state using ref to ensure we have the latest + const currentMessages = messagesRef.current; + const aiMessages: AIMessage[] = [...currentMessages, autoBuildMessage, buildErrorMessage, errorFixRequest]; + await createAIChat(projectId, aiMessages); + } catch (fixError) { + console.error('Failed to get AI to fix build error:', fixError); + const fixErrorMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: `❌ Failed to auto-fix the build error. Please try fixing manually: ${errorDetails}`, + }; + addMessage(fixErrorMessage); + } finally { + setIsLoading(false); + } + }, 1000); + } + }, 1000); // Small delay to show the auto-build message first + } }, tools: { git_commit: new GitCommitTool(browserFS, cwd), @@ -272,21 +444,132 @@ When creating new components or pages, follow the existing patterns in the codeb setInput(''); setIsLoading(true); + const _isAutoFixCase = { value: false }; + try { const aiMessages: AIMessage[] = [...messages, userMessage]; updateMetadata('Shakespeare', `Processing your request for ${projectName}...`); await createAIChat(projectId, aiMessages); - } catch (error) { - console.error('AI chat error:', error); + } catch (caughtError) { + console.error('AI chat error:', caughtError); + + const _isAutoFixCase = { value: false }; + + // Check if this is an AI API error that can be auto-fixed + if (caughtError && typeof caughtError === 'object' && 'name' in caughtError && + (caughtError.name === 'AI_APICallError' || caughtError.name === 'AI_TypeValidationError' || + caughtError.name === 'ZodError')) { + + _isAutoFixCase.value = true; + + const errorDetails = caughtError instanceof Error ? caughtError.message : JSON.stringify(caughtError); + const errorCause = 'cause' in caughtError && caughtError.cause ? caughtError.cause : undefined; + + // Extract specific validation error details if available + let validationErrors = ''; + if (caughtError.name === 'AI_TypeValidationError' || caughtError.name === 'ZodError') { + if ('issues' in caughtError && Array.isArray(caughtError.issues)) { + validationErrors = caughtError.issues + .map((issue: { path: (string | number)[]; message: string }) => `- ${issue.path.join('.')}: ${issue.message}`) + .join('\n'); + } else if ('cause' in caughtError && caughtError.cause && 'issues' in caughtError.cause) { + validationErrors = caughtError.cause.issues + .map((issue: { path: (string | number)[]; message: string }) => `- ${issue.path.join('.')}: ${issue.message}`) + .join('\n'); + } + } + + // Add error message to show user what happened + const apiErrorMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: `❌ AI response error detected. Analyzing and attempting to fix automatically...`, + }; + addMessage(apiErrorMessage); + + // Feed the API error back to the AI agent as a new problem to solve + const errorFixRequest: AIMessage = { + id: generateId(), + role: 'user', + content: `The AI generated an invalid response that caused an error. Please analyze this error and regenerate a valid response: + +\`\`\` +Error Type: ${caughtError.name} +Error Details: ${errorDetails} +${validationErrors ? `Validation Errors:\n${validationErrors}` : ''} +${errorCause ? `Cause: ${JSON.stringify(errorCause, null, 2)}` : ''} +\`\`\` + +Common issues to check: +- Malformed tool calls (ensure all tool calls have proper 'name' and 'arguments' fields) +- Invalid JSON structure in responses +- Missing required fields in function calls +- Improperly formatted arguments +- Tool call name is undefined or empty +- Arguments are missing or malformed + +Please regenerate your response with the same intent but ensure it's properly formatted and valid. Make sure all tool calls are complete and correctly structured. Double-check that: +1. Every tool call has a 'name' field with the exact tool name +2. Every tool call has an 'arguments' field with valid JSON +3. All required arguments are provided +4. The JSON structure is valid`, + }; + addMessage(errorFixRequest); + + // Trigger the AI to fix the error + setTimeout(async () => { + // Check if we've exceeded auto-fix attempts + if (autoFixAttemptsRef.current >= 3) { + console.log('Auto-fix attempt limit reached for API error, stopping auto-fix'); + const limitMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: `⚠️ Auto-fix attempt limit reached for API error. Please try rephrasing your request or try again later.`, + }; + addMessage(limitMessage); + setIsLoading(false); + return; + } + + autoFixAttemptsRef.current++; + console.log(`Auto-fix API error attempt ${autoFixAttemptsRef.current}/3`); + + try { + updateMetadata('Shakespeare', `Fixing AI response error for ${projectName}...`); + + // Get the current messages state using ref to ensure we have the latest + const currentMessages = messagesRef.current; + const aiMessages: AIMessage[] = [...currentMessages, apiErrorMessage, errorFixRequest]; + await createAIChat(projectId, aiMessages); + } catch (fixError) { + console.error('Failed to get AI to fix API error:', fixError); + const fixErrorMessage: AIMessage = { + id: generateId(), + role: 'assistant', + content: `❌ Failed to auto-fix the AI response error. Please try rephrasing your request or try again later.`, + }; + addMessage(fixErrorMessage); + } finally { + setIsLoading(false); + } + }, 1000); + + return; // Don't set isLoading(false) here as it's handled in the timeout + } + + // Handle other types of errors with the original logic const errorMessage: AIMessage = { id: generateId(), role: 'assistant', - content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.', + content: caughtError instanceof Error ? caughtError.message : 'Sorry, I encountered an error. Please try again.', }; addMessage(errorMessage); } finally { - setIsLoading(false); + // Only set loading to false if we're not handling an auto-fix case + if (!_isAutoFixCase.value) { + setIsLoading(false); + } } }; diff --git a/src/components/ai/AssistantContent.test.tsx b/src/components/ai/AssistantContent.test.tsx new file mode 100644 index 00000000..d1427da1 --- /dev/null +++ b/src/components/ai/AssistantContent.test.tsx @@ -0,0 +1,165 @@ +import { describe, it, expect } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { AssistantContent } from './AssistantContent'; +import { TestApp } from '@/test/TestApp'; +import type { CoreToolMessage } from 'ai'; + +describe('AssistantContent', () => { + const mockToolResults: CoreToolMessage[] = []; + + describe('Build Action Detection', () => { + it('should render build action for string content with auto-build message', () => { + const content = 'βœ… Agent completed successfully. Auto-building project and checking deployment preview...'; + + render( + + + + ); + + expect(screen.getByText('Auto-Build Project')).toBeInTheDocument(); + expect(screen.getByText('Success')).toBeInTheDocument(); + }); + + it('should render build action for string content with build success message', () => { + const content = 'πŸŽ‰ Project built successfully! Checking deployment preview...'; + + render( + + + + ); + + expect(screen.getByText(/Build Project|Auto-Build Project/)).toBeInTheDocument(); + expect(screen.getByText('Success')).toBeInTheDocument(); + }); + + it('should render build action for string content with preview updated message', () => { + const content = 'πŸ‘€ Preview updated! Your changes are now visible in the preview pane.'; + + render( + + + + ); + + expect(screen.getByText(/Build Project|Auto-Build Project/)).toBeInTheDocument(); + expect(screen.getByText('Success')).toBeInTheDocument(); + }); + + it('should render build action for string content with error message', () => { + const content = '❌ Auto-build failed. Analyzing error and attempting to fix automatically...'; + + render( + + + + ); + + expect(screen.getByText('Auto-Build Project')).toBeInTheDocument(); + expect(screen.getByText('Failed')).toBeInTheDocument(); + }); + + it('should render build action for array content with auto-build message', () => { + const content = [ + { type: 'text' as const, text: 'βœ… Agent completed successfully. Auto-building project and checking deployment preview...' } + ]; + + render( + + + + ); + + expect(screen.getByText('Auto-Build Project')).toBeInTheDocument(); + expect(screen.getByText('Auto-build completed')).toBeInTheDocument(); + }); + + it('should render build action for array content with loading message', () => { + const content = [ + { type: 'text' as const, text: 'πŸ”„ Building project...' } + ]; + + render( + + + + ); + + expect(screen.getByText('Build Project')).toBeInTheDocument(); + expect(screen.getByText('Running')).toBeInTheDocument(); + }); + + it('should render build action for array content with deploy message', () => { + const content = [ + { type: 'text' as const, text: 'πŸŽ‰ Deploy completed successfully!' } + ]; + + render( + + + + ); + + expect(screen.getByText('Deploy Project')).toBeInTheDocument(); + expect(screen.getByText('Success')).toBeInTheDocument(); + }); + + it('should render build action for array content with auto-fix message', () => { + const content = [ + { type: 'text' as const, text: '⚠️ Auto-fix attempt limit reached. Please fix the build error manually: Some error details' } + ]; + + render( + + + + ); + + expect(screen.getByText('Auto-Fix Error')).toBeInTheDocument(); + expect(screen.getByText('Success')).toBeInTheDocument(); + }); + + it('should render regular markdown for non-build-action string content', () => { + const content = 'Hello, I can help you with your project.'; + + render( + + + + ); + + expect(screen.getByText('Hello, I can help you with your project.')).toBeInTheDocument(); + expect(screen.queryByText('Build Project')).not.toBeInTheDocument(); + }); + + it('should render regular markdown for non-build-action array content', () => { + const content = [ + { type: 'text' as const, text: 'Hello, I can help you with your project.' } + ]; + + render( + + + + ); + + expect(screen.getByText('Hello, I can help you with your project.')).toBeInTheDocument(); + expect(screen.queryByText('Build Project')).not.toBeInTheDocument(); + }); + + it('should render tool calls for array content with tool-call items', () => { + const content = [ + { type: 'tool-call' as const, toolName: 'some_custom_tool', toolCallId: 'test-id', args: { param1: 'value1' } } + ]; + + render( + + + + ); + + expect(screen.getByText(/some_custom_tool/)).toBeInTheDocument(); + }); + }); +}); \ No newline at end of file diff --git a/src/components/ai/AssistantContent.tsx b/src/components/ai/AssistantContent.tsx index 02c96463..9a60816a 100644 --- a/src/components/ai/AssistantContent.tsx +++ b/src/components/ai/AssistantContent.tsx @@ -10,6 +10,7 @@ import { FileWriter } from '@/components/ai/FileWriter'; import { ShellCommand } from '@/components/ai/ShellCommand'; import { PackageManager } from '@/components/ai/PackageManager'; import { GitCommit } from '@/components/ai/GitCommit'; +import { BuildAction } from '@/components/ai/BuildAction'; import type { CoreAssistantMessage, CoreToolMessage } from 'ai'; interface AssistantContentProps { @@ -64,8 +65,60 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo return { isError: toolResult.isError || false }; }; + + // Helper function to check and render build action + const renderBuildAction = (text: string, key: number | string) => { + const buildActionMatch = text.match(/(βœ…|❌|⏸️|πŸ”„|πŸŽ‰|⚠️|πŸ‘€).*?(Agent completed successfully|Auto-building|Build|Deploy|Auto-fix|Building|Deploying|Fixing|Preview updated)/i); + + if (buildActionMatch) { + const icon = buildActionMatch[1]; + const fullText = text; + + console.log('BuildAction Detection - Match found:', { icon, fullText }); + + let actionType: 'build' | 'deploy' | 'auto-build' | 'auto-fix' = 'build'; + let isError = false; + let isLoading = false; + + // Determine action type and status based on full text content + if (fullText.includes('Auto-build') || fullText.includes('Auto-building')) { + actionType = 'auto-build'; + } else if (fullText.includes('Auto-fix') || fullText.includes('Fixing')) { + actionType = 'auto-fix'; + } else if (fullText.includes('Deploy') || fullText.includes('Deploying')) { + actionType = 'deploy'; + } + + // Determine status + if (icon === '❌' || fullText.includes('failed')) { + isError = true; + } else if (icon === '⏸️' || icon === 'πŸ”„' || fullText.includes('Building') || fullText.includes('Deploying') || fullText.includes('Fixing')) { + isLoading = true; + } else if (icon === 'βœ…' || icon === 'πŸŽ‰' || icon === 'πŸ‘€') { + // Success state - no loading or error + } + + return ( + + ); + } + return null; + }; + // Handle string content (simple text messages) if (typeof content === 'string') { + // Check if this is a build action message + const buildAction = renderBuildAction(content, 'string-content'); + if (buildAction) { + return buildAction; + } + return (
{content.map((item, index) => { if (item.type === 'text') { + // Check if this is a build action message + const buildAction = renderBuildAction(item.text, index); + if (buildAction) { + return buildAction; + } + return (
{ + const getActionIcon = () => { + if (isLoading) return ; + if (isError) return ; + return ; + }; + + const getActionTitle = () => { + if (action === 'build') return 'Build Project'; + if (action === 'deploy') return 'Deploy Project'; + if (action === 'auto-build') return 'Auto-Build Project'; + if (action === 'auto-fix') return 'Auto-Fix Error'; + return 'Build Action'; + }; + + const getActionDescription = () => { + if (isLoading) { + if (action === 'build') return 'Building project...'; + if (action === 'deploy') return 'Deploying project...'; + if (action === 'auto-build') return 'Auto-building project...'; + if (action === 'auto-fix') return 'Auto-fixing error...'; + return 'Processing...'; + } + + if (isError) { + if (action === 'build') return 'Build failed'; + if (action === 'deploy') return 'Deploy failed'; + if (action === 'auto-build') return 'Auto-build failed'; + if (action === 'auto-fix') return 'Auto-fix failed'; + return 'Action failed'; + } + + if (result) { + if (action === 'build') return 'Build completed'; + if (action === 'deploy') return 'Deploy completed'; + if (action === 'auto-build') return 'Auto-build completed'; + if (action === 'auto-fix') return 'Auto-fix completed'; + return 'Action completed'; + } + + if (action === 'build') return 'Starting build process...'; + if (action === 'deploy') return 'Starting deploy process...'; + if (action === 'auto-build') return 'Starting auto-build process...'; + if (action === 'auto-fix') return 'Starting auto-fix process...'; + return 'Starting action...'; + }; + + return ( + + +
+
+ {getActionIcon()} + {getActionTitle()} +
+
+ {isLoading ? ( + + + Running + + ) : isError ? ( + + + Failed + + ) : ( + + + Success + + )} +
+
+
+ + +
+ {getActionDescription()} +
+ + {result && ( +
+
{result}
+
+ )} +
+
+ ); +}); + +BuildAction.displayName = 'BuildAction'; \ No newline at end of file