update
Browse filesFiles changed (3)
89 unmodified lines90919293949596393 unmodified lines49049149249349449549649749849950050150250350450589 unmodified lines# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [{"name": "Gemini 3.0 Pro", "id": "gemini-3.0-pro", "description": "Google Gemini 3.0 Pro via Poe with advanced reasoning"},{"name": "Grok 4.1 Fast", "id": "x-ai/grok-4.1-fast", "description": "Grok 4.1 Fast model via OpenRouter"},{"name": "MiniMax M2", "id": "MiniMaxAI/MiniMax-M2", "description": "MiniMax M2 model via HuggingFace InferenceClient with Novita provider"},{"name": "DeepSeek V3.2-Exp", "id": "deepseek-ai/DeepSeek-V3.2-Exp", "description": "DeepSeek V3.2 Experimental via HuggingFace"},{"name": "DeepSeek R1", "id": "deepseek-ai/DeepSeek-R1-0528", "description": "DeepSeek R1 model for code generation"},393 unmodified linesyield f"data: {completion_data}\n\n"except Exception as e:error_data = json.dumps({"type": "error","message": str(e)})yield f"data: {error_data}\n\n"except Exception as e:error_data = json.dumps({"type": "error","message": f"Generation error: {str(e)}"})yield f"data: {error_data}\n\n"89 unmodified lines90919293949596393 unmodified lines49049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755889 unmodified lines# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [{"name": "Gemini 3.0 Pro", "id": "gemini-3.0-pro", "description": "Google Gemini 3.0 Pro via Poe with advanced reasoning"},{"name": "Grok 4.1 Fast", "id": "x-ai/grok-4.1-fast", "description": "Grok 4.1 Fast model via OpenRouter (20 req/min on free tier)"},{"name": "MiniMax M2", "id": "MiniMaxAI/MiniMax-M2", "description": "MiniMax M2 model via HuggingFace InferenceClient with Novita provider"},{"name": "DeepSeek V3.2-Exp", "id": "deepseek-ai/DeepSeek-V3.2-Exp", "description": "DeepSeek V3.2 Experimental via HuggingFace"},{"name": "DeepSeek R1", "id": "deepseek-ai/DeepSeek-R1-0528", "description": "DeepSeek R1 model for code generation"},393 unmodified linesyield f"data: {completion_data}\n\n"except Exception as e:# Handle rate limiting and other API errorserror_message = str(e)is_rate_limit = Falseerror_type = type(e).__name__# Check for OpenAI SDK rate limit errorsif error_type == "RateLimitError" or "rate_limit" in error_type.lower():is_rate_limit = True# Check if this is a rate limit error (429 status code)elif hasattr(e, 'status_code') and e.status_code == 429:is_rate_limit = True# Check error message for rate limit indicatorselif "429" in error_message or "rate limit" in error_message.lower() or "too many requests" in error_message.lower():is_rate_limit = Trueif is_rate_limit:# Try to extract retry-after header or messageretry_after = Noneif hasattr(e, 'response') and e.response:retry_after = e.response.headers.get('Retry-After') or e.response.headers.get('retry-after')# Also check if the error object has retry_afterelif hasattr(e, 'retry_after'):retry_after = str(e.retry_after)if selected_model_id == "x-ai/grok-4.1-fast" or selected_model_id.startswith("openrouter/"):error_message = "⏱️ Rate limit exceeded for OpenRouter model"if retry_after:error_message += f". Please wait {retry_after} seconds before trying again."else:error_message += ". Free tier allows up to 20 requests per minute. Please wait a moment and try again."else:error_message = f"⏱️ Rate limit exceeded. Please wait before trying again."if retry_after:error_message += f" Retry after {retry_after} seconds."# Check for other common API errorselif hasattr(e, 'status_code'):if e.status_code == 401:error_message = "❌ Authentication failed. Please check your API key."elif e.status_code == 403:error_message = "❌ Access forbidden. Please check your API key permissions."elif e.status_code == 500 or e.status_code == 502 or e.status_code == 503:error_message = "❌ Service temporarily unavailable. Please try again later."error_data = json.dumps({"type": "error","message": error_message})yield f"data: {error_data}\n\n"except Exception as e:# Fallback error handlingerror_message = str(e)# Check if it's a rate limit error in the exception messageif "429" in error_message or "rate limit" in error_message.lower() or "too many requests" in error_message.lower():if selected_model_id == "x-ai/grok-4.1-fast" or selected_model_id.startswith("openrouter/"):error_message = "⏱️ Rate limit exceeded for OpenRouter model. Free tier allows up to 20 requests per minute. Please wait a moment and try again."else:error_message = "⏱️ Rate limit exceeded. Please wait before trying again."error_data = json.dumps({"type": "error","message": f"Generation error: {error_message}"})yield f"data: {error_data}\n\n"
58 unmodified lines5960616263643 unmodified lines68697071727374753 unmodified lines79808182838485863 unmodified lines9091929394959697989911 unmodified lines1111121131141151161171181191201211221231241251261271284 unmodified lines1331341351361371381391401411421431443 unmodified lines14814915015115215315415515615715815916016158 unmodified lines// Track if we've attempted to fetch username to avoid repeated failuresconst usernameFetchAttemptedRef = useRef(false);// Check auth on mount and handle OAuth callbackuseEffect(() => {3 unmodified lines// initializeOAuth already handles this, but we call checkAuth to sync stateconst urlParams = new URLSearchParams(window.location.search);if (urlParams.get('session')) {// OAuth callback - reset username fetch attempt and check auth after a brief delayusernameFetchAttemptedRef.current = false;setTimeout(() => checkAuth(), 200);}}, []); // Only run once on mount3 unmodified linesuseEffect(() => {const handleStorageChange = (e: StorageEvent) => {if (e.key === 'hf_oauth_token' || e.key === 'hf_user_info') {// Reset username fetch attempt when storage changesusernameFetchAttemptedRef.current = false;checkAuth();}};3 unmodified lines}, []);// Listen for window focus (user returns to tab after OAuth redirect)useEffect(() => {const handleFocus = () => {// Reset username fetch attempt on focus (user might have logged in elsewhere)usernameFetchAttemptedRef.current = false;checkAuth();};11 unmodified linesif (token) {apiClient.setToken(token);// Get username from auth status (only if we don't have it yet and haven't failed)// This is a one-time fetch per session, not pollingif (!username && !usernameFetchAttemptedRef.current) {usernameFetchAttemptedRef.current = true;try {const authStatus = await apiClient.getAuthStatus();if (authStatus.username) {setUsername(authStatus.username);}} catch (error: any) {// Silently handle connection errors - don't spam console// Connection errors mean backend isn't available, which is OK for client-side authconst isConnectionError =error.code === 'ECONNABORTED' ||error.code === 'ECONNRESET' ||4 unmodified lineserror.response?.status === 503 ||error.response?.status === 502;if (!isConnectionError) {// Only log non-connection errorsconsole.error('Failed to get username:', error);}// Reset attempt flag so we can try again later (e.g., when backend comes up)usernameFetchAttemptedRef.current = false;}}} else {3 unmodified linessetUsername(null);}usernameFetchAttemptedRef.current = false;}} else {// Not authenticated - clear username and reset fetch attemptapiClient.setToken(null);if (username) {setUsername(null);}usernameFetchAttemptedRef.current = false;}};58 unmodified lines59606162636465663 unmodified lines7071727374757677783 unmodified lines82838485868788899091923 unmodified lines9697989910010110210310410510610710810911011111 unmodified lines1231241251261271281291301311321331341351361371381391404 unmodified lines1451461471481491501511521531541551561571581591603 unmodified lines16416516616716816917017117217317417517617717817958 unmodified lines// Track if we've attempted to fetch username to avoid repeated failuresconst usernameFetchAttemptedRef = useRef(false);// Track if backend appears to be unavailable (to avoid repeated failed requests)const backendUnavailableRef = useRef(false);// Check auth on mount and handle OAuth callbackuseEffect(() => {3 unmodified lines// initializeOAuth already handles this, but we call checkAuth to sync stateconst urlParams = new URLSearchParams(window.location.search);if (urlParams.get('session')) {// OAuth callback - reset both flags and check auth after a brief delayusernameFetchAttemptedRef.current = false;backendUnavailableRef.current = false; // Reset backend status on OAuth callbacksetTimeout(() => checkAuth(), 200);}}, []); // Only run once on mount3 unmodified linesuseEffect(() => {const handleStorageChange = (e: StorageEvent) => {if (e.key === 'hf_oauth_token' || e.key === 'hf_user_info') {// Only reset username fetch if we have a token (might be logging in)if (e.newValue) {usernameFetchAttemptedRef.current = false;backendUnavailableRef.current = false; // Reset backend status on login}checkAuth();}};3 unmodified lines}, []);// Listen for window focus (user returns to tab after OAuth redirect)// Only check if backend was available before or if we're authenticated with tokenuseEffect(() => {const handleFocus = () => {// Only reset and check if we're authenticated (might have logged in elsewhere)// Don't reset if backend is known to be unavailable and we're not authenticatedconst authenticated = checkIsAuthenticated();if (authenticated) {usernameFetchAttemptedRef.current = false;backendUnavailableRef.current = false; // Reset backend status - might be back up}checkAuth();};11 unmodified linesif (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) {usernameFetchAttemptedRef.current = true;try {const authStatus = await apiClient.getAuthStatus();if (authStatus.username) {setUsername(authStatus.username);backendUnavailableRef.current = false; // Backend is working}} catch (error: any) {// Check if this is a connection errorconst isConnectionError =error.code === 'ECONNABORTED' ||error.code === 'ECONNRESET' ||4 unmodified lineserror.response?.status === 503 ||error.response?.status === 502;if (isConnectionError) {// Mark backend as unavailable to avoid repeated requestsbackendUnavailableRef.current = true;// Don't reset attempt flag - keep it true so we don't retry until explicitly reset// This prevents repeated failed requests when backend is down} else {// Non-connection error - log it and reset attempt flagconsole.error('Failed to get username:', error);usernameFetchAttemptedRef.current = false;}}}} else {3 unmodified linessetUsername(null);}usernameFetchAttemptedRef.current = false;backendUnavailableRef.current = false;}} else {// Not authenticated - clear username and reset flagsapiClient.setToken(null);if (username) {setUsername(null);}usernameFetchAttemptedRef.current = false;// Keep backendUnavailableRef as is - it's useful information even when not authenticated}};
176 unmodified lines177178179180181182176 unmodified linessignal: abortController.signal,}).then(async (response) => {if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}176 unmodified lines177178179180181182183184185186187188176 unmodified linessignal: abortController.signal,}).then(async (response) => {// Handle rate limit errors before parsing responseif (response.status === 429) {onError('⏱️ Rate limit exceeded. Free tier allows up to 20 requests per minute. Please wait a moment and try again.');return;}if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}
backend_api.py+56-3
frontend/src/app/page.tsx+33-15
frontend/src/lib/api.ts+6