Skip to content

Updated error detection #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 0 additions & 25 deletions app/api/generate/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,12 @@ const extendedComponentSchema = componentSchema.extend({

export async function POST(request: NextRequest) {
try {
console.log('🚀 API route started');
const body = await request.json();

// Validate the request using extended schema
const validationResult = extendedComponentSchema.safeParse(body);

if (!validationResult.success) {
console.log('❌ Validation failed:', validationResult.error.format());
return NextResponse.json(
{ error: 'Invalid request format', details: validationResult.error.format() },
{ status: 400 }
Expand All @@ -38,25 +36,13 @@ export async function POST(request: NextRequest) {

const { description, existingFiles, editInstruction, useBuggyCode, useFixer } = validationResult.data;

console.log('✅ Validation passed, API Request:', {
isEdit: !!(existingFiles && editInstruction),
filesCount: existingFiles?.length || 0,
editInstruction: editInstruction || 'none',
description: description || 'none',
useBuggyCode,
useFixer
});

// Process the app request using centralized logic
const filesToSandbox = await processAppRequest(description, existingFiles, editInstruction, useBuggyCode);

console.log('📦 Files ready for sandbox:', filesToSandbox.length);

let repairedFiles = filesToSandbox;

// Repair the generated code using Benchify's API if requested
if (useFixer) {
console.log('🔧 Running Benchify fixer...');
try {
const { data } = await benchify.fixer.run({
files: filesToSandbox.map((file: { path: string; content: string }) => ({
Expand All @@ -69,31 +55,21 @@ export async function POST(request: NextRequest) {
const { success, diff } = data;

if (success && diff) {
console.log('✅ Fixer applied successfully');
repairedFiles = filesToSandbox.map((file: { path: string; content: string }) => {
const patchResult = applyPatch(file.content, diff);
return {
...file,
content: typeof patchResult === 'string' ? patchResult : file.content
};
});
} else {
console.log('⚠️ Fixer ran but no fixes were applied');
}
} else {
console.log('⚠️ Fixer returned no data');
}
} catch (error) {
console.error('❌ Error running fixer:', error);
// Continue with original files if fixer fails
}
} else {
console.log('⏭️ Skipping fixer as requested');
}

console.log('🏗️ Creating sandbox...');
const sandboxResult = await createSandbox({ files: repairedFiles });
console.log('✅ Sandbox created successfully');

// Return the results to the client
return NextResponse.json({
Expand All @@ -106,7 +82,6 @@ export async function POST(request: NextRequest) {
...(editInstruction && { editInstruction }),
});
} catch (error) {
console.error('💥 Error in API route:', error);
return NextResponse.json(
{
error: 'Failed to generate app',
Expand Down
56 changes: 51 additions & 5 deletions lib/e2b.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,13 @@ export async function createSandbox({ files }: { files: z.infer<typeof benchifyF

if (buildCheck.stdout && (
buildCheck.stdout.includes('Unterminated string constant') ||
buildCheck.stdout.includes('Unterminated string literal') ||
buildCheck.stdout.includes('SyntaxError') ||
buildCheck.stdout.includes('Unexpected token') ||
buildCheck.stdout.includes('[plugin:vite:')
buildCheck.stdout.includes('error TS') ||
buildCheck.stdout.includes('[plugin:vite:') ||
buildCheck.stdout.includes('Parse error') ||
buildCheck.stdout.includes('Parsing error')
)) {
hasCompilationError = true;
compilationErrorOutput = buildCheck.stdout;
Expand Down Expand Up @@ -208,10 +212,18 @@ export async function createSandbox({ files }: { files: z.infer<typeof benchifyF

if (errorOutput) {
console.log('Adding build error with message length:', errorOutput.length);
buildErrors.push({
type: 'build',
message: errorOutput
});

// Parse TypeScript errors for better display
const parsedErrors = parseTypeScriptErrors(errorOutput);
if (parsedErrors.length > 0) {
buildErrors.push(...parsedErrors);
} else {
// Fallback to raw error output
buildErrors.push({
type: 'build',
message: errorOutput
});
}
}
} else if (isPermissionError) {
console.log('⚠️ Permission errors detected but likely non-critical (E2B sandbox issue)');
Expand Down Expand Up @@ -241,6 +253,40 @@ export async function createSandbox({ files }: { files: z.infer<typeof benchifyF
};
}

function parseTypeScriptErrors(output: string): BuildError[] {
const errors: BuildError[] = [];

// Match TypeScript error format: file(line,col): error TSxxxx: message
const tsErrorRegex = /([^(]+)\((\d+),(\d+)\): error (TS\d+): (.+)/g;

let match;
while ((match = tsErrorRegex.exec(output)) !== null) {
const [, file, line, col, errorCode, message] = match;
errors.push({
type: 'typescript',
message: `${errorCode}: ${message}`,
file: file.trim(),
line: parseInt(line, 10),
column: parseInt(col, 10)
});
}

// If no specific TypeScript errors found, try to extract any line that looks like an error
if (errors.length === 0) {
const lines = output.split('\n');
for (const line of lines) {
if (line.includes('error') || line.includes('Error')) {
errors.push({
type: 'build',
message: line.trim()
});
}
}
}

return errors;
}

function extractNewPackages(packageJsonContent: string): string[] {
try {
const packageJson = JSON.parse(packageJsonContent);
Expand Down