From b3d4deedc80220367cec10173a3029ded08dacb3 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Wed, 20 Aug 2025 15:30:10 +0000 Subject: [PATCH] further refactor + remove auto-fix for now --- .gitignore | 3 +- src/components/Shakespeare/ChatPane.tsx | 171 ++------------------ src/components/ai/AssistantContent.test.tsx | 65 ++------ src/components/ai/AssistantContent.tsx | 21 ++- src/components/ai/BuildAction.tsx | 33 ++-- src/pages/ProjectView.tsx | 16 +- src/types/build.ts | 33 ++++ 7 files changed, 102 insertions(+), 240 deletions(-) create mode 100644 src/types/build.ts diff --git a/.gitignore b/.gitignore index 086cb28e..57dc219c 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* +.ai/ node_modules dist @@ -29,4 +30,4 @@ dist-ssr .env .env.* !.env.example -.ai/ + diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index e5c47ab4..02981826 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -1,5 +1,6 @@ import { useState, useRef, useEffect } from 'react'; import { CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage, generateId } from 'ai'; + import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { Send, Settings, Play, CloudUpload, Loader2 } from 'lucide-react'; @@ -23,39 +24,21 @@ import { buildProject } from "@/lib/build"; interface ChatPaneProps { projectId: string; projectName: string; + onBuildComplete?: (projectId: string) => void; } -interface ValidationError { - name: string; - issues?: Array<{ path: (string | number)[]; message: string }>; - cause?: ValidationError; -} + type AIMessage = (CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string }; -export function ChatPane({ projectId, projectName }: ChatPaneProps) { +export function ChatPane({ projectId, projectName, onBuildComplete }: ChatPaneProps) { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); const [isBuildLoading, setIsBuildLoading] = useState(false); const [isDeployLoading, setIsDeployLoading] = useState(false); const scrollAreaRef = useRef(null); - const messagesRef = useRef([]); - const autoFixAttemptsRef = useRef(0); - const [shouldSwitchToPreview, setShouldSwitchToPreview] = useState(false); - // Handle preview tab switching via React state instead of DOM manipulation - useEffect(() => { - if (shouldSwitchToPreview) { - // This will be handled by the parent component that controls tabs - // We'll emit a custom event that the parent can listen to - const switchEvent = new CustomEvent('switchToPreview', { - detail: { projectId }, - }); - window.dispatchEvent(switchEvent); - setShouldSwitchToPreview(false); - } - }, [shouldSwitchToPreview, projectId]); const { settings, isConfigured } = useAISettings(); const { fs: browserFS } = useFS(); const { runtime } = useJSRuntime(); @@ -77,9 +60,7 @@ 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); - const newMessages = Array.from(messageMap.values()); - messagesRef.current = newMessages; - return newMessages; + return Array.from(messageMap.values()); }); }; @@ -87,127 +68,11 @@ 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)); - const updatedMessages = Array.from(messageMap.values()); - messagesRef.current = updatedMessages; - return updatedMessages; + return Array.from(messageMap.values()); }); }; - const handleAutoFix = async (errorType: 'build' | 'api', error: unknown) => { - if (autoFixAttemptsRef.current >= 3) { - const errorDetails = error instanceof Error ? error.message : 'Unknown error'; - addMessage({ - id: generateId(), - role: 'assistant', - content: `⚠️ Auto-fix attempt limit reached. Please ${errorType === 'build' ? 'fix the build error' : 'try rephrasing your request'} manually: ${errorDetails}`, - }); - setIsLoading(false); - return; - } - autoFixAttemptsRef.current++; - console.log(`Auto-fix ${errorType} error attempt ${autoFixAttemptsRef.current}/3`); - - const errorDetails = error instanceof Error ? error.message : 'Unknown error'; - - const createFixMessages = (): [AIMessage, AIMessage] => { - const baseErrorMessage = { - id: generateId(), - role: 'assistant' as const, - content: errorType === 'build' - ? `❌ Auto-build failed. Analyzing error and attempting to fix automatically...` - : `❌ AI response error detected. Analyzing and attempting to fix automatically...`, - }; - - if (errorType === 'build') { - const buildErrorContent = typeof error === 'object' && error !== null && 'toString' in error - ? error.toString() - : errorDetails; - - const fixRequest: 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.`, - }; - - return [baseErrorMessage, fixRequest]; - } - - const caughtError = error as ValidationError; - const errorCause = caughtError.cause; - let validationErrors = ''; - - if ((caughtError.name === 'AI_TypeValidationError' || caughtError.name === 'ZodError') && caughtError.issues) { - validationErrors = caughtError.issues - .map(issue => `- ${issue.path.join('.')}: ${issue.message}`) - .join('\n'); - } else if (errorCause?.issues) { - validationErrors = errorCause.issues - .map(issue => `- ${issue.path.join('.')}: ${issue.message}`) - .join('\n'); - } - - const fixRequest: 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`, - }; - - return [baseErrorMessage, fixRequest]; - }; - - const [errorMessage, fixRequest] = createFixMessages(); - addMessage(errorMessage); - addMessage(fixRequest); - - try { - updateMetadata('Shakespeare', `Fixing ${errorType} error for ${projectName}...`); - const currentMessages = messagesRef.current; - await createAIChat(projectId, [...currentMessages, errorMessage, fixRequest]); - } catch (fixError) { - console.error('Failed to get AI to fix error:', fixError); - addMessage({ - id: generateId(), - role: 'assistant', - content: `❌ Failed to auto-fix the ${errorType} error. Please ${errorType === 'build' ? 'try fixing manually' : 'try rephrasing your request or try again later'}: ${errorDetails}`, - }); - } finally { - setIsLoading(false); - } - }; const runBuild = async () => { if (isBuildLoading) return; @@ -322,8 +187,7 @@ 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) => { @@ -367,7 +231,6 @@ BASE_DOMAIN=nostrdeploy.com`); // 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...'); - autoFixAttemptsRef.current = 0; setTimeout(async () => { if (isBuildLoading || isDeployLoading) { @@ -381,10 +244,9 @@ BASE_DOMAIN=nostrdeploy.com`); try { await runBuild(); - - window.dispatchEvent(new CustomEvent('buildComplete', { detail: { projectId } })); - setShouldSwitchToPreview(true); - + if (onBuildComplete) { + onBuildComplete(projectId); + } addMessage({ id: generateId(), role: 'assistant', @@ -392,7 +254,11 @@ BASE_DOMAIN=nostrdeploy.com`); }); } catch (error) { console.error('Auto-build failed:', error); - await handleAutoFix('build', error); + addMessage({ + id: generateId(), + role: 'assistant', + content: `❌ Auto-build failed: ${error instanceof Error ? error.message : 'Unknown error'}`, + }); } }, 1000); } @@ -460,14 +326,7 @@ When creating new components or pages, follow the existing patterns in the codeb } catch (error) { console.error('AI chat error:', error); - // Check if this is an AI API error that can be auto-fixed - if (error && typeof error === 'object' && 'name' in error && - (error.name === 'AI_APICallError' || error.name === 'AI_TypeValidationError' || - error.name === 'ZodError')) { - await handleAutoFix('api', error); - return; // Don't set isLoading(false) here as it's handled in handleAutoFix - } // Handle other types of errors with the original logic const errorMessage: AIMessage = { diff --git a/src/components/ai/AssistantContent.test.tsx b/src/components/ai/AssistantContent.test.tsx index 44bce06e..8c9762db 100644 --- a/src/components/ai/AssistantContent.test.tsx +++ b/src/components/ai/AssistantContent.test.tsx @@ -4,67 +4,22 @@ import { AssistantContent } from './AssistantContent'; import { TestApp } from '@/test/TestApp'; import type { CoreToolMessage } from 'ai'; + describe('AssistantContent', () => { const mockToolResults: CoreToolMessage[] = []; describe('Build Action Detection', () => { - const testCases = [ - { - name: 'auto-build success', - content: '✅ Agent completed successfully. Project built and preview updated!', - expectedTitle: 'Auto-Build Project', - expectedStatus: 'Success' - }, - { - name: 'build error', - content: '❌ Auto-build failed. Analyzing error and attempting to fix automatically...', - expectedTitle: 'Auto-Build Project', - expectedStatus: 'Failed' - }, - { - name: 'build loading', - content: '🔄 Building project...', - expectedTitle: 'Build Project', - expectedStatus: 'Running' - }, - { - name: 'deploy success', - content: '🎉 Deploy completed successfully!', - expectedTitle: 'Deploy Project', - expectedStatus: 'Success' - }, - { - name: 'auto-fix', - content: '⚠️ Auto-fix attempt limit reached. Please fix the build error manually', - expectedTitle: 'Auto-Fix Error', - expectedStatus: 'Success' - } - ]; + it('should render build action for auto-build success message', () => { + const content = '✅ Agent completed successfully. Project built and preview updated!'; - testCases.forEach(({ name, content, expectedTitle, expectedStatus }) => { - it(`should render ${name} action for string content`, () => { - render( - - - - ); + render( + + + + ); - expect(screen.getByText(expectedTitle)).toBeInTheDocument(); - expect(screen.getByText(expectedStatus)).toBeInTheDocument(); - }); - - it(`should render ${name} action for array content`, () => { - const arrayContent = [{ type: 'text' as const, text: content }]; - - render( - - - - ); - - expect(screen.getByText(expectedTitle)).toBeInTheDocument(); - expect(screen.getByText(expectedStatus)).toBeInTheDocument(); - }); + // Check if BuildAction component is rendered + expect(screen.queryByText(/Project/)).toBeInTheDocument(); }); it('should render regular markdown for non-build-action string content', () => { diff --git a/src/components/ai/AssistantContent.tsx b/src/components/ai/AssistantContent.tsx index f2699c42..8ae4c549 100644 --- a/src/components/ai/AssistantContent.tsx +++ b/src/components/ai/AssistantContent.tsx @@ -11,6 +11,7 @@ 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 { @@ -66,32 +67,31 @@ 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) => { - if (!/(✅|❌|⏸️|🔄|🎉|⚠️|👀).*?(Agent completed successfully|Auto-building|Build|Deploy|Auto-fix|Building|Deploying|Fixing|Preview updated)/i.test(text)) { + if (!/(✅|❌|⏸️|🔄|🎉|🎉)/.test(text) || !/(Agent completed successfully|Auto-build|Build|Deploy|Building|Deploying)/i.test(text)) { return null; } - const getActionType = (): 'build' | 'deploy' | 'auto-build' | 'auto-fix' => { + const getActionType = (): 'BUILD' | 'DEPLOY' | 'AUTO_BUILD' => { if (text.includes('Auto-build') || text.includes('Auto-building') || (text.includes('Agent completed successfully') && text.includes('built'))) { - return 'auto-build'; - } - if (text.includes('Auto-fix') || text.includes('Fixing')) { - return 'auto-fix'; + return 'AUTO_BUILD'; } if (text.includes('Deploy') || text.includes('Deploying')) { - return 'deploy'; + return 'DEPLOY'; } - return 'build'; + return 'BUILD'; }; const getStatus = () => { - const icon = text.match(/(✅|❌|⏸️|🔄|🎉|⚠️|👀)/)?.[1]; + const icon = text.match(/(✅|❌|⏸️|🔄|🎉)/)?.[1]; if (icon === '❌' || text.includes('failed')) { return { isError: true, isLoading: false }; } - if (icon === '⏸️' || icon === '🔄' || /(Building|Deploying|Fixing)/i.test(text)) { + if (icon === '⏸️' || icon === '🔄' || /(Building|Deploying)/i.test(text)) { return { isError: false, isLoading: true }; } return { isError: false, isLoading: false }; @@ -118,7 +118,6 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo if (buildAction) { return buildAction; } - return (
{ +export const BuildAction = memo(({ action, result, status, isError, isLoading }: BuildActionProps) => { + // Handle both new status-based and old boolean-based props for compatibility + const effectiveStatus = status || ( + isLoading ? 'RUNNING' : + isError ? 'FAILED' : 'SUCCESS' + ); + const actionConfig = { build: { title: 'Build Project', verb: 'build' }, deploy: { title: 'Deploy Project', verb: 'deploy' }, 'auto-build': { title: 'Auto-Build Project', verb: 'auto-build' }, - 'auto-fix': { title: 'Auto-Fix Error', verb: 'auto-fix' }, }[action] || { title: 'Build Action', verb: 'process' }; const getActionIcon = () => { - if (isLoading) return ; - if (isError) return ; + if (effectiveStatus === 'RUNNING') return ; + if (effectiveStatus === 'FAILED') return ; return ; }; const getActionDescription = () => { - if (isLoading) return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)}${action === 'auto-fix' ? 'ing error' : 'ing project'}...`; - if (isError) return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)} failed`; - if (result) return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)} completed`; + if (effectiveStatus === 'RUNNING') return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)}ing project...`; + if (effectiveStatus === 'FAILED') return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)} failed`; + if (effectiveStatus === 'SUCCESS') return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)} completed`; return `Starting ${actionConfig.verb} process...`; }; return ( - +
@@ -41,12 +44,12 @@ export const BuildAction = memo(({ action, result, isError = false, isLoading = {actionConfig.title}
- {isLoading ? ( + {effectiveStatus === 'RUNNING' ? ( Running - ) : isError ? ( + ) : effectiveStatus === 'FAILED' ? ( Failed @@ -69,7 +72,7 @@ export const BuildAction = memo(({ action, result, isError = false, isLoading = {result && (
diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 14ac9c72..64ebfdc3 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -17,6 +17,10 @@ export function ProjectView() { const [project, setProject] = useState(null); const [isLoading, setIsLoading] = useState(true); const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview'); + + const handleBuildComplete = useCallback(() => { + setActiveTab('preview'); + }, []); const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat'); const projectsManager = useProjectsManager(); const navigate = useNavigate(); @@ -117,7 +121,11 @@ export function ProjectView() {
{mobileView === 'chat' && ( - + )} {(mobileView === 'preview' || mobileView === 'code') && ( - +
diff --git a/src/types/build.ts b/src/types/build.ts new file mode 100644 index 00000000..b4c0790a --- /dev/null +++ b/src/types/build.ts @@ -0,0 +1,33 @@ +export const BuildActionType = { + BUILD: 'build', + DEPLOY: 'deploy', + AUTO_BUILD: 'auto-build', +} as const; + +export type BuildActionType = keyof typeof BuildActionType; + +export const BuildActionStatus = { + SUCCESS: 'success', + FAILED: 'failed', + RUNNING: 'running', + PENDING: 'pending', +} as const; + +export type BuildActionStatus = keyof typeof BuildActionStatus; + +export interface BuildActionContent { + type: 'build-action'; + action: BuildActionType; + status: BuildActionStatus; + message: string; + timestamp: number; +} + +export interface BuildActionComponentProps { + action: BuildActionType; + result?: string; + status?: BuildActionStatus; + isError?: boolean; + isLoading?: boolean; +} +