update model name
Browse filesFiles changed (3)
13 unmodified lines141516171819202122231 unmodified line2526272829303132333435363712 unmodified lines5051525354555657585960613 unmodified lines656667686970717273747576777818 unmodified lines9798991001011021033 unmodified lines10710810911011111211311411511611711811916 unmodified lines13613713813914014114231 unmodified lines17417517617717817918025 unmodified lines2062072082092102112122132142152162172186 unmodified lines22522622722822923023123223323423523623723823924051 unmodified lines2922932942952962972982993003011 unmodified line3033043053063073083092 unmodified lines31231331431531631731831932032132232332432532632732832933033133233333435 unmodified lines3703713723733743753763 unmodified lines38038138238338438538635 unmodified lines4224234244254264274284294304314324334343 unmodified lines43843944044144244344427 unmodified lines4724734744754764774783 unmodified lines4824834844854864874881 unmodified line4904914924934944954964974984993 unmodified lines5035045055065075085091 unmodified line51151251351451551651711 unmodified lines52953053153253353453518 unmodified lines5545555565575585595605615625635645655665675685695705712 unmodified lines57457557657757857958023 unmodified lines6046056066076086096106 unmodified lines61761861962062162262318 unmodified lines6426436446456466476486496506516526536546556566576586596606612 unmodified lines6646656666676686696703 unmodified lines67467567667767867968010 unmodified lines6916926936946956966976986997007017027037047057067077087097107117127136 unmodified lines72072172272372472572672772872973073117 unmodified lines74975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877915 unmodified lines7957967977987998008018028038048058068078088098108118128138148158168178188198202 unmodified lines8238248258268278288298308318321 unmodified line83483583683783883984016 unmodified lines85785885986086186286337 unmodified lines90190290390490590690710 unmodified lines9189199209219229239249259269279288 unmodified lines9379389399409419429437 unmodified lines95195295395495595695712 unmodified lines9709719729739749759769779789799806 unmodified lines9879889899909919929936 unmodified lines1000100110021003100410051006100710081009101010111012101320 unmodified lines10341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107213 unmodified linesexport default function Home() {// Initialize messages as empty array (will load from localStorage in useEffect)const [messages, setMessages] = useState<Message[]>([]);const [generatedCode, setGeneratedCode] = useState('');const [selectedLanguage, setSelectedLanguage] = useState<Language>('html');const [selectedModel, setSelectedModel] = useState('zai-org/GLM-4.6V:zai-org');const [models, setModels] = useState<Model[]>([]);const [isGenerating, setIsGenerating] = useState(false);const [isAuthenticated, setIsAuthenticated] = useState(false);1 unmodified lineconst [username, setUsername] = useState<string | null>(null); // Track current userconst [pendingPR, setPendingPR] = useState<{ repoId: string; language: Language } | null>(null); // Track pending PR after redesignconst pendingPRRef = useRef<{ repoId: string; language: Language } | null>(null); // Ref for immediate access// Landing page state - show landing page if no messages existconst [showLandingPage, setShowLandingPage] = useState(true);// Mobile view state: 'chat', 'editor', or 'settings' - start on chat for mobileconst [mobileView, setMobileView] = useState<'chat' | 'editor' | 'settings'>('chat');// Resizable sidebar widths (in pixels)const [chatSidebarWidth, setChatSidebarWidth] = useState(320);const [settingsSidebarWidth, setSettingsSidebarWidth] = useState(288);12 unmodified linesconsole.log('[Cache] Clearing models and languages cache on app startup');localStorage.removeItem('anycoder_models');localStorage.removeItem('anycoder_languages');// Load models for checking image supportloadModels();}}, []); // Run once on mountconst loadModels = async () => {try {const modelsList = await apiClient.getModels();3 unmodified linesconsole.error('Failed to load models:', error);}};// Check if current model supports images// Show immediately for GLM-4.6V even before models loadconst currentModelSupportsImages =selectedModel === 'zai-org/GLM-4.6V:zai-org' ||models.find(m => m.id === selectedModel)?.supports_images ||false;// Debug log for image supportuseEffect(() => {console.log('[Image Support] Selected model:', selectedModel);18 unmodified linesconsole.error('[localStorage] Failed to parse saved messages:', e);}}// Load sidebar widths from localStorageconst savedChatWidth = localStorage.getItem('anycoder_chat_sidebar_width');const savedSettingsWidth = localStorage.getItem('anycoder_settings_sidebar_width');3 unmodified linesif (savedSettingsWidth) {setSettingsSidebarWidth(parseInt(savedSettingsWidth, 10));}// Check if desktop on mountconst checkDesktop = () => {setIsDesktop(window.innerWidth >= 768);};checkDesktop();// Listen for window resize to update desktop statuswindow.addEventListener('resize', checkDesktop);return () => window.removeEventListener('resize', checkDesktop);16 unmodified lines// Check auth on mount and handle OAuth callbackuseEffect(() => {checkAuth();// Check for OAuth callback in URL (handles ?session=token)// initializeOAuth already handles this, but we call checkAuth to sync stateconst urlParams = new URLSearchParams(window.location.search);31 unmodified linessetIsAuthenticated(false);setUsername(null);apiClient.setToken(null);// Show alert to userif (typeof window !== 'undefined') {alert(e.detail?.message || 'Your session has expired. Please sign in again.');25 unmodified linesconst checkAuth = async () => {const authenticated = checkIsAuthenticated();setIsAuthenticated(authenticated);// Make sure API client has the token or clears itif (authenticated) {const token = getStoredToken();if (token) {apiClient.setToken(token);// Get username from auth status (only if we don't have it yet and backend is available)// Skip if backend is known to be unavailable to avoid repeated failed requestsif (!username && !usernameFetchAttemptedRef.current && !backendUnavailableRef.current) {6 unmodified lines}} catch (error: any) {// Check if this is a connection errorconst isConnectionError =error.code === 'ECONNABORTED' ||error.code === 'ECONNRESET' ||error.code === 'ECONNREFUSED' ||error.message?.includes('socket hang up') ||error.message?.includes('timeout') ||error.message?.includes('Network Error') ||error.response?.status === 503 ||error.response?.status === 502;if (isConnectionError) {// Mark backend as unavailable to avoid repeated requestsbackendUnavailableRef.current = true;51 unmodified lines// If there's existing code, include it in the message context for modificationslet enhancedMessage = message;const hasRealCode = generatedCode &&generatedCode.length > 50 &&!generatedCode.includes('Your generated code will appear here');if (hasRealCode) {enhancedMessage = `I have existing code in the editor. Please modify it based on my request.\n\nCurrent code:\n\`\`\`${language}\n${generatedCode}\n\`\`\`\n\nMy request: ${message}`;}1 unmodified line// Add user message (show original message to user, but send enhanced to API)console.log('[handleSendMessage] Received imageUrl:', imageUrl ? 'Yes' : 'No');console.log('[handleSendMessage] Image URL length:', imageUrl?.length || 0);const userMessage: Message = {role: 'user',content: message,2 unmodified lines};setMessages((prev) => [...prev, userMessage]);setIsGenerating(true);// Clear previous code to show streaming from startsetGeneratedCode('');// Prepare request with enhanced query that includes current code// Use overrideRepoId if provided (from import/duplicate), otherwise use currentRepoId from stateconst effectiveRepoId = overrideRepoId || currentRepoId || undefined;console.log('[SendMessage] ========== GENERATION REQUEST ==========');console.log('[SendMessage] overrideRepoId:', overrideRepoId);console.log('[SendMessage] currentRepoId:', currentRepoId);console.log('[SendMessage] effectiveRepoId (will use):', effectiveRepoId);console.log('[SendMessage] ==========================================');console.log('[Request] Building request with imageUrl:', imageUrl ? 'Yes' : 'No');console.log('[Request] Image URL:', imageUrl?.substring(0, 50) + '...');const request: CodeGenerationRequest = {query: enhancedMessage,language: language,35 unmodified lines(code: string) => {setGeneratedCode(code);setIsGenerating(false);// Update final message - just show success, not the codesetMessages((prev) => {const newMessages = [...prev];3 unmodified lines};return newMessages;});// Check if we need to create a PR (redesign with PR option)console.log('[PR] onComplete - Checking pendingPR ref:', pendingPRRef.current);console.log('[PR] onComplete - Checking pendingPR state:', pendingPR);35 unmodified lines// onDeployed(message: string, spaceUrl: string) => {console.log('[Deploy] Deployment successful:', spaceUrl);// Extract repo_id from space URLconst match = spaceUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);if (match) {setCurrentRepoId(match[1]);}// Update message with deployment success - use backend message format for history trackingsetMessages((prev) => {const newMessages = [...prev];3 unmodified lines};return newMessages;});// Open the space URL in a new tabwindow.open(spaceUrl, '_blank');},27 unmodified linesconst createPullRequestAfterGeneration = async (repoId: string, code: string, language: Language) => {try {console.log('[PR] Creating PR on:', repoId);// Update message to show PR creation in progresssetMessages((prev) => {const newMessages = [...prev];3 unmodified lines};return newMessages;});const prResult = await apiClient.createPullRequest(repoId,code,1 unmodified line'🎨 Redesign from AnyCoder',undefined);if (prResult.success && prResult.pr_url) {console.log('[PR] Pull Request created:', prResult.pr_url);// Update message with PR linksetMessages((prev) => {const newMessages = [...prev];3 unmodified lines};return newMessages;});// Open PR in new tabwindow.open(prResult.pr_url, '_blank');} else {1 unmodified line}} catch (error: any) {console.error('[PR] Failed to create Pull Request:', error);// Update message with errorsetMessages((prev) => {const newMessages = [...prev];11 unmodified linesconsole.log('[Deploy] generatedCode exists?', !!generatedCode);console.log('[Deploy] generatedCode length:', generatedCode?.length);console.log('[Deploy] generatedCode preview:', generatedCode?.substring(0, 200));if (!generatedCode) {alert('No code to publish! Generate some code first.');return;18 unmodified lines// SAME LOGIC AS GRADIO VERSION: Parse message history to find existing spacelet existingSpace: string | null = null;// Look for previous deployment or imported space in historyconsole.log('[Deploy] ========== DEBUG START ==========');console.log('[Deploy] Total messages in history:', messages.length);console.log('[Deploy] Current username:', currentUsername);console.log('[Deploy] Auth status:', isAuthenticated ? 'authenticated' : 'not authenticated');console.log('[Deploy] Messages:', JSON.stringify(messages, null, 2));if (messages.length > 0 && currentUsername) {console.log('[Deploy] Scanning message history FORWARD (oldest first) - MATCHING GRADIO LOGIC...');console.log('[Deploy] Total messages to scan:', messages.length);// EXACT GRADIO LOGIC: Scan forward (oldest first) and stop at first match// Gradio: for user_msg, assistant_msg in history:for (let i = 0; i < messages.length; i++) {2 unmodified linesrole: msg.role,contentPreview: msg.content.substring(0, 100)});// Check assistant messages for deployment confirmationsif (msg.role === 'assistant') {// Check for "✅ Deployed!" message23 unmodified linesconst importedSpace = match[1];console.log('[Deploy] Extracted imported space:', importedSpace);console.log('[Deploy] Checking ownership - user:', currentUsername, 'space:', importedSpace);// Only use if user owns it (EXACT GRADIO LOGIC)if (importedSpace.startsWith(`${currentUsername}/`)) {existingSpace = importedSpace;6 unmodified lines}}}console.log('[Deploy] Final existingSpace value:', existingSpace);} else {console.log('[Deploy] Skipping scan - no messages or no username');18 unmodified linesconsole.log('[Deploy] Will create new space?', !existingSpace);console.log('[Deploy] Messages count:', messages.length);console.log('[Deploy] Messages (first 3):', messages.slice(0, 3).map(m => ({ role: m.role, content: m.content.substring(0, 100) })));// CRITICAL DEBUG: Check what we're actually sendingconst historyToSend = messages.map(msg => ({ role: msg.role, content: msg.content }));console.log('[Deploy] History to send (length):', historyToSend.length);console.log('[Deploy] History to send (first 2):', historyToSend.slice(0, 2));console.log('[Deploy] =================================================================');// Build deploy request, omitting undefined fieldsconst deployRequest: any = {code: generatedCode,language: selectedLanguage,history: historyToSend // Use the variable we just logged};// Only include optional fields if they have valuesif (spaceName) {deployRequest.space_name = spaceName;2 unmodified linesdeployRequest.existing_repo_id = existingSpace;deployRequest.commit_message = 'Update via AnyCoder';}console.log('[Deploy] 🚀 Sending to backend:', {existing_repo_id: deployRequest.existing_repo_id,space_name: deployRequest.space_name,3 unmodified lineshistory_length: deployRequest.history?.length});console.log('[Deploy] Full request object:', JSON.stringify(deployRequest, null, 2).substring(0, 500));const response = await apiClient.deploy(deployRequest);console.log('[Deploy] ✅ Response received:', response);10 unmodified linessetCurrentRepoId(match[1]);}}// Add deployment message to chat (EXACT format backend expects)const deployMessage: Message = {role: 'assistant',content: existingSpace? `✅ Updated! View your space at: ${response.space_url}`: `✅ Deployed! View your space at: ${response.space_url}`,timestamp: new Date().toISOString(),};setMessages((prev) => [...prev, deployMessage]);// Open the space URL in a new tabwindow.open(response.space_url, '_blank');// Show success messageconst isDev = response.dev_mode;const message = isDev? '🚀 Opening HuggingFace Spaces creation page...\nPlease complete the space setup in the new tab.': existingSpace? `✅ Updated successfully!\n\nOpening: ${response.space_url}`6 unmodified linesconsole.error('[Deploy] Full error object:', error);console.error('[Deploy] Error response:', error.response);console.error('[Deploy] Error data:', error.response?.data);const errorMessage = error.response?.data?.detail|| error.response?.data?.message|| error.message|| 'Unknown error';alert(`Deployment error: ${errorMessage}\n\nCheck console for details.`);}};17 unmodified linesconsole.log('[Import] Import URL:', importUrl);console.log('[Import] Current username:', username);console.log('[Import] Current repo before import:', currentRepoId);// Hide landing page when importingif (showLandingPage) {setShowLandingPage(false);}setGeneratedCode(code);setSelectedLanguage(language);// Extract repo_id from import URL if providedif (importUrl) {const spaceMatch = importUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);console.log('[Import] Regex match result:', spaceMatch);if (spaceMatch) {const importedRepoId = spaceMatch[1];const importedUsername = importedRepoId.split('/')[0];console.log('[Import] ========================================');console.log('[Import] Extracted repo_id:', importedRepoId);console.log('[Import] Imported username:', importedUsername);console.log('[Import] Logged-in username:', username);console.log('[Import] Ownership check:', importedUsername === username);console.log('[Import] ========================================');// Only set as current repo if user owns itif (username && importedRepoId.startsWith(`${username}/`)) {console.log('[Import] ✅✅✅ BEFORE setCurrentRepoId - currentRepoId was:', currentRepoId);15 unmodified lines} else {console.log('[Import] No import URL provided');}console.log('[Import] ========== IMPORT END ==========');// Add messages that include the imported code so LLM can see itconst userMessage: Message = {role: 'user',content: importUrl? `Imported Space from ${importUrl}`: `I imported a ${language} project. Here's the code that was imported.`,timestamp: new Date().toISOString(),};const assistantMessage: Message = {role: 'assistant',content: `✅ I've loaded your ${language} project. The code is now in the editor. You can ask me to:\n\n• Modify existing features\n• Add new functionality\n• Fix bugs or improve code\n• Explain how it works\n• Publish it to HuggingFace Spaces\n\nWhat would you like me to help you with?`,timestamp: new Date().toISOString(),};setMessages((prev) => [...prev, userMessage, assistantMessage]);// Switch to editor view on mobilesetMobileView('editor');};2 unmodified linesconst handleLandingPageStart = async (prompt: string, language: Language, modelId: string, imageUrl?: string, repoId?: string, shouldCreatePR?: boolean) => {console.log('[LandingPageStart] Received imageUrl:', imageUrl ? 'Yes' : 'No');console.log('[LandingPageStart] Image URL length:', imageUrl?.length || 0);// Hide landing page immediately for smooth transitionsetShowLandingPage(false);// If shouldCreatePR is true, set pending PR state and refif (shouldCreatePR && repoId) {console.log('[PR] Setting pending PR for:', repoId);1 unmodified linesetPendingPR(prInfo);pendingPRRef.current = prInfo; // Set ref immediately for synchronous access}// Send the message with the selected language, model, and image// Don't pass repoId to handleSendMessage when creating PR (we want to generate code first, then create PR)await handleSendMessage(prompt, imageUrl, language, modelId, shouldCreatePR ? undefined : repoId, shouldCreatePR);16 unmodified linesuseEffect(() => {const handleMouseMove = (e: MouseEvent) => {if (!isDesktop) return; // Skip on mobileif (isResizingChat) {const newWidth = Math.min(Math.max(e.clientX, 250), 600); // Min 250px, max 600pxsetChatSidebarWidth(newWidth);37 unmodified linesif (showLandingPage && messages.length === 0) {return (<div className="min-h-screen animate-in fade-in duration-300"><LandingPageonStart={handleLandingPageStart}onImport={handleImport}isAuthenticated={isAuthenticated}10 unmodified linesreturn (<div className="h-screen flex flex-col bg-[#000000] animate-in fade-in duration-300"><Header />{/* Apple-style layout - Responsive */}<main className="flex-1 flex overflow-hidden relative">{/* Left Sidebar - Chat Panel (Hidden on mobile, shown when mobileView='chat') */}<divclassName={`${mobileView === 'chat' ? 'flex' : 'hidden'} md:flexw-full8 unmodified lines<div className="flex items-center px-4 py-3 bg-[#000000] border-b border-[#424245]/30"><span className="text-sm font-medium text-[#f5f5f7]">Chat</span></div>{/* Chat Panel */}<div className="flex-1 overflow-hidden"><ChatInterface7 unmodified lines</div>{/* Resize Handle for Chat Sidebar (Desktop only) */}<divclassName={`hidden md:block resize-handle ${isResizingChat ? 'resizing' : ''}`}onMouseDown={startResizingChat}title="Drag to resize chat panel"12 unmodified lines<div className="flex items-center space-x-2"><div className="px-3 py-1 bg-[#2d2d2f] text-sm text-[#f5f5f7] rounded-t-lg font-normal border-t border-x border-[#424245]/50">{selectedLanguage === 'html' ? 'app.html' :selectedLanguage === 'gradio' || selectedLanguage === 'streamlit' ? 'app.py' :selectedLanguage === 'transformers.js' ? 'app.js' :selectedLanguage === 'comfyui' ? 'app.json' :selectedLanguage === 'react' ? 'app.jsx' :`${selectedLanguage}.txt`}</div></div><div className="ml-auto flex items-center space-x-3 text-xs text-[#86868b]">6 unmodified lines<span className="font-medium">{selectedLanguage.toUpperCase()}</span></div></div>{/* Editor */}<div className="flex-1"><CodeEditor6 unmodified lines</div>{/* Resize Handle for Settings Sidebar (Desktop only) */}<divclassName={`hidden md:block resize-handle ${isResizingSettings ? 'resizing' : ''}`}onMouseDown={startResizingSettings}title="Drag to resize settings panel"/>{/* Right Sidebar - Configuration Panel (Hidden on mobile, shown when mobileView='settings') */}<divclassName={`${mobileView === 'settings' ? 'flex' : 'hidden'} md:flexw-full20 unmodified lines<nav className="md:hidden bg-[#000000]/95 backdrop-blur-xl border-t border-[#424245]/20 flex items-center justify-around h-14 px-2 safe-area-bottom"><buttononClick={() => setMobileView('chat')}className={`flex flex-col items-center justify-center flex-1 py-1.5 transition-all ${mobileView === 'chat'? 'text-white': 'text-[#86868b]'}`}><svg className="w-5 h-5 mb-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" /></svg><span className="text-[10px]">Chat</span></button><buttononClick={() => setMobileView('editor')}className={`flex flex-col items-center justify-center flex-1 py-1.5 transition-all ${mobileView === 'editor'? 'text-white': 'text-[#86868b]'}`}><svg className="w-5 h-5 mb-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" /></svg><span className="text-[10px]">Code</span></button><buttononClick={() => setMobileView('settings')}className={`flex flex-col items-center justify-center flex-1 py-1.5 transition-all ${mobileView === 'settings'? 'text-white': 'text-[#86868b]'}`}><svg className="w-5 h-5 mb-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />13 unmodified lines141516171819202122231 unmodified line2526272829303132333435363712 unmodified lines5051525354555657585960613 unmodified lines656667686970717273747576777818 unmodified lines9798991001011021033 unmodified lines10710810911011111211311411511611711811916 unmodified lines13613713813914014114231 unmodified lines17417517617717817918025 unmodified lines2062072082092102112122132142152162172186 unmodified lines22522622722822923023123223323423523623723823924051 unmodified lines2922932942952962972982993003011 unmodified line3033043053063073083092 unmodified lines31231331431531631731831932032132232332432532632732832933033133233333435 unmodified lines3703713723733743753763 unmodified lines38038138238338438538635 unmodified lines4224234244254264274284294304314324334343 unmodified lines43843944044144244344427 unmodified lines4724734744754764774783 unmodified lines4824834844854864874881 unmodified line4904914924934944954964974984993 unmodified lines5035045055065075085091 unmodified line51151251351451551651711 unmodified lines52953053153253353453518 unmodified lines5545555565575585595605615625635645655665675685695705712 unmodified lines57457557657757857958023 unmodified lines6046056066076086096106 unmodified lines61761861962062162262318 unmodified lines6426436446456466476486496506516526536546556566576586596606612 unmodified lines6646656666676686696703 unmodified lines67467567667767867968010 unmodified lines6916926936946956966976986997007017027037047057067077087097107117127136 unmodified lines72072172272372472572672772872973073117 unmodified lines74975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877915 unmodified lines7957967977987998008018028038048058068078088098108118128138148158168178188198202 unmodified lines8238248258268278288298308318321 unmodified line83483583683783883984016 unmodified lines85785885986086186286337 unmodified lines90190290390490590690710 unmodified lines9189199209219229239249259269279288 unmodified lines9379389399409419429437 unmodified lines95195295395495595695712 unmodified lines9709719729739749759769779789799806 unmodified lines9879889899909919929936 unmodified lines1000100110021003100410051006100710081009101010111012101320 unmodified lines10341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106913 unmodified linesexport default function Home() {// Initialize messages as empty array (will load from localStorage in useEffect)const [messages, setMessages] = useState<Message[]>([]);const [generatedCode, setGeneratedCode] = useState('');const [selectedLanguage, setSelectedLanguage] = useState<Language>('html');const [selectedModel, setSelectedModel] = useState('devstral-medium-2512');const [models, setModels] = useState<Model[]>([]);const [isGenerating, setIsGenerating] = useState(false);const [isAuthenticated, setIsAuthenticated] = useState(false);1 unmodified lineconst [username, setUsername] = useState<string | null>(null); // Track current userconst [pendingPR, setPendingPR] = useState<{ repoId: string; language: Language } | null>(null); // Track pending PR after redesignconst pendingPRRef = useRef<{ repoId: string; language: Language } | null>(null); // Ref for immediate access// Landing page state - show landing page if no messages existconst [showLandingPage, setShowLandingPage] = useState(true);// Mobile view state: 'chat', 'editor', or 'settings' - start on chat for mobileconst [mobileView, setMobileView] = useState<'chat' | 'editor' | 'settings'>('chat');// Resizable sidebar widths (in pixels)const [chatSidebarWidth, setChatSidebarWidth] = useState(320);const [settingsSidebarWidth, setSettingsSidebarWidth] = useState(288);12 unmodified linesconsole.log('[Cache] Clearing models and languages cache on app startup');localStorage.removeItem('anycoder_models');localStorage.removeItem('anycoder_languages');// Load models for checking image supportloadModels();}}, []); // Run once on mountconst loadModels = async () => {try {const modelsList = await apiClient.getModels();3 unmodified linesconsole.error('Failed to load models:', error);}};// Check if current model supports images// Show immediately for GLM-4.6V even before models loadconst currentModelSupportsImages =selectedModel === 'zai-org/GLM-4.6V:zai-org' ||models.find(m => m.id === selectedModel)?.supports_images ||false;// Debug log for image supportuseEffect(() => {console.log('[Image Support] Selected model:', selectedModel);18 unmodified linesconsole.error('[localStorage] Failed to parse saved messages:', e);}}// Load sidebar widths from localStorageconst savedChatWidth = localStorage.getItem('anycoder_chat_sidebar_width');const savedSettingsWidth = localStorage.getItem('anycoder_settings_sidebar_width');3 unmodified linesif (savedSettingsWidth) {setSettingsSidebarWidth(parseInt(savedSettingsWidth, 10));}// Check if desktop on mountconst checkDesktop = () => {setIsDesktop(window.innerWidth >= 768);};checkDesktop();// Listen for window resize to update desktop statuswindow.addEventListener('resize', checkDesktop);return () => window.removeEventListener('resize', checkDesktop);16 unmodified lines// Check auth on mount and handle OAuth callbackuseEffect(() => {checkAuth();// Check for OAuth callback in URL (handles ?session=token)// initializeOAuth already handles this, but we call checkAuth to sync stateconst urlParams = new URLSearchParams(window.location.search);31 unmodified linessetIsAuthenticated(false);setUsername(null);apiClient.setToken(null);// Show alert to userif (typeof window !== 'undefined') {alert(e.detail?.message || 'Your session has expired. Please sign in again.');25 unmodified linesconst checkAuth = async () => {const authenticated = checkIsAuthenticated();setIsAuthenticated(authenticated);// Make sure API client has the token or clears itif (authenticated) {const token = getStoredToken();if (token) {apiClient.setToken(token);// Get username from auth status (only if we don't have it yet and backend is available)// Skip if backend is known to be unavailable to avoid repeated failed requestsif (!username && !usernameFetchAttemptedRef.current && !backendUnavailableRef.current) {6 unmodified lines}} catch (error: any) {// Check if this is a connection errorconst isConnectionError =error.code === 'ECONNABORTED' ||error.code === 'ECONNRESET' ||error.code === 'ECONNREFUSED' ||error.message?.includes('socket hang up') ||error.message?.includes('timeout') ||error.message?.includes('Network Error') ||error.response?.status === 503 ||error.response?.status === 502;if (isConnectionError) {// Mark backend as unavailable to avoid repeated requestsbackendUnavailableRef.current = true;51 unmodified lines// If there's existing code, include it in the message context for modificationslet enhancedMessage = message;const hasRealCode = generatedCode &&generatedCode.length > 50 &&!generatedCode.includes('Your generated code will appear here');if (hasRealCode) {enhancedMessage = `I have existing code in the editor. Please modify it based on my request.\n\nCurrent code:\n\`\`\`${language}\n${generatedCode}\n\`\`\`\n\nMy request: ${message}`;}1 unmodified line// Add user message (show original message to user, but send enhanced to API)console.log('[handleSendMessage] Received imageUrl:', imageUrl ? 'Yes' : 'No');console.log('[handleSendMessage] Image URL length:', imageUrl?.length || 0);const userMessage: Message = {role: 'user',content: message,2 unmodified lines};setMessages((prev) => [...prev, userMessage]);setIsGenerating(true);// Clear previous code to show streaming from startsetGeneratedCode('');// Prepare request with enhanced query that includes current code// Use overrideRepoId if provided (from import/duplicate), otherwise use currentRepoId from stateconst effectiveRepoId = overrideRepoId || currentRepoId || undefined;console.log('[SendMessage] ========== GENERATION REQUEST ==========');console.log('[SendMessage] overrideRepoId:', overrideRepoId);console.log('[SendMessage] currentRepoId:', currentRepoId);console.log('[SendMessage] effectiveRepoId (will use):', effectiveRepoId);console.log('[SendMessage] ==========================================');console.log('[Request] Building request with imageUrl:', imageUrl ? 'Yes' : 'No');console.log('[Request] Image URL:', imageUrl?.substring(0, 50) + '...');const request: CodeGenerationRequest = {query: enhancedMessage,language: language,35 unmodified lines(code: string) => {setGeneratedCode(code);setIsGenerating(false);// Update final message - just show success, not the codesetMessages((prev) => {const newMessages = [...prev];3 unmodified lines};return newMessages;});// Check if we need to create a PR (redesign with PR option)console.log('[PR] onComplete - Checking pendingPR ref:', pendingPRRef.current);console.log('[PR] onComplete - Checking pendingPR state:', pendingPR);35 unmodified lines// onDeployed(message: string, spaceUrl: string) => {console.log('[Deploy] Deployment successful:', spaceUrl);// Extract repo_id from space URLconst match = spaceUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);if (match) {setCurrentRepoId(match[1]);}// Update message with deployment success - use backend message format for history trackingsetMessages((prev) => {const newMessages = [...prev];3 unmodified lines};return newMessages;});// Open the space URL in a new tabwindow.open(spaceUrl, '_blank');},27 unmodified linesconst createPullRequestAfterGeneration = async (repoId: string, code: string, language: Language) => {try {console.log('[PR] Creating PR on:', repoId);// Update message to show PR creation in progresssetMessages((prev) => {const newMessages = [...prev];3 unmodified lines};return newMessages;});const prResult = await apiClient.createPullRequest(repoId,code,1 unmodified line'🎨 Redesign from AnyCoder',undefined);if (prResult.success && prResult.pr_url) {console.log('[PR] Pull Request created:', prResult.pr_url);// Update message with PR linksetMessages((prev) => {const newMessages = [...prev];3 unmodified lines};return newMessages;});// Open PR in new tabwindow.open(prResult.pr_url, '_blank');} else {1 unmodified line}} catch (error: any) {console.error('[PR] Failed to create Pull Request:', error);// Update message with errorsetMessages((prev) => {const newMessages = [...prev];11 unmodified linesconsole.log('[Deploy] generatedCode exists?', !!generatedCode);console.log('[Deploy] generatedCode length:', generatedCode?.length);console.log('[Deploy] generatedCode preview:', generatedCode?.substring(0, 200));if (!generatedCode) {alert('No code to publish! Generate some code first.');return;18 unmodified lines// SAME LOGIC AS GRADIO VERSION: Parse message history to find existing spacelet existingSpace: string | null = null;// Look for previous deployment or imported space in historyconsole.log('[Deploy] ========== DEBUG START ==========');console.log('[Deploy] Total messages in history:', messages.length);console.log('[Deploy] Current username:', currentUsername);console.log('[Deploy] Auth status:', isAuthenticated ? 'authenticated' : 'not authenticated');console.log('[Deploy] Messages:', JSON.stringify(messages, null, 2));if (messages.length > 0 && currentUsername) {console.log('[Deploy] Scanning message history FORWARD (oldest first) - MATCHING GRADIO LOGIC...');console.log('[Deploy] Total messages to scan:', messages.length);// EXACT GRADIO LOGIC: Scan forward (oldest first) and stop at first match// Gradio: for user_msg, assistant_msg in history:for (let i = 0; i < messages.length; i++) {2 unmodified linesrole: msg.role,contentPreview: msg.content.substring(0, 100)});// Check assistant messages for deployment confirmationsif (msg.role === 'assistant') {// Check for "✅ Deployed!" message23 unmodified linesconst importedSpace = match[1];console.log('[Deploy] Extracted imported space:', importedSpace);console.log('[Deploy] Checking ownership - user:', currentUsername, 'space:', importedSpace);// Only use if user owns it (EXACT GRADIO LOGIC)if (importedSpace.startsWith(`${currentUsername}/`)) {existingSpace = importedSpace;6 unmodified lines}}}console.log('[Deploy] Final existingSpace value:', existingSpace);} else {console.log('[Deploy] Skipping scan - no messages or no username');18 unmodified linesconsole.log('[Deploy] Will create new space?', !existingSpace);console.log('[Deploy] Messages count:', messages.length);console.log('[Deploy] Messages (first 3):', messages.slice(0, 3).map(m => ({ role: m.role, content: m.content.substring(0, 100) })));// CRITICAL DEBUG: Check what we're actually sendingconst historyToSend = messages.map(msg => ({ role: msg.role, content: msg.content }));console.log('[Deploy] History to send (length):', historyToSend.length);console.log('[Deploy] History to send (first 2):', historyToSend.slice(0, 2));console.log('[Deploy] =================================================================');// Build deploy request, omitting undefined fieldsconst deployRequest: any = {code: generatedCode,language: selectedLanguage,history: historyToSend // Use the variable we just logged};// Only include optional fields if they have valuesif (spaceName) {deployRequest.space_name = spaceName;2 unmodified linesdeployRequest.existing_repo_id = existingSpace;deployRequest.commit_message = 'Update via AnyCoder';}console.log('[Deploy] 🚀 Sending to backend:', {existing_repo_id: deployRequest.existing_repo_id,space_name: deployRequest.space_name,3 unmodified lineshistory_length: deployRequest.history?.length});console.log('[Deploy] Full request object:', JSON.stringify(deployRequest, null, 2).substring(0, 500));const response = await apiClient.deploy(deployRequest);console.log('[Deploy] ✅ Response received:', response);10 unmodified linessetCurrentRepoId(match[1]);}}// Add deployment message to chat (EXACT format backend expects)const deployMessage: Message = {role: 'assistant',content: existingSpace? `✅ Updated! View your space at: ${response.space_url}`: `✅ Deployed! View your space at: ${response.space_url}`,timestamp: new Date().toISOString(),};setMessages((prev) => [...prev, deployMessage]);// Open the space URL in a new tabwindow.open(response.space_url, '_blank');// Show success messageconst isDev = response.dev_mode;const message = isDev? '🚀 Opening HuggingFace Spaces creation page...\nPlease complete the space setup in the new tab.': existingSpace? `✅ Updated successfully!\n\nOpening: ${response.space_url}`6 unmodified linesconsole.error('[Deploy] Full error object:', error);console.error('[Deploy] Error response:', error.response);console.error('[Deploy] Error data:', error.response?.data);const errorMessage = error.response?.data?.detail|| error.response?.data?.message|| error.message|| 'Unknown error';alert(`Deployment error: ${errorMessage}\n\nCheck console for details.`);}};17 unmodified linesconsole.log('[Import] Import URL:', importUrl);console.log('[Import] Current username:', username);console.log('[Import] Current repo before import:', currentRepoId);// Hide landing page when importingif (showLandingPage) {setShowLandingPage(false);}setGeneratedCode(code);setSelectedLanguage(language);// Extract repo_id from import URL if providedif (importUrl) {const spaceMatch = importUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);console.log('[Import] Regex match result:', spaceMatch);if (spaceMatch) {const importedRepoId = spaceMatch[1];const importedUsername = importedRepoId.split('/')[0];console.log('[Import] ========================================');console.log('[Import] Extracted repo_id:', importedRepoId);console.log('[Import] Imported username:', importedUsername);console.log('[Import] Logged-in username:', username);console.log('[Import] Ownership check:', importedUsername === username);console.log('[Import] ========================================');// Only set as current repo if user owns itif (username && importedRepoId.startsWith(`${username}/`)) {console.log('[Import] ✅✅✅ BEFORE setCurrentRepoId - currentRepoId was:', currentRepoId);15 unmodified lines} else {console.log('[Import] No import URL provided');}console.log('[Import] ========== IMPORT END ==========');// Add messages that include the imported code so LLM can see itconst userMessage: Message = {role: 'user',content: importUrl? `Imported Space from ${importUrl}`: `I imported a ${language} project. Here's the code that was imported.`,timestamp: new Date().toISOString(),};const assistantMessage: Message = {role: 'assistant',content: `✅ I've loaded your ${language} project. The code is now in the editor. You can ask me to:\n\n• Modify existing features\n• Add new functionality\n• Fix bugs or improve code\n• Explain how it works\n• Publish it to HuggingFace Spaces\n\nWhat would you like me to help you with?`,timestamp: new Date().toISOString(),};setMessages((prev) => [...prev, userMessage, assistantMessage]);// Switch to editor view on mobilesetMobileView('editor');};2 unmodified linesconst handleLandingPageStart = async (prompt: string, language: Language, modelId: string, imageUrl?: string, repoId?: string, shouldCreatePR?: boolean) => {console.log('[LandingPageStart] Received imageUrl:', imageUrl ? 'Yes' : 'No');console.log('[LandingPageStart] Image URL length:', imageUrl?.length || 0);// Hide landing page immediately for smooth transitionsetShowLandingPage(false);// If shouldCreatePR is true, set pending PR state and refif (shouldCreatePR && repoId) {console.log('[PR] Setting pending PR for:', repoId);1 unmodified linesetPendingPR(prInfo);pendingPRRef.current = prInfo; // Set ref immediately for synchronous access}// Send the message with the selected language, model, and image// Don't pass repoId to handleSendMessage when creating PR (we want to generate code first, then create PR)await handleSendMessage(prompt, imageUrl, language, modelId, shouldCreatePR ? undefined : repoId, shouldCreatePR);16 unmodified linesuseEffect(() => {const handleMouseMove = (e: MouseEvent) => {if (!isDesktop) return; // Skip on mobileif (isResizingChat) {const newWidth = Math.min(Math.max(e.clientX, 250), 600); // Min 250px, max 600pxsetChatSidebarWidth(newWidth);37 unmodified linesif (showLandingPage && messages.length === 0) {return (<div className="min-h-screen animate-in fade-in duration-300"><LandingPageonStart={handleLandingPageStart}onImport={handleImport}isAuthenticated={isAuthenticated}10 unmodified linesreturn (<div className="h-screen flex flex-col bg-[#000000] animate-in fade-in duration-300"><Header />{/* Apple-style layout - Responsive */}<main className="flex-1 flex overflow-hidden relative">{/* Left Sidebar - Chat Panel (Hidden on mobile, shown when mobileView='chat') */}<divclassName={`${mobileView === 'chat' ? 'flex' : 'hidden'} md:flexw-full8 unmodified lines<div className="flex items-center px-4 py-3 bg-[#000000] border-b border-[#424245]/30"><span className="text-sm font-medium text-[#f5f5f7]">Chat</span></div>{/* Chat Panel */}<div className="flex-1 overflow-hidden"><ChatInterface7 unmodified lines</div>{/* Resize Handle for Chat Sidebar (Desktop only) */}<divclassName={`hidden md:block resize-handle ${isResizingChat ? 'resizing' : ''}`}onMouseDown={startResizingChat}title="Drag to resize chat panel"12 unmodified lines<div className="flex items-center space-x-2"><div className="px-3 py-1 bg-[#2d2d2f] text-sm text-[#f5f5f7] rounded-t-lg font-normal border-t border-x border-[#424245]/50">{selectedLanguage === 'html' ? 'app.html' :selectedLanguage === 'gradio' || selectedLanguage === 'streamlit' ? 'app.py' :selectedLanguage === 'transformers.js' ? 'app.js' :selectedLanguage === 'comfyui' ? 'app.json' :selectedLanguage === 'react' ? 'app.jsx' :`${selectedLanguage}.txt`}</div></div><div className="ml-auto flex items-center space-x-3 text-xs text-[#86868b]">6 unmodified lines<span className="font-medium">{selectedLanguage.toUpperCase()}</span></div></div>{/* Editor */}<div className="flex-1"><CodeEditor6 unmodified lines</div>{/* Resize Handle for Settings Sidebar (Desktop only) */}<divclassName={`hidden md:block resize-handle ${isResizingSettings ? 'resizing' : ''}`}onMouseDown={startResizingSettings}title="Drag to resize settings panel"/>{/* Right Sidebar - Configuration Panel (Hidden on mobile, shown when mobileView='settings') */}<divclassName={`${mobileView === 'settings' ? 'flex' : 'hidden'} md:flexw-full20 unmodified lines<nav className="md:hidden bg-[#000000]/95 backdrop-blur-xl border-t border-[#424245]/20 flex items-center justify-around h-14 px-2 safe-area-bottom"><buttononClick={() => setMobileView('chat')}className={`flex flex-col items-center justify-center flex-1 py-1.5 transition-all ${mobileView === 'chat'? 'text-white': 'text-[#86868b]'}`}><svg className="w-5 h-5 mb-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" /></svg><span className="text-[10px]">Chat</span></button><buttononClick={() => setMobileView('editor')}className={`flex flex-col items-center justify-center flex-1 py-1.5 transition-all ${mobileView === 'editor'? 'text-white': 'text-[#86868b]'}`}><svg className="w-5 h-5 mb-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" /></svg><span className="text-[10px]">Code</span></button><buttononClick={() => setMobileView('settings')}className={`flex flex-col items-center justify-center flex-1 py-1.5 transition-all ${mobileView === 'settings'? 'text-white': 'text-[#86868b]'}`}><svg className="w-5 h-5 mb-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
23 unmodified lines2425262728293062 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823 unmodified linesconst [models, setModels] = useState<Model[]>([]);const [languages, setLanguages] = useState<Language[]>([]);const [isLoading, setIsLoading] = useState(true);// Dropdown statesconst [showLanguageDropdown, setShowLanguageDropdown] = useState(false);const [showModelDropdown, setShowModelDropdown] = useState(false);62 unmodified lines<div className="flex items-center px-4 py-3 border-b border-[#424245]/30"><h3 className="text-sm font-medium text-[#f5f5f7]">Settings</h3></div>{/* Content */}<div className="flex-1 p-4 space-y-5 overflow-y-auto">{/* Language Selection */}<div className="relative" ref={languageDropdownRef}><label className="block text-xs font-medium text-[#f5f5f7] mb-2">Language</label><buttontype="button"onClick={() => {setShowLanguageDropdown(!showLanguageDropdown);setShowModelDropdown(false);}}disabled={isGenerating || isLoading}className="w-full px-3 py-2 bg-[#1d1d1f] text-[#f5f5f7] text-sm border border-[#424245]/50 rounded-lg focus:outline-none focus:border-[#424245] disabled:opacity-40 flex items-center justify-between hover:bg-[#2d2d2f] transition-colors"><span>{isLoading ? 'Loading...' : formatLanguageName(selectedLanguage)}</span><svgclassName={`w-3.5 h-3.5 text-[#86868b] transition-transform ${showLanguageDropdown ? 'rotate-180' : ''}`}fill="none"stroke="currentColor"viewBox="0 0 24 24"strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" /></svg></button>{/* Language Dropdown Tray */}{showLanguageDropdown && !isLoading && languages.length > 0 && (<div className="absolute z-50 w-full mt-1 bg-[#1d1d1f] border border-[#424245] rounded-lg shadow-xl overflow-hidden"><div className="max-h-64 overflow-y-auto py-1">{languages.map((lang) => (<buttonkey={lang}type="button"onClick={() => {onLanguageChange(lang);setShowLanguageDropdown(false);}}className={`w-full px-3 py-2 text-left text-sm text-[#f5f5f7] hover:bg-[#2d2d2f] transition-colors ${selectedLanguage === lang ? 'bg-[#2d2d2f]' : ''}`}>{formatLanguageName(lang)}</button>))}</div></div>)}</div>{/* Model Selection */}<div className="relative" ref={modelDropdownRef}><label className="block text-xs font-medium text-[#f5f5f7] mb-2">AI Model</label><buttontype="button"onClick={() => {setShowModelDropdown(!showModelDropdown);setShowLanguageDropdown(false);}}disabled={isGenerating}className="w-full px-3 py-2 bg-[#1d1d1f] text-[#f5f5f7] text-sm border border-[#424245]/50 rounded-lg focus:outline-none focus:border-[#424245] disabled:opacity-40 flex items-center justify-between hover:bg-[#2d2d2f] transition-colors"><span className="truncate">{isLoading? 'Loading...': models.find(m => m.id === selectedModel)?.name || selectedModel || 'Select model'}</span><svgclassName={`w-3.5 h-3.5 text-[#86868b] flex-shrink-0 ml-2 transition-transform ${showModelDropdown ? 'rotate-180' : ''}`}fill="none"stroke="currentColor"viewBox="0 0 24 24"strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" /></svg></button>{/* Model Dropdown Tray */}{showModelDropdown && models.length > 0 && (<div className="absolute z-50 w-full mt-1 bg-[#1d1d1f] border border-[#424245] rounded-lg shadow-xl overflow-hidden"><div className="max-h-96 overflow-y-auto py-1">{models.map((model) => (<buttonkey={model.id}type="button"onClick={() => {onModelChange(model.id);setShowModelDropdown(false);}}className={`w-full px-3 py-2 text-left transition-colors ${selectedModel === model.id? 'bg-[#2d2d2f]': 'hover:bg-[#2d2d2f]'}`}><div className="flex items-center justify-between gap-2"><span className="text-sm text-[#f5f5f7]">{model.name}</span>{model.id === 'zai-org/GLM-4.6V:zai-org' && (<span className="px-1.5 py-0.5 bg-gradient-to-r from-purple-500 to-pink-500 text-white text-[9px] font-bold rounded uppercase flex-shrink-0">NEW</span>)}</div>{model.description && (<div className="text-[10px] text-[#86868b] mt-0.5 leading-relaxed">{model.description}</div>)}</button>))}</div></div>)}{/* Model Description */}{!isLoading && models.find(m => m.id === selectedModel) && (<p className="text-[10px] text-[#86868b] mt-2 leading-relaxed">{models.find(m => m.id === selectedModel)?.description}</p>)}</div>{/* Action Buttons */}<div className="flex flex-col space-y-2"><buttononClick={onClear}disabled={isGenerating}className="w-full px-3 py-2.5 bg-[#1d1d1f] text-[#f5f5f7] text-sm rounded-full hover:bg-[#2d2d2f] disabled:opacity-30 disabled:cursor-not-allowed transition-all font-medium border border-[#424245]/50 flex items-center justify-center active:scale-95">New Chat</button></div></div></div>);23 unmodified lines2425262728293062 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623 unmodified linesconst [models, setModels] = useState<Model[]>([]);const [languages, setLanguages] = useState<Language[]>([]);const [isLoading, setIsLoading] = useState(true);// Dropdown statesconst [showLanguageDropdown, setShowLanguageDropdown] = useState(false);const [showModelDropdown, setShowModelDropdown] = useState(false);62 unmodified lines<div className="flex items-center px-4 py-3 border-b border-[#424245]/30"><h3 className="text-sm font-medium text-[#f5f5f7]">Settings</h3></div>{/* Content */}<div className="flex-1 p-4 space-y-5 overflow-y-auto">{/* Language Selection */}<div className="relative" ref={languageDropdownRef}><label className="block text-xs font-medium text-[#f5f5f7] mb-2">Language</label><buttontype="button"onClick={() => {setShowLanguageDropdown(!showLanguageDropdown);setShowModelDropdown(false);}}disabled={isGenerating || isLoading}className="w-full px-3 py-2 bg-[#1d1d1f] text-[#f5f5f7] text-sm border border-[#424245]/50 rounded-lg focus:outline-none focus:border-[#424245] disabled:opacity-40 flex items-center justify-between hover:bg-[#2d2d2f] transition-colors"><span>{isLoading ? 'Loading...' : formatLanguageName(selectedLanguage)}</span><svgclassName={`w-3.5 h-3.5 text-[#86868b] transition-transform ${showLanguageDropdown ? 'rotate-180' : ''}`}fill="none"stroke="currentColor"viewBox="0 0 24 24"strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" /></svg></button>{/* Language Dropdown Tray */}{showLanguageDropdown && !isLoading && languages.length > 0 && (<div className="absolute z-50 w-full mt-1 bg-[#1d1d1f] border border-[#424245] rounded-lg shadow-xl overflow-hidden"><div className="max-h-64 overflow-y-auto py-1">{languages.map((lang) => (<buttonkey={lang}type="button"onClick={() => {onLanguageChange(lang);setShowLanguageDropdown(false);}}className={`w-full px-3 py-2 text-left text-sm text-[#f5f5f7] hover:bg-[#2d2d2f] transition-colors ${selectedLanguage === lang ? 'bg-[#2d2d2f]' : ''}`}>{formatLanguageName(lang)}</button>))}</div></div>)}</div>{/* Model Selection */}<div className="relative" ref={modelDropdownRef}><label className="block text-xs font-medium text-[#f5f5f7] mb-2">AI Model</label><buttontype="button"onClick={() => {setShowModelDropdown(!showModelDropdown);setShowLanguageDropdown(false);}}disabled={isGenerating}className="w-full px-3 py-2 bg-[#1d1d1f] text-[#f5f5f7] text-sm border border-[#424245]/50 rounded-lg focus:outline-none focus:border-[#424245] disabled:opacity-40 flex items-center justify-between hover:bg-[#2d2d2f] transition-colors"><span className="truncate">{isLoading? 'Loading...': models.find(m => m.id === selectedModel)?.name || selectedModel || 'Select model'}</span><svgclassName={`w-3.5 h-3.5 text-[#86868b] flex-shrink-0 ml-2 transition-transform ${showModelDropdown ? 'rotate-180' : ''}`}fill="none"stroke="currentColor"viewBox="0 0 24 24"strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" /></svg></button>{/* Model Dropdown Tray */}{showModelDropdown && models.length > 0 && (<div className="absolute z-50 w-full mt-1 bg-[#1d1d1f] border border-[#424245] rounded-lg shadow-xl overflow-hidden"><div className="max-h-96 overflow-y-auto py-1">{models.map((model) => (<buttonkey={model.id}type="button"onClick={() => {onModelChange(model.id);setShowModelDropdown(false);}}className={`w-full px-3 py-2 text-left transition-colors ${selectedModel === model.id? 'bg-[#2d2d2f]': 'hover:bg-[#2d2d2f]'}`}><div className="flex items-center justify-between gap-2"><span className="text-sm text-[#f5f5f7]">{model.name}</span>{model.id === 'devstral-medium-2512' && (<span className="px-1.5 py-0.5 bg-gradient-to-r from-purple-500 to-pink-500 text-white text-[9px] font-bold rounded uppercase flex-shrink-0">NEW</span>)}</div>{model.description && (<div className="text-[10px] text-[#86868b] mt-0.5 leading-relaxed">{model.description}</div>)}</button>))}</div></div>)}{/* Model Description */}{!isLoading && models.find(m => m.id === selectedModel) && (<p className="text-[10px] text-[#86868b] mt-2 leading-relaxed">{models.find(m => m.id === selectedModel)?.description}</p>)}</div>{/* Action Buttons */}<div className="flex flex-col space-y-2"><buttononClick={onClear}disabled={isGenerating}className="w-full px-3 py-2.5 bg-[#1d1d1f] text-[#f5f5f7] text-sm rounded-full hover:bg-[#2d2d2f] disabled:opacity-30 disabled:cursor-not-allowed transition-all font-medium border border-[#424245]/50 flex items-center justify-center active:scale-95">New Chat</button></div></div></div>);
2 unmodified lines3456789101112131415169 unmodified lines2627282930313233343536374 unmodified lines42434445464748495051525354553 unmodified lines596061626364656667686970717273747576777879808127 unmodified lines10911011111211311411533 unmodified lines14915015115215315415560 unmodified lines21621721821922022122222322422522622722822923 unmodified lines2532542552562572582595 unmodified lines26526626726826927027114 unmodified lines28628728828929029129229329429529629729829923 unmodified lines3233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683691 unmodified line3713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064 unmodified lines4114124134144154164171 unmodified line41942042142242342442526 unmodified lines45245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749810 unmodified lines5095105115125135145151 unmodified line51751851952052152252352452552652752852953053153253353453553653753853954054154212 unmodified lines55555655755855956056156256356456556656756856957012 unmodified lines5835845855865875885895905915925935945955965971 unmodified line59960060160260360460560652 unmodified lines65966066166266366466526 unmodified lines6926936946956966976986997007017027 unmodified lines7107117127137147157168 unmodified lines72572672772872973073112 unmodified lines7447457467477487497507517527537547557567577587597607617627636 unmodified lines77077177277377477577677777817 unmodified lines7967977987998008018028038048058068078088098108118128138148158168178188198206 unmodified lines82782882983083183283383483583683783883984084125 unmodified lines86786886987087187287387487587611 unmodified lines88888989089189289389489589689789889912 unmodified lines91291391491591691791810 unmodified lines92993093193293393493510 unmodified lines9469479489499509519521 unmodified line95495595695795895996096196296396448 unmodified lines10131014101510161017101810191020102110228 unmodified lines10311032103310341035103610377 unmodified lines104510461047104810491050105110521053105410551056105717 unmodified lines107510761077107810791080108129 unmodified lines11111112111311141115111611178 unmodified lines112611271128112911301131113245 unmodified lines11781179118011811182118311842 unmodified linesimport { useState, useEffect, useRef } from 'react';import Image from 'next/image';import { apiClient } from '@/lib/api';import {initializeOAuth,loginWithHuggingFace,loginDevMode,logout,getStoredUserInfo,isAuthenticated as checkIsAuthenticated,isDevelopmentMode} from '@/lib/auth';import type { Model, Language } from '@/types';import type { OAuthUserInfo } from '@/lib/auth';9 unmodified linespendingPRRef?: React.MutableRefObject<{ repoId: string; language: Language } | null>;}export default function LandingPage({onStart,onImport,isAuthenticated,initialLanguage = 'html',initialModel = 'zai-org/GLM-4.6V:zai-org',onAuthChange,setPendingPR,pendingPRRef4 unmodified linesconst [models, setModels] = useState<Model[]>([]);const [languages, setLanguages] = useState<Language[]>([]);const [isLoading, setIsLoading] = useState(true);// Auth statesconst [userInfo, setUserInfo] = useState<OAuthUserInfo | null>(null);const [isAuthLoading, setIsAuthLoading] = useState(true);const [showDevLogin, setShowDevLogin] = useState(false);const [devUsername, setDevUsername] = useState('');const isDevMode = isDevelopmentMode();// Dropdown statesconst [showLanguageDropdown, setShowLanguageDropdown] = useState(false);const [showModelDropdown, setShowModelDropdown] = useState(false);3 unmodified linesconst modelDropdownRef = useRef<HTMLDivElement>(null);const importDialogRef = useRef<HTMLDivElement>(null);const redesignDialogRef = useRef<HTMLDivElement>(null);// Trending apps stateconst [trendingApps, setTrendingApps] = useState<any[]>([]);// Import project stateconst [importUrl, setImportUrl] = useState('');const [isImporting, setIsImporting] = useState(false);const [importError, setImportError] = useState('');const [importAction, setImportAction] = useState<'duplicate' | 'update' | 'pr'>('duplicate'); // Default to duplicateconst [isSpaceOwner, setIsSpaceOwner] = useState(false); // Track if user owns the space// Redesign project stateconst [redesignUrl, setRedesignUrl] = useState('');const [isRedesigning, setIsRedesigning] = useState(false);const [redesignError, setRedesignError] = useState('');const [createPR, setCreatePR] = useState(false); // Default to normal redesign (not PR)// Image upload stateconst [uploadedImageUrl, setUploadedImageUrl] = useState<string | null>(null);const fileInputRef = useRef<HTMLInputElement>(null);27 unmodified linessetIsAuthLoading(true);try {const oauthResult = await initializeOAuth();if (oauthResult) {setUserInfo(oauthResult.userInfo);apiClient.setToken(oauthResult.accessToken);33 unmodified linesalert('Please enter a username');return;}try {const result = loginDevMode(devUsername);setUserInfo(result.userInfo);60 unmodified linesconsole.error('Failed to load languages:', error);}};// Check if current model supports images// Show immediately for GLM-4.6V even before models loadconst currentModelSupportsImages =selectedModel === 'zai-org/GLM-4.6V:zai-org' ||models.find(m => m.id === selectedModel)?.supports_images ||false;// Debug logginguseEffect(() => {console.log('[LandingPage] Selected model:', selectedModel);23 unmodified linesalert('Please sign in with HuggingFace first!');}};const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {const file = e.target.files?.[0];if (file) {5 unmodified linesreader.readAsDataURL(file);}};const removeImage = () => {setUploadedImageUrl(null);if (fileInputRef.current) {14 unmodified linessetIsSpaceOwner(false);return;}const spaceMatch = url.match(/huggingface\.co\/spaces\/([^\/\s\)]+)\/[^\/\s\)]+/);if (spaceMatch) {const spaceOwner = spaceMatch[1];const isOwner = spaceOwner === userInfo.preferred_username;setIsSpaceOwner(isOwner);console.log('[Import] Space owner:', spaceOwner, '| Current user:', userInfo.preferred_username, '| Is owner:', isOwner);// Auto-select update mode if owner, otherwise duplicateif (isOwner) {setImportAction('update');23 unmodified linesconsole.log('[Import] ========== STARTING IMPORT ==========');console.log('[Import] Import URL:', importUrl);console.log('[Import] Action:', importAction);// Extract space ID from URLconst spaceMatch = importUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);console.log('[Import] Space regex match result:', spaceMatch);if (spaceMatch) {const fromSpaceId = spaceMatch[1];console.log('[Import] ✅ Detected HF Space:', fromSpaceId);// Import the code first (always needed to load in editor)const importResult = await apiClient.importProject(importUrl);if (importResult.status !== 'success') {setImportError(importResult.message || 'Failed to import project');setIsImporting(false);return;}// Handle different import actionsif (importAction === 'update' && isSpaceOwner) {// Option 1: Update existing space directly (for owners)console.log('[Import] Owner update - loading code for direct update to:', fromSpaceId);if (onImport && importResult.code) {// Pass the original space URL so future deployments update itonImport(importResult.code, importResult.language || 'html', importUrl);alert(`✅ Code loaded!\n\nYou can now make changes and deploy them directly to: ${importUrl}\n\nThe code has been loaded in the editor.`);}setShowImportDialog(false);setImportUrl('');} else if (importAction === 'pr') {// Option 2: Create Pull Requestconsole.log('[Import] PR mode - loading code to create PR to:', fromSpaceId);if (onImport && importResult.code) {// Load code in editor with the original space for PR trackingonImport(importResult.code, importResult.language || 'html', importUrl);// Set pending PR state so any future code generation creates a PRif (setPendingPR && pendingPRRef) {const prInfo = { repoId: fromSpaceId, language: (importResult.language || 'html') as Language };1 unmodified linependingPRRef.current = prInfo;console.log('[Import PR] Set pending PR:', prInfo);}// Show success messagealert(`✅ Code loaded in PR mode!\n\nYou can now:\n• Make manual edits in the editor\n• Generate new features with AI\n\nWhen you deploy, a Pull Request will be created to: ${fromSpaceId}`);}setShowImportDialog(false);setImportUrl('');} else {// Option 3: Duplicate space (default)console.log('[Import] Duplicate mode - will duplicate:', fromSpaceId);const duplicateResult = await apiClient.duplicateSpace(fromSpaceId);console.log('[Import] Duplicate API response:', duplicateResult);if (duplicateResult.success) {console.log('[Import] ========== DUPLICATE SUCCESS ==========');console.log('[Import] Duplicated space URL:', duplicateResult.space_url);console.log('[Import] Duplicated space ID:', duplicateResult.space_id);console.log('[Import] ==========================================');if (onImport && importResult.code) {console.log('[Import] Calling onImport with duplicated space URL:', duplicateResult.space_url);// Pass the duplicated space URL so it's tracked for future deploymentsonImport(importResult.code, importResult.language || 'html', duplicateResult.space_url);// Show success message with link to duplicated spacealert(`✅ Space duplicated successfully!\n\nYour space: ${duplicateResult.space_url}\n\nThe code has been loaded in the editor. Any changes you deploy will update this duplicated space.`);}setShowImportDialog(false);setImportUrl('');} else {4 unmodified lines// Not a Space URL - fall back to regular importconsole.log('[Import] ❌ Not a HF Space URL - using regular import');const result = await apiClient.importProject(importUrl);if (result.status === 'success') {if (onImport && result.code) {onImport(result.code, result.language || 'html', importUrl);1 unmodified lineconst importMessage = `Imported from ${importUrl}`;onStart(importMessage, result.language || 'html', selectedModel, undefined);}setShowImportDialog(false);setImportUrl('');} else {26 unmodified lines// Extract space ID from URLconst spaceMatch = redesignUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);const repoId = spaceMatch ? spaceMatch[1] : null;if (!repoId) {setRedesignError('Please enter a valid HuggingFace Space URL');setIsRedesigning(false);return;}// Import the code firstconst result = await apiClient.importProject(redesignUrl);if (result.status !== 'success') {setRedesignError(result.message || 'Failed to import project for redesign');setIsRedesigning(false);return;}if (!createPR) {// Option 1: Redesign WITHOUT PR - Duplicate space first, then generate redesignconsole.log('[Redesign] Duplicating space first:', repoId);try {const duplicateResult = await apiClient.duplicateSpace(repoId);console.log('[Redesign] Duplicate result:', duplicateResult);if (!duplicateResult.success) {setRedesignError(duplicateResult.message || 'Failed to duplicate space');setIsRedesigning(false);return;}// Load code and trigger redesignif (onImport && onStart) {// Pass duplicated space URLonImport(result.code, result.language || 'html', duplicateResult.space_url);// Extract duplicated space ID to pass to generationconst dupSpaceMatch = duplicateResult.space_url?.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);const duplicatedRepoId = dupSpaceMatch ? dupSpaceMatch[1] : undefined;console.log('[Redesign] Duplicated space ID:', duplicatedRepoId);setTimeout(() => {const isGradio = (result.language || 'html') === 'gradio';const redesignPrompt = `I have existing code in the editor from a duplicated space. Please redesign it to make it look better with minimal components needed, mobile friendly, and modern design.10 unmodified lines- Better visual hierarchy and spacing${isGradio ? '\n\nIMPORTANT: Only output app.py with the redesigned UI (themes, layout, styling). Do NOT modify or output any other .py files (utils.py, models.py, etc.). Do NOT include requirements.txt or README.md.' : ''}`;if (onStart) {// Pass duplicated space ID so auto-deploy updates itconsole.log('[Redesign] Calling onStart with duplicated repo ID:', duplicatedRepoId);1 unmodified lineonStart(redesignPrompt, result.language || 'html', 'claude-sonnet-4.5', undefined, duplicatedRepoId);}}, 100);// Show success messagealert(`✅ Space duplicated!\n\nYour space: ${duplicateResult.space_url}\n\nGenerating redesign now...`);}setShowRedesignDialog(false);setRedesignUrl('');} catch (dupError: any) {console.error('[Redesign] Duplication error:', dupError);setRedesignError(dupError.response?.data?.message || dupError.message || 'Failed to duplicate space');setIsRedesigning(false);return;}} else {// Option 2: Redesign WITH PR - Import code and generate, then create PRif (onImport && onStart) {onImport(result.code, result.language || 'html', redesignUrl);setTimeout(() => {const isGradio = (result.language || 'html') === 'gradio';const redesignPrompt = `I have existing code in the editor that I imported from ${redesignUrl}. Please redesign it to make it look better with minimal components needed, mobile friendly, and modern design.12 unmodified lines${isGradio ? '\n\nIMPORTANT: Only output app.py with the redesigned UI (themes, layout, styling). Do NOT modify or output any other .py files (utils.py, models.py, etc.). Do NOT include requirements.txt or README.md.' : ''}Note: After generating the redesign, I will create a Pull Request on the original space.`;if (onStart) {console.log('[Redesign] Will create PR - not passing repo ID');console.log('[Redesign] Using Claude-Sonnet-4.5 for redesign');onStart(redesignPrompt, result.language || 'html', 'claude-sonnet-4.5', undefined, repoId, true); // Pass true for shouldCreatePR}console.log('[Redesign] Will create PR after code generation completes');}, 100);setShowRedesignDialog(false);setRedesignUrl('');} else {12 unmodified lines<div className="h-screen flex flex-col bg-[#000000] overflow-hidden">{/* Header - Apple style */}<header className="flex items-center justify-between px-6 py-3 backdrop-blur-xl bg-[#000000]/80 border-b border-[#424245]/30 flex-shrink-0"><ahref="https://huggingface.co/spaces/akhaliq/anycoder"target="_blank"rel="noopener noreferrer"className="text-sm font-medium text-[#f5f5f7] hover:text-white transition-colors">AnyCoder</a>{/* Auth Section */}<div className="flex items-center space-x-3">{isAuthLoading ? (1 unmodified line) : userInfo ? (<div className="flex items-center space-x-3">{userInfo.avatarUrl && (<imgsrc={userInfo.avatarUrl}alt={userInfo.name}className="w-7 h-7 rounded-full"/>52 unmodified lines<span className="text-[#86868b] text-sm">or</span></>)}{/* OAuth Login */}<buttononClick={handleLogin}26 unmodified lines{uploadedImageUrl && (<div className="px-4 pt-3"><div className="relative inline-block"><Imagesrc={uploadedImageUrl}alt="Upload preview"width={120}height={120}className="rounded-lg object-cover"unoptimized/>7 unmodified lines</div></div>)}{/* Textarea */}<textareavalue={prompt}8 unmodified lines}}}/>{/* Bottom controls - Apple style */}<div className="flex items-center justify-between px-3 pb-3 gap-2">{/* Compact dropdowns on the left */}12 unmodified linesclassName="px-3 py-1.5 bg-[#1d1d1f] text-[#f5f5f7] text-xs border border-[#424245] rounded-full hover:bg-[#2d2d2f] transition-all disabled:opacity-50 flex items-center gap-1.5 font-medium"><span>{isLoading ? '...' : formatLanguageName(selectedLanguage)}</span><svgclassName={`w-3 h-3 text-[#86868b] transition-transform ${showLanguageDropdown ? 'rotate-180' : ''}`}fill="none"stroke="currentColor"viewBox="0 0 24 24"strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" /></svg></button>{/* Language Dropdown Menu */}{showLanguageDropdown && !isLoading && languages.length > 0 && (<divclassName="absolute bottom-full left-0 mb-2 w-48 bg-[#1d1d1f] border border-[#424245] rounded-xl shadow-2xl overflow-hidden backdrop-blur-xl"onClick={(e) => e.stopPropagation()}>6 unmodified linessetSelectedLanguage(lang);setShowLanguageDropdown(false);}}className={`w-full px-4 py-2.5 text-left text-xs text-[#f5f5f7] hover:bg-[#2d2d2f] transition-colors font-medium ${selectedLanguage === lang ? 'bg-[#2d2d2f]' : ''}`}>{formatLanguageName(lang)}</button>17 unmodified linesclassName="px-3 py-1.5 bg-[#1d1d1f] text-[#f5f5f7] text-xs border border-[#424245] rounded-full hover:bg-[#2d2d2f] transition-all flex items-center gap-1.5 max-w-[200px] font-medium"><span className="truncate">{isLoading? '...': models.find(m => m.id === selectedModel)?.name || selectedModel || 'Model'}</span><svgclassName={`w-3 h-3 text-[#86868b] flex-shrink-0 transition-transform ${showModelDropdown ? 'rotate-180' : ''}`}fill="none"stroke="currentColor"viewBox="0 0 24 24"strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" /></svg></button>{/* Model Dropdown Menu */}{showModelDropdown && models.length > 0 && (<divclassName="absolute top-full left-0 mt-2 w-56 bg-[#1d1d1f] border border-[#424245] rounded-xl shadow-2xl overflow-hidden backdrop-blur-xl z-50"onClick={(e) => e.stopPropagation()}>6 unmodified linessetSelectedModel(model.id);setShowModelDropdown(false);}}className={`w-full px-4 py-2 text-left transition-colors ${selectedModel === model.id? 'bg-[#2d2d2f]': 'hover:bg-[#2d2d2f]'}`}><div className="flex items-center justify-between gap-2"><span className="text-xs font-medium text-[#f5f5f7]">{model.name}</span>{model.id === 'zai-org/GLM-4.6V:zai-org' && (<span className="px-1.5 py-0.5 bg-gradient-to-r from-purple-500 to-pink-500 text-white text-[9px] font-bold rounded uppercase">NEW</span>25 unmodified lines</svg><span>Import</span></button>{/* Import Dialog */}{showImportDialog && (<divclassName="absolute top-full left-0 mt-2 w-80 bg-[#1d1d1f] border border-[#424245] rounded-xl shadow-2xl overflow-hidden backdrop-blur-xl z-50"onClick={(e) => e.stopPropagation()}>11 unmodified linesclassName="w-full px-3 py-2 rounded-lg text-xs bg-[#2d2d30] text-[#f5f5f7] border border-[#424245] focus:outline-none focus:border-white/50 font-normal mb-3"disabled={isImporting}/>{/* Import Action Options */}{importUrl.includes('huggingface.co/spaces/') && (<div className="mb-3 space-y-2"><p className="text-[10px] font-medium text-[#86868b] mb-2">Import Mode:</p>{/* Update Space (only for owners) */}{isSpaceOwner && (<label className="flex items-start gap-2 cursor-pointer group">12 unmodified lines</div></label>)}{/* Duplicate Space */}<label className="flex items-start gap-2 cursor-pointer group"><input10 unmodified lines</p></div></label>{/* Create PR */}<label className="flex items-start gap-2 cursor-pointer group"><input10 unmodified lines</p></div></label>{importAction === 'pr' && (<p className="text-[10px] text-[#86868b] ml-6 mt-1">⚠️ Requires space owner to enable PRs1 unmodified line)}</div>)}{importError && (<p className="text-xs text-red-400 mb-2">{importError}</p>)}<div className="flex gap-2"><buttononClick={handleImportProject}48 unmodified lines<span className="absolute inset-0 bg-gradient-to-r from-pink-500 via-purple-500 to-indigo-500 rounded-full blur-sm opacity-75 animate-pulse"></span></span></button>{/* Redesign Dialog */}{showRedesignDialog && (<divclassName="absolute top-full left-0 mt-2 w-80 bg-[#1d1d1f] border border-[#424245] rounded-xl shadow-2xl overflow-hidden backdrop-blur-xl z-50"onClick={(e) => e.stopPropagation()}>8 unmodified linesclassName="w-full px-3 py-2 rounded-lg text-xs bg-[#2d2d30] text-[#f5f5f7] border border-[#424245] focus:outline-none focus:border-white/50 font-normal mb-3"disabled={isRedesigning}/>{/* PR Option */}<label className="flex items-center gap-2 mb-1 cursor-pointer"><input7 unmodified linesCreate Pull Request on original space</span></label>{createPR && (<p className="text-[10px] text-[#86868b] mb-2 ml-6">⚠️ Note: PR creation requires space owner to enable PRs. If disabled, uncheck this to duplicate the space instead.</p>)}{redesignError && (<p className="text-xs text-red-400 mb-2">{redesignError}</p>)}17 unmodified lines</button></div><p className="text-[10px] text-[#86868b] mt-3">{createPR? 'Creates a Pull Request on the original space with your redesign': 'Import and automatically redesign with modern, mobile-friendly design'}</p>29 unmodified lines</button></>)}{/* Send button - Apple style */}<buttontype="submit"8 unmodified lines</div></div></div>{!isAuthenticated && (<div className="mt-4 text-center"><p className="text-xs text-[#86868b]">45 unmodified lines<span className="px-1.5 py-0.5 bg-[#2d2d30] text-[#86868b] text-[9px] rounded-full font-medium">{app.sdk}</span>{app.tags?.slice(0, 2).map((tag: string) =>tag !== 'anycoder' && tag !== app.sdk && tag !== 'region:us' && (<span key={tag} className="px-1.5 py-0.5 bg-[#2d2d30] text-[#86868b] text-[9px] rounded-full font-medium">{tag}2 unmodified lines3456789101112131415169 unmodified lines2627282930313233343536374 unmodified lines42434445464748495051525354553 unmodified lines596061626364656667686970717273747576777879808127 unmodified lines10911011111211311411533 unmodified lines14915015115215315415560 unmodified lines21621721821922022122222322422522622722822923 unmodified lines2532542552562572582595 unmodified lines26526626726826927027114 unmodified lines28628728828929029129229329429529629729829923 unmodified lines3233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683691 unmodified line3713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064 unmodified lines4114124134144154164171 unmodified line41942042142242342442526 unmodified lines45245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749810 unmodified lines5095105115125135145151 unmodified line51751851952052152252352452552652752852953053153253353453553653753853954054154212 unmodified lines55555655755855956056156256356456556656756856957012 unmodified lines5835845855865875885895905915925935945955965971 unmodified line59960060160260360460560652 unmodified lines65966066166266366466526 unmodified lines6926936946956966976986997007017027 unmodified lines7107117127137147157168 unmodified lines72572672772872973073112 unmodified lines7447457467477487497507517527537547557567577587597607617627636 unmodified lines77077177277377477577677717 unmodified lines7957967977987998008018028038048058068078088098108118128138148158168178188196 unmodified lines82682782882983083183283383483583683783883925 unmodified lines86586686786886987087187287387411 unmodified lines88688788888989089189289389489589689712 unmodified lines91091191291391491591610 unmodified lines92792892993093193293310 unmodified lines9449459469479489499501 unmodified line95295395495595695795895996096196248 unmodified lines10111012101310141015101610171018101910208 unmodified lines10291030103110321033103410357 unmodified lines104310441045104610471048104910501051105210531054105517 unmodified lines107310741075107610771078107929 unmodified lines11091110111111121113111411158 unmodified lines112411251126112711281129113045 unmodified lines11761177117811791180118111822 unmodified linesimport { useState, useEffect, useRef } from 'react';import Image from 'next/image';import { apiClient } from '@/lib/api';import {initializeOAuth,loginWithHuggingFace,loginDevMode,logout,getStoredUserInfo,isAuthenticated as checkIsAuthenticated,isDevelopmentMode} from '@/lib/auth';import type { Model, Language } from '@/types';import type { OAuthUserInfo } from '@/lib/auth';9 unmodified linespendingPRRef?: React.MutableRefObject<{ repoId: string; language: Language } | null>;}export default function LandingPage({onStart,onImport,isAuthenticated,initialLanguage = 'html',initialModel = 'devstral-medium-2512',onAuthChange,setPendingPR,pendingPRRef4 unmodified linesconst [models, setModels] = useState<Model[]>([]);const [languages, setLanguages] = useState<Language[]>([]);const [isLoading, setIsLoading] = useState(true);// Auth statesconst [userInfo, setUserInfo] = useState<OAuthUserInfo | null>(null);const [isAuthLoading, setIsAuthLoading] = useState(true);const [showDevLogin, setShowDevLogin] = useState(false);const [devUsername, setDevUsername] = useState('');const isDevMode = isDevelopmentMode();// Dropdown statesconst [showLanguageDropdown, setShowLanguageDropdown] = useState(false);const [showModelDropdown, setShowModelDropdown] = useState(false);3 unmodified linesconst modelDropdownRef = useRef<HTMLDivElement>(null);const importDialogRef = useRef<HTMLDivElement>(null);const redesignDialogRef = useRef<HTMLDivElement>(null);// Trending apps stateconst [trendingApps, setTrendingApps] = useState<any[]>([]);// Import project stateconst [importUrl, setImportUrl] = useState('');const [isImporting, setIsImporting] = useState(false);const [importError, setImportError] = useState('');const [importAction, setImportAction] = useState<'duplicate' | 'update' | 'pr'>('duplicate'); // Default to duplicateconst [isSpaceOwner, setIsSpaceOwner] = useState(false); // Track if user owns the space// Redesign project stateconst [redesignUrl, setRedesignUrl] = useState('');const [isRedesigning, setIsRedesigning] = useState(false);const [redesignError, setRedesignError] = useState('');const [createPR, setCreatePR] = useState(false); // Default to normal redesign (not PR)// Image upload stateconst [uploadedImageUrl, setUploadedImageUrl] = useState<string | null>(null);const fileInputRef = useRef<HTMLInputElement>(null);27 unmodified linessetIsAuthLoading(true);try {const oauthResult = await initializeOAuth();if (oauthResult) {setUserInfo(oauthResult.userInfo);apiClient.setToken(oauthResult.accessToken);33 unmodified linesalert('Please enter a username');return;}try {const result = loginDevMode(devUsername);setUserInfo(result.userInfo);60 unmodified linesconsole.error('Failed to load languages:', error);}};// Check if current model supports images// Show immediately for GLM-4.6V even before models loadconst currentModelSupportsImages =selectedModel === 'zai-org/GLM-4.6V:zai-org' ||models.find(m => m.id === selectedModel)?.supports_images ||false;// Debug logginguseEffect(() => {console.log('[LandingPage] Selected model:', selectedModel);23 unmodified linesalert('Please sign in with HuggingFace first!');}};const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {const file = e.target.files?.[0];if (file) {5 unmodified linesreader.readAsDataURL(file);}};const removeImage = () => {setUploadedImageUrl(null);if (fileInputRef.current) {14 unmodified linessetIsSpaceOwner(false);return;}const spaceMatch = url.match(/huggingface\.co\/spaces\/([^\/\s\)]+)\/[^\/\s\)]+/);if (spaceMatch) {const spaceOwner = spaceMatch[1];const isOwner = spaceOwner === userInfo.preferred_username;setIsSpaceOwner(isOwner);console.log('[Import] Space owner:', spaceOwner, '| Current user:', userInfo.preferred_username, '| Is owner:', isOwner);// Auto-select update mode if owner, otherwise duplicateif (isOwner) {setImportAction('update');23 unmodified linesconsole.log('[Import] ========== STARTING IMPORT ==========');console.log('[Import] Import URL:', importUrl);console.log('[Import] Action:', importAction);// Extract space ID from URLconst spaceMatch = importUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);console.log('[Import] Space regex match result:', spaceMatch);if (spaceMatch) {const fromSpaceId = spaceMatch[1];console.log('[Import] ✅ Detected HF Space:', fromSpaceId);// Import the code first (always needed to load in editor)const importResult = await apiClient.importProject(importUrl);if (importResult.status !== 'success') {setImportError(importResult.message || 'Failed to import project');setIsImporting(false);return;}// Handle different import actionsif (importAction === 'update' && isSpaceOwner) {// Option 1: Update existing space directly (for owners)console.log('[Import] Owner update - loading code for direct update to:', fromSpaceId);if (onImport && importResult.code) {// Pass the original space URL so future deployments update itonImport(importResult.code, importResult.language || 'html', importUrl);alert(`✅ Code loaded!\n\nYou can now make changes and deploy them directly to: ${importUrl}\n\nThe code has been loaded in the editor.`);}setShowImportDialog(false);setImportUrl('');} else if (importAction === 'pr') {// Option 2: Create Pull Requestconsole.log('[Import] PR mode - loading code to create PR to:', fromSpaceId);if (onImport && importResult.code) {// Load code in editor with the original space for PR trackingonImport(importResult.code, importResult.language || 'html', importUrl);// Set pending PR state so any future code generation creates a PRif (setPendingPR && pendingPRRef) {const prInfo = { repoId: fromSpaceId, language: (importResult.language || 'html') as Language };1 unmodified linependingPRRef.current = prInfo;console.log('[Import PR] Set pending PR:', prInfo);}// Show success messagealert(`✅ Code loaded in PR mode!\n\nYou can now:\n• Make manual edits in the editor\n• Generate new features with AI\n\nWhen you deploy, a Pull Request will be created to: ${fromSpaceId}`);}setShowImportDialog(false);setImportUrl('');} else {// Option 3: Duplicate space (default)console.log('[Import] Duplicate mode - will duplicate:', fromSpaceId);const duplicateResult = await apiClient.duplicateSpace(fromSpaceId);console.log('[Import] Duplicate API response:', duplicateResult);if (duplicateResult.success) {console.log('[Import] ========== DUPLICATE SUCCESS ==========');console.log('[Import] Duplicated space URL:', duplicateResult.space_url);console.log('[Import] Duplicated space ID:', duplicateResult.space_id);console.log('[Import] ==========================================');if (onImport && importResult.code) {console.log('[Import] Calling onImport with duplicated space URL:', duplicateResult.space_url);// Pass the duplicated space URL so it's tracked for future deploymentsonImport(importResult.code, importResult.language || 'html', duplicateResult.space_url);// Show success message with link to duplicated spacealert(`✅ Space duplicated successfully!\n\nYour space: ${duplicateResult.space_url}\n\nThe code has been loaded in the editor. Any changes you deploy will update this duplicated space.`);}setShowImportDialog(false);setImportUrl('');} else {4 unmodified lines// Not a Space URL - fall back to regular importconsole.log('[Import] ❌ Not a HF Space URL - using regular import');const result = await apiClient.importProject(importUrl);if (result.status === 'success') {if (onImport && result.code) {onImport(result.code, result.language || 'html', importUrl);1 unmodified lineconst importMessage = `Imported from ${importUrl}`;onStart(importMessage, result.language || 'html', selectedModel, undefined);}setShowImportDialog(false);setImportUrl('');} else {26 unmodified lines// Extract space ID from URLconst spaceMatch = redesignUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);const repoId = spaceMatch ? spaceMatch[1] : null;if (!repoId) {setRedesignError('Please enter a valid HuggingFace Space URL');setIsRedesigning(false);return;}// Import the code firstconst result = await apiClient.importProject(redesignUrl);if (result.status !== 'success') {setRedesignError(result.message || 'Failed to import project for redesign');setIsRedesigning(false);return;}if (!createPR) {// Option 1: Redesign WITHOUT PR - Duplicate space first, then generate redesignconsole.log('[Redesign] Duplicating space first:', repoId);try {const duplicateResult = await apiClient.duplicateSpace(repoId);console.log('[Redesign] Duplicate result:', duplicateResult);if (!duplicateResult.success) {setRedesignError(duplicateResult.message || 'Failed to duplicate space');setIsRedesigning(false);return;}// Load code and trigger redesignif (onImport && onStart) {// Pass duplicated space URLonImport(result.code, result.language || 'html', duplicateResult.space_url);// Extract duplicated space ID to pass to generationconst dupSpaceMatch = duplicateResult.space_url?.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);const duplicatedRepoId = dupSpaceMatch ? dupSpaceMatch[1] : undefined;console.log('[Redesign] Duplicated space ID:', duplicatedRepoId);setTimeout(() => {const isGradio = (result.language || 'html') === 'gradio';const redesignPrompt = `I have existing code in the editor from a duplicated space. Please redesign it to make it look better with minimal components needed, mobile friendly, and modern design.10 unmodified lines- Better visual hierarchy and spacing${isGradio ? '\n\nIMPORTANT: Only output app.py with the redesigned UI (themes, layout, styling). Do NOT modify or output any other .py files (utils.py, models.py, etc.). Do NOT include requirements.txt or README.md.' : ''}`;if (onStart) {// Pass duplicated space ID so auto-deploy updates itconsole.log('[Redesign] Calling onStart with duplicated repo ID:', duplicatedRepoId);1 unmodified lineonStart(redesignPrompt, result.language || 'html', 'claude-sonnet-4.5', undefined, duplicatedRepoId);}}, 100);// Show success messagealert(`✅ Space duplicated!\n\nYour space: ${duplicateResult.space_url}\n\nGenerating redesign now...`);}setShowRedesignDialog(false);setRedesignUrl('');} catch (dupError: any) {console.error('[Redesign] Duplication error:', dupError);setRedesignError(dupError.response?.data?.message || dupError.message || 'Failed to duplicate space');setIsRedesigning(false);return;}} else {// Option 2: Redesign WITH PR - Import code and generate, then create PRif (onImport && onStart) {onImport(result.code, result.language || 'html', redesignUrl);setTimeout(() => {const isGradio = (result.language || 'html') === 'gradio';const redesignPrompt = `I have existing code in the editor that I imported from ${redesignUrl}. Please redesign it to make it look better with minimal components needed, mobile friendly, and modern design.12 unmodified lines${isGradio ? '\n\nIMPORTANT: Only output app.py with the redesigned UI (themes, layout, styling). Do NOT modify or output any other .py files (utils.py, models.py, etc.). Do NOT include requirements.txt or README.md.' : ''}Note: After generating the redesign, I will create a Pull Request on the original space.`;if (onStart) {console.log('[Redesign] Will create PR - not passing repo ID');console.log('[Redesign] Using Claude-Sonnet-4.5 for redesign');onStart(redesignPrompt, result.language || 'html', 'claude-sonnet-4.5', undefined, repoId, true); // Pass true for shouldCreatePR}console.log('[Redesign] Will create PR after code generation completes');}, 100);setShowRedesignDialog(false);setRedesignUrl('');} else {12 unmodified lines<div className="h-screen flex flex-col bg-[#000000] overflow-hidden">{/* Header - Apple style */}<header className="flex items-center justify-between px-6 py-3 backdrop-blur-xl bg-[#000000]/80 border-b border-[#424245]/30 flex-shrink-0"><ahref="https://huggingface.co/spaces/akhaliq/anycoder"target="_blank"rel="noopener noreferrer"className="text-sm font-medium text-[#f5f5f7] hover:text-white transition-colors">AnyCoder</a>{/* Auth Section */}<div className="flex items-center space-x-3">{isAuthLoading ? (1 unmodified line) : userInfo ? (<div className="flex items-center space-x-3">{userInfo.avatarUrl && (<imgsrc={userInfo.avatarUrl}alt={userInfo.name}className="w-7 h-7 rounded-full"/>52 unmodified lines<span className="text-[#86868b] text-sm">or</span></>)}{/* OAuth Login */}<buttononClick={handleLogin}26 unmodified lines{uploadedImageUrl && (<div className="px-4 pt-3"><div className="relative inline-block"><Imagesrc={uploadedImageUrl}alt="Upload preview"width={120}height={120}className="rounded-lg object-cover"unoptimized/>7 unmodified lines</div></div>)}{/* Textarea */}<textareavalue={prompt}8 unmodified lines}}}/>{/* Bottom controls - Apple style */}<div className="flex items-center justify-between px-3 pb-3 gap-2">{/* Compact dropdowns on the left */}12 unmodified linesclassName="px-3 py-1.5 bg-[#1d1d1f] text-[#f5f5f7] text-xs border border-[#424245] rounded-full hover:bg-[#2d2d2f] transition-all disabled:opacity-50 flex items-center gap-1.5 font-medium"><span>{isLoading ? '...' : formatLanguageName(selectedLanguage)}</span><svgclassName={`w-3 h-3 text-[#86868b] transition-transform ${showLanguageDropdown ? 'rotate-180' : ''}`}fill="none"stroke="currentColor"viewBox="0 0 24 24"strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" /></svg></button>{/* Language Dropdown Menu */}{showLanguageDropdown && !isLoading && languages.length > 0 && (<divclassName="absolute bottom-full left-0 mb-2 w-48 bg-[#1d1d1f] border border-[#424245] rounded-xl shadow-2xl overflow-hidden backdrop-blur-xl"onClick={(e) => e.stopPropagation()}>6 unmodified linessetSelectedLanguage(lang);setShowLanguageDropdown(false);}}className={`w-full px-4 py-2.5 text-left text-xs text-[#f5f5f7] hover:bg-[#2d2d2f] transition-colors font-medium ${selectedLanguage === lang ? 'bg-[#2d2d2f]' : ''}`}>{formatLanguageName(lang)}</button>17 unmodified linesclassName="px-3 py-1.5 bg-[#1d1d1f] text-[#f5f5f7] text-xs border border-[#424245] rounded-full hover:bg-[#2d2d2f] transition-all flex items-center gap-1.5 max-w-[200px] font-medium"><span className="truncate">{isLoading? '...': models.find(m => m.id === selectedModel)?.name || selectedModel || 'Model'}</span><svgclassName={`w-3 h-3 text-[#86868b] flex-shrink-0 transition-transform ${showModelDropdown ? 'rotate-180' : ''}`}fill="none"stroke="currentColor"viewBox="0 0 24 24"strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" /></svg></button>{/* Model Dropdown Menu */}{showModelDropdown && models.length > 0 && (<divclassName="absolute top-full left-0 mt-2 w-56 bg-[#1d1d1f] border border-[#424245] rounded-xl shadow-2xl overflow-hidden backdrop-blur-xl z-50"onClick={(e) => e.stopPropagation()}>6 unmodified linessetSelectedModel(model.id);setShowModelDropdown(false);}}className={`w-full px-4 py-2 text-left transition-colors ${selectedModel === model.id? 'bg-[#2d2d2f]': 'hover:bg-[#2d2d2f]'}`}><div className="flex items-center justify-between gap-2"><span className="text-xs font-medium text-[#f5f5f7]">{model.name}</span>{model.id === 'devstral-medium-2512' && (<span className="px-1.5 py-0.5 bg-gradient-to-r from-purple-500 to-pink-500 text-white text-[9px] font-bold rounded uppercase">NEW</span>25 unmodified lines</svg><span>Import</span></button>{/* Import Dialog */}{showImportDialog && (<divclassName="absolute top-full left-0 mt-2 w-80 bg-[#1d1d1f] border border-[#424245] rounded-xl shadow-2xl overflow-hidden backdrop-blur-xl z-50"onClick={(e) => e.stopPropagation()}>11 unmodified linesclassName="w-full px-3 py-2 rounded-lg text-xs bg-[#2d2d30] text-[#f5f5f7] border border-[#424245] focus:outline-none focus:border-white/50 font-normal mb-3"disabled={isImporting}/>{/* Import Action Options */}{importUrl.includes('huggingface.co/spaces/') && (<div className="mb-3 space-y-2"><p className="text-[10px] font-medium text-[#86868b] mb-2">Import Mode:</p>{/* Update Space (only for owners) */}{isSpaceOwner && (<label className="flex items-start gap-2 cursor-pointer group">12 unmodified lines</div></label>)}{/* Duplicate Space */}<label className="flex items-start gap-2 cursor-pointer group"><input10 unmodified lines</p></div></label>{/* Create PR */}<label className="flex items-start gap-2 cursor-pointer group"><input10 unmodified lines</p></div></label>{importAction === 'pr' && (<p className="text-[10px] text-[#86868b] ml-6 mt-1">⚠️ Requires space owner to enable PRs1 unmodified line)}</div>)}{importError && (<p className="text-xs text-red-400 mb-2">{importError}</p>)}<div className="flex gap-2"><buttononClick={handleImportProject}48 unmodified lines<span className="absolute inset-0 bg-gradient-to-r from-pink-500 via-purple-500 to-indigo-500 rounded-full blur-sm opacity-75 animate-pulse"></span></span></button>{/* Redesign Dialog */}{showRedesignDialog && (<divclassName="absolute top-full left-0 mt-2 w-80 bg-[#1d1d1f] border border-[#424245] rounded-xl shadow-2xl overflow-hidden backdrop-blur-xl z-50"onClick={(e) => e.stopPropagation()}>8 unmodified linesclassName="w-full px-3 py-2 rounded-lg text-xs bg-[#2d2d30] text-[#f5f5f7] border border-[#424245] focus:outline-none focus:border-white/50 font-normal mb-3"disabled={isRedesigning}/>{/* PR Option */}<label className="flex items-center gap-2 mb-1 cursor-pointer"><input7 unmodified linesCreate Pull Request on original space</span></label>{createPR && (<p className="text-[10px] text-[#86868b] mb-2 ml-6">⚠️ Note: PR creation requires space owner to enable PRs. If disabled, uncheck this to duplicate the space instead.</p>)}{redesignError && (<p className="text-xs text-red-400 mb-2">{redesignError}</p>)}17 unmodified lines</button></div><p className="text-[10px] text-[#86868b] mt-3">{createPR? 'Creates a Pull Request on the original space with your redesign': 'Import and automatically redesign with modern, mobile-friendly design'}</p>29 unmodified lines</button></>)}{/* Send button - Apple style */}<buttontype="submit"8 unmodified lines</div></div></div>{!isAuthenticated && (<div className="mt-4 text-center"><p className="text-xs text-[#86868b]">45 unmodified lines<span className="px-1.5 py-0.5 bg-[#2d2d30] text-[#86868b] text-[9px] rounded-full font-medium">{app.sdk}</span>{app.tags?.slice(0, 2).map((tag: string) =>tag !== 'anycoder' && tag !== app.sdk && tag !== 'region:us' && (<span key={tag} className="px-1.5 py-0.5 bg-[#2d2d30] text-[#86868b] text-[9px] rounded-full font-medium">{tag}
frontend/src/app/page.tsx+106-109
frontend/src/components/ControlPanel.tsx+130-132
frontend/src/components/LandingPage.tsx+117-119