baseline auto-build/deploy

This commit is contained in:
Chad Curtis committed 2025-08-20 11:11:39 +00:00
1 parent ebc180a850
commit 0140e46894
5 files changed
+624 -6

No files matched your search

+1
View File
@@ -29,3 +29,4 @@ dist-ssr
.env
.env.*
!.env.example
.ai/
+289 -6
View File
@@ -34,6 +34,8 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
const [isBuildLoading, setIsBuildLoading] = useState(false);
const [isDeployLoading, setIsDeployLoading] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const messagesRef = useRef<AIMessage[]>([]);
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);
}
}
};
+165
View File
@@ -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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
expect(screen.getByText(/some_custom_tool/)).toBeInTheDocument();
});
});
});
+59
View File
@@ -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 (
<BuildAction
key={key}
action={actionType}
result={fullText}
isError={isError}
isLoading={isLoading}
/>
);
}
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 (
<div className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
@@ -117,6 +170,12 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
<>
{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 (
<div key={index} className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
+110
View File
@@ -0,0 +1,110 @@
import { memo } from 'react';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Play, Loader2, XCircle, CheckCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
interface BuildActionProps {
action: 'build' | 'deploy' | 'auto-build' | 'auto-fix';
result?: string;
isError?: boolean;
isLoading?: boolean;
}
export const BuildAction = memo(({ action, result, isError = false, isLoading = false }: BuildActionProps) => {
const getActionIcon = () => {
if (isLoading) return <Loader2 className="h-4 w-4 animate-spin" />;
if (isError) return <XCircle className="h-4 w-4 text-destructive" />;
return <Play className="h-4 w-4" />;
};
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 (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted")}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{getActionIcon()}
<span className="font-mono text-sm font-medium">{getActionTitle()}</span>
</div>
<div className="flex items-center gap-2">
{isLoading ? (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
Running
</Badge>
) : isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
Success
</Badge>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="text-sm text-muted-foreground mb-3">
{getActionDescription()}
</div>
{result && (
<div className={cn(
"p-3 rounded-md text-sm",
isError
? "bg-destructive/10 text-destructive border border-destructive/20"
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
)}>
<pre className="whitespace-pre-wrap break-words">{result}</pre>
</div>
)}
</CardContent>
</Card>
);
});
BuildAction.displayName = 'BuildAction';