Skip to content
Open
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
5 changes: 4 additions & 1 deletion app/api/analyze-edit-intent/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ export async function POST(request: NextRequest) {
aiModel = openai(model.replace('openai/', ''));
}
} else if (model.startsWith('google/')) {
aiModel = createGoogleGenerativeAI(model.replace('google/', ''));
const google = createGoogleGenerativeAI({
apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY,
});
aiModel = google(model.replace('google/', ''));
} else {
// Default to groq if model format is unclear
aiModel = groq(model);
Expand Down
30 changes: 17 additions & 13 deletions app/api/generate-ai-code-stream/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ export async function POST(request: NextRequest) {
if (manifest) {
await sendProgress({ type: 'status', message: '🔍 Creating search plan...' });

const fileContents = global.sandboxState.fileCache.files;
const fileContents = global.sandboxState.fileCache?.files || {};
console.log('[generate-ai-code-stream] Files available for search:', Object.keys(fileContents).length);

// STEP 1: Get search plan from AI
Expand Down Expand Up @@ -331,7 +331,7 @@ User request: "${prompt}"`;

// For now, fall back to keyword search since we don't have file contents for search execution
// This path happens when no manifest was initially available
let targetFiles = [];
let targetFiles: string[] = [];
if (!searchPlan || searchPlan.searchTerms.length === 0) {
console.warn('[generate-ai-code-stream] No target files after fetch, searching for relevant files');

Expand Down Expand Up @@ -953,15 +953,17 @@ CRITICAL: When files are provided in the context:
}

// Store files in cache
for (const [path, content] of Object.entries(filesData.files)) {
const normalizedPath = path.replace('/home/user/app/', '');
global.sandboxState.fileCache.files[normalizedPath] = {
content: content as string,
lastModified: Date.now()
};
if (global.sandboxState.fileCache) {
for (const [path, content] of Object.entries(filesData.files)) {
const normalizedPath = path.replace('/home/user/app/', '');
global.sandboxState.fileCache.files[normalizedPath] = {
content: content as string,
lastModified: Date.now()
};
}
}

if (filesData.manifest) {
if (filesData.manifest && global.sandboxState.fileCache) {
global.sandboxState.fileCache.manifest = filesData.manifest;

// Now try to analyze edit intent with the fetched manifest
Expand Down Expand Up @@ -993,7 +995,7 @@ CRITICAL: When files are provided in the context:
}

// Update variables
backendFiles = global.sandboxState.fileCache.files;
backendFiles = global.sandboxState.fileCache?.files || {};
hasBackendFiles = Object.keys(backendFiles).length > 0;
console.log('[generate-ai-code-stream] Updated backend cache with fetched files');
}
Expand Down Expand Up @@ -1594,17 +1596,19 @@ Provide the complete file content without any truncation. Include all necessary
completionClient = groq;
}

const cleanModelName = model.replace(/^(openai|anthropic|groq)\//, '');
const isGPT5 = cleanModelName.includes('gpt-5');

const completionResult = await streamText({
model: completionClient(modelMapping[model] || model),
model: completionClient(cleanModelName),
messages: [
{
role: 'system',
content: 'You are completing a truncated file. Provide the complete, working file content.'
},
{ role: 'user', content: completionPrompt }
],
temperature: isGPT5 ? undefined : appConfig.ai.defaultTemperature,
maxTokens: appConfig.ai.truncationRecoveryMaxTokens
temperature: isGPT5 ? undefined : appConfig.ai.defaultTemperature
});

// Get the full text from the stream
Expand Down
2 changes: 1 addition & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default function RootLayout({
}>) {
return (
<html lang="en">
<body className={inter.className}>
<body className={inter.className} suppressHydrationWarning={true}>
{children}
</body>
</html>
Expand Down
59 changes: 39 additions & 20 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { useState, useEffect, useRef } from 'react';
import { useState, useEffect, useRef, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { appConfig } from '@/config/app.config';
import { Button } from '@/components/ui/button';
Expand Down Expand Up @@ -42,20 +42,27 @@ interface ChatMessage {
};
}

export default function AISandboxPage() {
function AISandboxPageContent() {
const [isClient, setIsClient] = useState(false);
const [sandboxData, setSandboxData] = useState<SandboxData | null>(null);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState({ text: 'Not connected', active: false });
const [responseArea, setResponseArea] = useState<string[]>([]);
const [structureContent, setStructureContent] = useState('No sandbox created yet');
const [promptInput, setPromptInput] = useState('');
const [chatMessages, setChatMessages] = useState<ChatMessage[]>([
{
content: 'Welcome! I can help you generate code with full context of your sandbox files and structure. Just start chatting - I\'ll automatically create a sandbox for you if needed!\n\nTip: If you see package errors like "react-router-dom not found", just type "npm install" or "check packages" to automatically install missing packages.',
type: 'system',
timestamp: new Date()
}
]);
const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);

// Initialize client-side only data
useEffect(() => {
setIsClient(true);
setChatMessages([
{
content: 'Welcome! I can help you generate code with full context of your sandbox files and structure. Just start chatting - I\'ll automatically create a sandbox for you if needed!\n\nTip: If you see package errors like "react-router-dom not found", just type "npm install" or "check packages" to automatically install missing packages.',
type: 'system',
timestamp: new Date()
}
]);
}, []);
const [aiChatInput, setAiChatInput] = useState('');
const [aiEnabled] = useState(true);
const searchParams = useSearchParams();
Expand Down Expand Up @@ -119,7 +126,7 @@ export default function AISandboxPage() {
thinkingText?: string;
thinkingDuration?: number;
currentFile?: { path: string; content: string; type: string };
files: Array<{ path: string; content: string; type: string; completed: boolean }>;
files: Array<{ path: string; content: string; type: string; completed: boolean; edited?: boolean }>;
lastProcessedPosition: number;
isEdit?: boolean;
}>({
Expand Down Expand Up @@ -530,7 +537,7 @@ Tip: I automatically detect and install npm packages from your code imports (lik
} else if (data.message.includes('Creating files') || data.message.includes('Applying')) {
setCodeApplicationState({
stage: 'applying',
filesGenerated: results.filesCreated
filesGenerated: data.filesCreated || []
});
}
break;
Expand Down Expand Up @@ -620,13 +627,8 @@ Tip: I automatically detect and install npm packages from your code imports (lik

// Process final data
if (finalData && finalData.type === 'complete') {
const data = {
success: true,
results: finalData.results,
explanation: finalData.explanation,
structure: finalData.structure,
message: finalData.message
};
const data = finalData as any;
data.success = true;

if (data.success) {
const { results } = data;
Expand Down Expand Up @@ -2737,6 +2739,15 @@ Focus on the key sections and content, making it clean and modern.`;
}, 500);
};

// Prevent hydration mismatch by only rendering after client-side hydration
if (!isClient) {
return (
<div className="flex items-center justify-center h-screen">
<div className="w-8 h-8 border-2 border-gray-300 border-t-transparent rounded-full animate-spin" />
</div>
);
}

return (
<div className="font-sans bg-background text-foreground h-screen flex flex-col">
{/* Home Screen Overlay */}
Expand Down Expand Up @@ -2991,7 +3002,7 @@ Focus on the key sections and content, making it clean and modern.`;
>
{appConfig.ai.availableModels.map(model => (
<option key={model} value={model}>
{appConfig.ai.modelDisplayNames[model] || model}
{(appConfig.ai.modelDisplayNames as any)[model] || model}
</option>
))}
</select>
Expand Down Expand Up @@ -3027,7 +3038,7 @@ Focus on the key sections and content, making it clean and modern.`;
>
{appConfig.ai.availableModels.map(model => (
<option key={model} value={model}>
{appConfig.ai.modelDisplayNames[model] || model}
{(appConfig.ai.modelDisplayNames as any)[model] || model}
</option>
))}
</select>
Expand Down Expand Up @@ -3426,4 +3437,12 @@ Focus on the key sections and content, making it clean and modern.`;

</div>
);
}

export default function AISandboxPage() {
return (
<Suspense fallback={<div className="flex items-center justify-center h-screen">Loading...</div>}>
<AISandboxPageContent />
</Suspense>
);
}
Loading