fix
Browse filesFiles changed (4)
914 unmodified lines9159169179189189199209219229239249259269279289299309319329331 unmodified line9359369379389399409419429299439449459469479489499509519527 unmodified lines960961962963964965966967968969970914 unmodified lines # PRIORITY 1: Check history for deployed/imported spaces (like Gradio version does) # This is more reliable than session tracking since history persists in frontend if request.history and auth.username: print(f"[Deploy] Checking history for deployed spaces ({len(request.history)} messages)...") print(f"[Deploy] ========== CHECKING HISTORY ==========") print(f"[Deploy] History length: {len(request.history)} messages") print(f"[Deploy] Username: {auth.username}") # Log each message in history for debugging for i, msg in enumerate(request.history): role = msg.get('role', 'unknown') content = msg.get('content', '') content_preview = content[:100] if content else '' print(f"[Deploy] Message {i+1}: role={role}, content_preview='{content_preview}...'") print(f"[Deploy] ==========================================") for msg in request.history: role = msg.get('role', '') content = msg.get('content', '')1 unmodified line # Check for deployment confirmations if role == 'assistant' and ('✅ Deployed!' in content or '✅ Updated!' in content): import re print(f"[Deploy] 🔍 Found deployment message in history!") print(f"[Deploy] Content: {content[:200]}") match = re.search(r'huggingface\.co/spaces/([^/\s\)]+/[^/\s\)]+)', content) if match: history_space_id = match.group(1) print(f"[Deploy] ✅ Found deployed space in history: {history_space_id}") print(f"[Deploy] ✅ EXTRACTED space ID from history: {history_space_id}") if not existing_repo_id: existing_repo_id = history_space_id print(f"[Deploy] ✅ WILL UPDATE EXISTING SPACE: {existing_repo_id}") break else: print(f"[Deploy] ⚠️ Deployment message found but couldn't extract space ID") # Check for imports elif role == 'user' and 'import' in content.lower():7 unmodified lines if not existing_repo_id: existing_repo_id = imported_space break else: if not request.history: print(f"[Deploy] ⚠️ No history provided in request") if not auth.username: print(f"[Deploy] ⚠️ No username available") # PRIORITY 2: Check session for previously deployed spaces (fallback) # This helps when history isn't passed from frontend432 unmodified lines43343443543643743843944044144244344444544644744844244945045145232 unmodified lines485486487481488489490491485486492493494495496432 unmodified lines console.log('[Deploy] Username:', currentUsername); console.log('[Deploy] Existing space from history:', existingSpace); console.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 sending const 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 fields const deployRequest: any = { code: generatedCode, language: selectedLanguage, history: messages.map(msg => ({ role: msg.role, content: msg.content })) // Pass full chat history history: historyToSend // Use the variable we just logged }; // Only include optional fields if they have values32 unmodified lines } } // Add deployment message to chat (EXACT Gradio format with markdown link) // Add deployment message to chat (EXACT format backend expects) const deployMessage: Message = { role: 'assistant', content: existingSpace ? `Updated! [Open your app here](${response.space_url})` : `Deployed! [Open your app here](${response.space_url})`, ? `✅ Updated! View your space at: ${response.space_url}` : `✅ Deployed! View your space at: ${response.space_url}`, timestamp: new Date().toISOString(), }; setMessages((prev) => [...prev, deployMessage]);123456747 unmodified lines55565758596061576263646566213 unmodified lines280281282283277284285286287// API client for AnyCoder backend
import axios, { AxiosInstance } from 'axios';import { getStoredSessionToken } from './auth'; // NEW: Import session tokenimport type { Model, AuthStatus,47 unmodified lines
// Add auth token to requests if available this.client.interceptors.request.use((config) => { // Use session token instead of OAuth token for session tracking const sessionToken = getStoredSessionToken(); if (sessionToken) { config.headers.Authorization = `Bearer ${sessionToken}`; if (this.token) { } else if (this.token) { // Fallback to OAuth token if no session token config.headers.Authorization = `Bearer ${this.token}`; } return config;213 unmodified lines method: 'POST', headers: { 'Content-Type': 'application/json', ...(getStoredSessionToken() ? { 'Authorization': `Bearer ${getStoredSessionToken()}` } : ...(this.token ? { 'Authorization': `Bearer ${this.token}` } : {}), this.token ? { 'Authorization': `Bearer ${this.token}` } : {}), }, body: JSON.stringify(request), signal: abortController.signal,123456764 unmodified lines7273747475767778798050 unmodified lines1311321331341351361379 unmodified lines147148149150151152153154155156157158159160161162163164165166167168169170171// HuggingFace OAuth authentication utilities (Server-side flow for Docker Spaces)
const STORAGE_KEY = 'hf_oauth_token';const SESSION_KEY = 'hf_session_token'; // NEW: Store session UUIDconst USER_INFO_KEY = 'hf_user_info';const DEV_MODE_KEY = 'hf_dev_mode';const API_BASE = '/api';64 unmodified lines userInfo, }; // Store the OAuth result // Store the OAuth result AND session token storeOAuthData(oauthResult); storeSessionToken(sessionToken); // NEW: Store session UUID // Clean up URL window.history.replaceState({}, document.title, window.location.pathname);50 unmodified linesexport function logout(): void { if (typeof window !== 'undefined') { localStorage.removeItem(STORAGE_KEY); localStorage.removeItem(SESSION_KEY); // NEW: Clear session token localStorage.removeItem(USER_INFO_KEY); localStorage.removeItem(DEV_MODE_KEY); }9 unmodified lines }}
/** * Store session token in localStorage */function storeSessionToken(sessionToken: string): void { if (typeof window !== 'undefined') { localStorage.setItem(SESSION_KEY, sessionToken); }}
/** * Get stored session token */export function getStoredSessionToken(): string | null { if (typeof window !== 'undefined') { return localStorage.getItem(SESSION_KEY); } return null;}
/** * Get stored access token */backend_api.py+24-2
frontend/src/app/page.tsx+11-4
frontend/src/lib/api.ts+9-2
frontend/src/lib/auth.ts+23-1