further refactor + remove auto-fix for now

This commit is contained in:
Chad Curtis committed 2025-08-20 15:30:21 +00:00
1 parent 0445b4d0c0
commit b3d4deedc8
7 files changed
+102 -240

No files matched your search

+2 -1
View File
@@ -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/
+15 -156
View File
@@ -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<AIMessage[]>([]);
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isBuildLoading, setIsBuildLoading] = useState(false);
const [isDeployLoading, setIsDeployLoading] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const messagesRef = useRef<AIMessage[]>([]);
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 = {
+10 -55
View File
@@ -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(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
render(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
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(
<TestApp>
<AssistantContent content={arrayContent} toolResults={mockToolResults} />
</TestApp>
);
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', () => {
+10 -11
View File
@@ -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 (
<div className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
+18 -15
View File
@@ -3,37 +3,40 @@ 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';
import type { BuildActionComponentProps } from '@/types/build';
interface BuildActionProps {
action: 'build' | 'deploy' | 'auto-build' | 'auto-fix';
interface BuildActionProps extends BuildActionComponentProps {
result?: string;
isError?: boolean;
isLoading?: boolean;
}
export const BuildAction = memo(({ action, result, isError = false, isLoading = false }: BuildActionProps) => {
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 <Loader2 className="h-4 w-4 animate-spin" />;
if (isError) return <XCircle className="h-4 w-4 text-destructive" />;
if (effectiveStatus === 'RUNNING') return <Loader2 className="h-4 w-4 animate-spin" />;
if (effectiveStatus === 'FAILED') return <XCircle className="h-4 w-4 text-destructive" />;
return <Play className="h-4 w-4" />;
};
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 (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted")}>
<Card className={cn("mt-2", effectiveStatus === 'FAILED' ? "border-destructive/50" : "border-muted")}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
@@ -41,12 +44,12 @@ export const BuildAction = memo(({ action, result, isError = false, isLoading =
<span className="font-mono text-sm font-medium">{actionConfig.title}</span>
</div>
<div className="flex items-center gap-2">
{isLoading ? (
{effectiveStatus === 'RUNNING' ? (
<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 ? (
) : effectiveStatus === 'FAILED' ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
@@ -69,7 +72,7 @@ export const BuildAction = memo(({ action, result, isError = false, isLoading =
{result && (
<div className={cn(
"p-3 rounded-md text-sm",
isError
effectiveStatus === 'FAILED'
? "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"
)}>
+14 -2
View File
@@ -17,6 +17,10 @@ export function ProjectView() {
const [project, setProject] = useState<Project | null>(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() {
<div className="flex-1 overflow-hidden">
{mobileView === 'chat' && (
<ChatPane projectId={project.id} projectName={project.name} />
<ChatPane
projectId={project.id}
projectName={project.name}
onBuildComplete={handleBuildComplete}
/>
)}
{(mobileView === 'preview' || mobileView === 'code') && (
<PreviewPane
@@ -221,7 +229,11 @@ export function ProjectView() {
{/* Chat Content */}
<div className="flex-1 overflow-hidden">
<ChatPane projectId={project.id} projectName={project.name} />
<ChatPane
projectId={project.id}
projectName={project.name}
onBuildComplete={handleBuildComplete}
/>
</div>
</div>
</ResizablePanel>
+33
View File
@@ -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;
}