more consolidation

This commit is contained in:
Chad Curtis committed 2025-08-20 11:55:39 +00:00
1 parent e117805487
commit 24e23e4a6e
4 files changed
+159 -283

No files matched your search

+54 -84
View File
@@ -25,14 +25,9 @@ interface ChatPaneProps {
projectName: string;
}
interface ValidationErrorIssue {
path: (string | number)[];
message: string;
}
interface ValidationError {
name: string;
issues?: ValidationErrorIssue[];
issues?: Array<{ path: (string | number)[]; message: string }>;
cause?: ValidationError;
}
@@ -100,18 +95,15 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
// Unified auto-fix handler to eliminate code duplication
// Unified auto-fix handler
const handleAutoFix = async (errorType: 'build' | 'api', error: unknown) => {
// Check if we've exceeded auto-fix attempts
if (autoFixAttemptsRef.current >= 3) {
console.log('Auto-fix attempt limit reached, stopping auto-fix');
const errorDetails = error instanceof Error ? error.message : 'Unknown error';
const limitMessage: AIMessage = {
addMessage({
id: generateId(),
role: 'assistant',
content: `⚠️ Auto-fix attempt limit reached. Please ${errorType === 'build' ? 'fix the build error' : 'try rephrasing your request'} manually: ${errorDetails}`,
};
addMessage(limitMessage);
});
setIsLoading(false);
return;
}
@@ -121,23 +113,24 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
const errorDetails = error instanceof Error ? error.message : 'Unknown error';
// Generate error-specific messages
let errorMessage: AIMessage;
let fixRequest: AIMessage;
if (errorType === 'build') {
const buildErrorContent = typeof error === 'object' && error !== null && 'toString' in error ? error.toString() : errorDetails;
errorMessage = {
const createFixMessages = (): [AIMessage, AIMessage] => {
const baseErrorMessage = {
id: generateId(),
role: 'assistant',
content: `❌ Auto-build failed. Analyzing error and attempting to fix automatically...`,
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...`,
};
fixRequest = {
id: generateId(),
role: 'user',
content: `The build failed with the following error. Please analyze this error and fix the issue:
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}
@@ -150,31 +143,26 @@ Common issues to check:
- Configuration issues (update config files)
Please fix this issue and ensure the project builds successfully.`,
};
} else {
};
return [baseErrorMessage, fixRequest];
}
const caughtError = error as ValidationError;
const errorCause = caughtError.cause;
let validationErrors = '';
if (caughtError.name === 'AI_TypeValidationError' || caughtError.name === 'ZodError') {
if (caughtError.issues && Array.isArray(caughtError.issues)) {
validationErrors = caughtError.issues
.map((issue: ValidationErrorIssue) => `- ${issue.path.join('.')}: ${issue.message}`)
.join('\n');
} else if (errorCause && errorCause.issues && Array.isArray(errorCause.issues)) {
validationErrors = errorCause.issues
.map((issue: ValidationErrorIssue) => `- ${issue.path.join('.')}: ${issue.message}`)
.join('\n');
}
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');
}
errorMessage = {
id: generateId(),
role: 'assistant',
content: `❌ AI response error detected. Analyzing and attempting to fix automatically...`,
};
fixRequest = {
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:
@@ -200,25 +188,25 @@ Please regenerate your response with the same intent but ensure it's properly fo
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;
const aiMessages: AIMessage[] = [...currentMessages, errorMessage, fixRequest];
await createAIChat(projectId, aiMessages);
await createAIChat(projectId, [...currentMessages, errorMessage, fixRequest]);
} catch (fixError) {
console.error('Failed to get AI to fix error:', fixError);
const fixErrorMessage: AIMessage = {
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}`,
};
addMessage(fixErrorMessage);
});
} finally {
setIsLoading(false);
}
@@ -382,52 +370,34 @@ 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...');
// Reset auto-fix attempts on successful completion
autoFixAttemptsRef.current = 0;
// 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;
}
if (isBuildLoading || isDeployLoading) {
addMessage({
id: generateId(),
role: 'assistant',
content: '⏸️ Build or deploy already in progress. Skipping auto-build.',
});
return;
}
try {
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);
// Signal to switch to preview tab
window.dispatchEvent(new CustomEvent('buildComplete', { detail: { projectId } }));
setShouldSwitchToPreview(true);
console.log('Signaled to switch to preview tab');
// Add success message
const successMessage: AIMessage = {
addMessage({
id: generateId(),
role: 'assistant',
content: '✅ Agent completed successfully. Project built! Switch to the "Preview" tab to see your changes.',
};
addMessage(successMessage);
});
} catch (error) {
console.error('Auto-build failed:', error);
await handleAutoFix('build', error);
}
}, 1000); // Small delay before starting auto-build
}, 1000);
}
},
tools: {
@@ -483,7 +453,7 @@ 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];
+53 -121
View File
@@ -8,116 +8,63 @@ 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. Project built and preview updated!';
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'
}
];
render(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
testCases.forEach(({ name, content, expectedTitle, expectedStatus }) => {
it(`should render ${name} action for string content`, () => {
render(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
expect(screen.getByText('Auto-Build Project')).toBeInTheDocument();
expect(screen.getByText('Success')).toBeInTheDocument();
});
expect(screen.getByText(expectedTitle)).toBeInTheDocument();
expect(screen.getByText(expectedStatus)).toBeInTheDocument();
});
it('should render build action for string content with build success message', () => {
const content = '✅ Agent completed successfully. Project built! Switch to the "Preview" tab to see your changes.';
it(`should render ${name} action for array content`, () => {
const arrayContent = [{ type: 'text' as const, text: content }];
render(
<TestApp>
<AssistantContent content={content} toolResults={mockToolResults} />
</TestApp>
);
render(
<TestApp>
<AssistantContent content={arrayContent} 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 = '✅ Agent completed successfully. Project built and preview updated!';
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. Project built and preview updated!' }
];
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();
expect(screen.getByText(expectedTitle)).toBeInTheDocument();
expect(screen.getByText(expectedStatus)).toBeInTheDocument();
});
});
it('should render regular markdown for non-build-action string content', () => {
@@ -130,22 +77,7 @@ describe('AssistantContent', () => {
);
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();
expect(screen.queryByText(/Project|Action/)).not.toBeInTheDocument();
});
it('should render tool calls for array content with tool-call items', () => {
+40 -40
View File
@@ -68,47 +68,47 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
// 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') || (fullText.includes('Agent completed successfully') && fullText.includes('built'))) {
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}
/>
);
if (!/(✅|❌|⏸️|🔄|🎉|⚠️|👀).*?(Agent completed successfully|Auto-building|Build|Deploy|Auto-fix|Building|Deploying|Fixing|Preview updated)/i.test(text)) {
return null;
}
return null;
const getActionType = (): 'build' | 'deploy' | 'auto-build' | 'auto-fix' => {
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';
}
if (text.includes('Deploy') || text.includes('Deploying')) {
return 'deploy';
}
return 'build';
};
const getStatus = () => {
const icon = text.match(/(✅|❌|⏸️|🔄|🎉|⚠️|👀)/)?.[1];
if (icon === '❌' || text.includes('failed')) {
return { isError: true, isLoading: false };
}
if (icon === '⏸️' || icon === '🔄' || /(Building|Deploying|Fixing)/i.test(text)) {
return { isError: false, isLoading: true };
}
return { isError: false, isLoading: false };
};
const actionType = getActionType();
const { isError, isLoading } = getStatus();
return (
<BuildAction
key={key}
action={actionType}
result={text}
isError={isError}
isLoading={isLoading}
/>
);
};
// Handle string content (simple text messages)
+12 -38
View File
@@ -12,50 +12,24 @@ interface BuildActionProps {
}
export const BuildAction = memo(({ action, result, isError = false, isLoading = false }: BuildActionProps) => {
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" />;
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...';
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`;
return `Starting ${actionConfig.verb} process...`;
};
return (
@@ -64,7 +38,7 @@ export const BuildAction = memo(({ action, result, isError = false, isLoading =
<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>
<span className="font-mono text-sm font-medium">{actionConfig.title}</span>
</div>
<div className="flex items-center gap-2">
{isLoading ? (