fix
Browse filesFiles changed (4)
914 unmodified lines9159169179189199209211 unmodified line9239249259269279289299309319329339349357 unmodified lines943944945946947948914 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 frontendif request.history and auth.username:print(f"[Deploy] Checking history for deployed spaces ({len(request.history)} messages)...")for msg in request.history:role = msg.get('role', '')content = msg.get('content', '')1 unmodified line# Check for deployment confirmationsif role == 'assistant' and ('✅ Deployed!' in content or '✅ Updated!' in content):import rematch = 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}")if not existing_repo_id:existing_repo_id = history_space_idbreak# Check for importselif role == 'user' and 'import' in content.lower():7 unmodified linesif not existing_repo_id:existing_repo_id = imported_spacebreak# PRIORITY 2: Check session for previously deployed spaces (fallback)# This helps when history isn't passed from frontend914 unmodified lines9159169179189199209219229239249259269279289299309319329331 unmodified line9359369379389399409419429439449459469479489499509519527 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 frontendif request.history and auth.username: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 debuggingfor 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 confirmationsif role == 'assistant' and ('✅ Deployed!' in content or '✅ Updated!' in content):import reprint(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] ✅ EXTRACTED space ID from history: {history_space_id}")if not existing_repo_id:existing_repo_id = history_space_idprint(f"[Deploy] ✅ WILL UPDATE EXISTING SPACE: {existing_repo_id}")breakelse:print(f"[Deploy] ⚠️ Deployment message found but couldn't extract space ID")# Check for importselif role == 'user' and 'import' in content.lower():7 unmodified linesif not existing_repo_id:existing_repo_id = imported_spacebreakelse: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 frontend
432 unmodified lines43343443543643743843944044144244344444532 unmodified lines478479480481482483484485486487488489432 unmodified linesconsole.log('[Deploy] Username:', currentUsername);console.log('[Deploy] Existing space from history:', existingSpace);console.log('[Deploy] Will create new space?', !existingSpace);console.log('[Deploy] =================================================================');// Build deploy request, omitting undefined fieldsconst deployRequest: any = {code: generatedCode,language: selectedLanguage,history: messages.map(msg => ({ role: msg.role, content: msg.content })) // Pass full chat history};// Only include optional fields if they have values32 unmodified lines}}// Add deployment message to chat (EXACT Gradio format with markdown link)const deployMessage: Message = {role: 'assistant',content: existingSpace? `Updated! [Open your app here](${response.space_url})`: `Deployed! [Open your app here](${response.space_url})`,timestamp: new Date().toISOString(),};setMessages((prev) => [...prev, deployMessage]);432 unmodified lines43343443543643743843944044144244344444544644744844945045145232 unmodified lines485486487488489490491492493494495496432 unmodified linesconsole.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 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 values32 unmodified lines}}// 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]);
12345647 unmodified lines54555657585960213 unmodified lines274275276277278279280// API client for AnyCoder backendimport axios, { AxiosInstance } from 'axios';import type {Model,AuthStatus,47 unmodified lines// Add auth token to requests if availablethis.client.interceptors.request.use((config) => {if (this.token) {config.headers.Authorization = `Bearer ${this.token}`;}return config;213 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json',...(this.token ? { 'Authorization': `Bearer ${this.token}` } : {}),},body: JSON.stringify(request),signal: abortController.signal,123456747 unmodified lines555657585960616263646566213 unmodified lines280281282283284285286287// API client for AnyCoder backendimport axios, { AxiosInstance } from 'axios';import { getStoredSessionToken } from './auth'; // NEW: Import session tokenimport type {Model,AuthStatus,47 unmodified lines// Add auth token to requests if availablethis.client.interceptors.request.use((config) => {// Use session token instead of OAuth token for session trackingconst sessionToken = getStoredSessionToken();if (sessionToken) {config.headers.Authorization = `Bearer ${sessionToken}`;} else if (this.token) {// Fallback to OAuth token if no session tokenconfig.headers.Authorization = `Bearer ${this.token}`;}return config;213 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json',...(getStoredSessionToken() ? { 'Authorization': `Bearer ${getStoredSessionToken()}` } :this.token ? { 'Authorization': `Bearer ${this.token}` } : {}),},body: JSON.stringify(request),signal: abortController.signal,
12345664 unmodified lines717273747576777850 unmodified lines1291301311321331349 unmodified lines144145146147148149// HuggingFace OAuth authentication utilities (Server-side flow for Docker Spaces)const STORAGE_KEY = 'hf_oauth_token';const USER_INFO_KEY = 'hf_user_info';const DEV_MODE_KEY = 'hf_dev_mode';const API_BASE = '/api';64 unmodified linesuserInfo,};// Store the OAuth resultstoreOAuthData(oauthResult);// Clean up URLwindow.history.replaceState({}, document.title, window.location.pathname);50 unmodified linesexport function logout(): void {if (typeof window !== 'undefined') {localStorage.removeItem(STORAGE_KEY);localStorage.removeItem(USER_INFO_KEY);localStorage.removeItem(DEV_MODE_KEY);}9 unmodified lines}}/*** Get stored access token*/123456764 unmodified lines72737475767778798050 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 linesuserInfo,};// Store the OAuth result AND session tokenstoreOAuthData(oauthResult);storeSessionToken(sessionToken); // NEW: Store session UUID// Clean up URLwindow.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 tokenlocalStorage.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