Add follow-up deployment support: Update existing spaces instead of creating new ones
Browse filesImplemented the same pattern as original deploy.py where follow-up prompts
update the existing deployed space with new commits instead of creating new spaces.
backend_deploy.py changes:
- Added existing_repo_id parameter to deploy_to_huggingface_space()
- Added commit_message parameter for custom commit messages
- Added is_update logic to detect updates vs new deployments
- Skip create_repo() when updating existing space
- Use appropriate commit message: "Update from anycoder" vs "Deploy from anycoder"
- Return different success message: "Updated" vs "Deployed"
- Skip 2-second wait for README on updates (already exists)
backend_api.py changes:
- Updated DeploymentRequest model to include:
* existing_repo_id (optional) - for explicitly updating a space
* commit_message (optional) - custom commit message
* space_name now optional (not needed for updates)
- Added deployed_spaces tracking to user_sessions
- Deploy endpoint now:
* Checks session for previously deployed spaces
* Automatically finds most recent space for same language
* Passes existing_repo_id to deployment function
* Tracks deployed spaces after successful deployment
* Returns repo_id in response for frontend tracking
Deployment flow:
1. First deployment: Creates new space, tracks in session
2. Follow-up for same language: Finds existing space from session
3. Updates that space with new commit (preserves git history)
4. Each update creates a new commit in the space's git repo
This matches the original Gradio UI behavior where:
- Initial "make a gradio app" creates new space
- Follow-up "add a button" updates the same space
- History is preserved with proper git commits
Session tracking ensures follow-up prompts in the same session
automatically update the correct space without user intervention.
Files changed (2)
- backend_api.py+47-3
- backend_deploy.py+59-40
109 unmodified lines110111112113114115116117118154 unmodified lines273274275276277278274 unmodified lines5535545555565575582 unmodified lines561562563564565566567568569570571572573574109 unmodified linesclass DeploymentRequest(BaseModel):code: strspace_name: strlanguage: strrequirements: Optional[str] = Noneclass AuthStatus(BaseModel):154 unmodified lines"access_token": access_token,"user_info": user_info,"timestamp": datetime.now(),}# Redirect to frontend with session token274 unmodified linesprint(f"[Deploy] Attempting deployment with token (first 10 chars): {user_token[:10]}...")# Use the standalone deployment functionsuccess, message, space_url = deploy_to_huggingface_space(code=request.code,2 unmodified linestoken=user_token,username=auth.username,description=request.description if hasattr(request, 'description') else None,private=False)if success:return {"success": True,"space_url": space_url,"message": message}else:# Provide user-friendly error message based on the error109 unmodified lines110111112113114115116117118119120154 unmodified lines275276277278279280281282274 unmodified lines5575585595605615625635645655665675685695705715725735745755765775782 unmodified lines581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618109 unmodified linesclass DeploymentRequest(BaseModel):code: strspace_name: Optional[str] = Nonelanguage: strrequirements: Optional[str] = Noneexisting_repo_id: Optional[str] = None # For updating existing spacescommit_message: Optional[str] = Noneclass AuthStatus(BaseModel):154 unmodified lines"access_token": access_token,"user_info": user_info,"timestamp": datetime.now(),"username": user_info.get("name") or user_info.get("preferred_username") or "user","deployed_spaces": [] # Track deployed spaces for follow-up updates}# Redirect to frontend with session token274 unmodified linesprint(f"[Deploy] Attempting deployment with token (first 10 chars): {user_token[:10]}...")# Check for existing deployed space in this sessionexisting_repo_id = request.existing_repo_idsession_token = authorization.replace("Bearer ", "") if authorization else None# If no existing_repo_id provided, check session for previously deployed spacesif not existing_repo_id and session_token and session_token in user_sessions:session = user_sessions[session_token]deployed_spaces = session.get("deployed_spaces", [])# Find the most recent space for this languagefor space in reversed(deployed_spaces):if space.get("language") == request.language:existing_repo_id = space.get("repo_id")print(f"[Deploy] Found existing space for {request.language}: {existing_repo_id}")break# Use the standalone deployment functionsuccess, message, space_url = deploy_to_huggingface_space(code=request.code,2 unmodified linestoken=user_token,username=auth.username,description=request.description if hasattr(request, 'description') else None,private=False,existing_repo_id=existing_repo_id,commit_message=request.commit_message)if success:# Track deployed space in session for follow-up updatesif session_token and session_token in user_sessions:repo_id = space_url.split("/spaces/")[-1] if space_url else Noneif repo_id:session = user_sessions[session_token]deployed_spaces = session.get("deployed_spaces", [])# Update or add the spacespace_entry = {"repo_id": repo_id,"language": request.language,"timestamp": datetime.now()}# Remove old entry for same repo_id if existsdeployed_spaces = [s for s in deployed_spaces if s.get("repo_id") != repo_id]deployed_spaces.append(space_entry)session["deployed_spaces"] = deployed_spacesprint(f"[Deploy] Tracked space in session: {repo_id}")return {"success": True,"space_url": space_url,"message": message,"repo_id": repo_id if 'repo_id' in locals() else None}else:# Provide user-friendly error message based on the error
255 unmodified lines2562572582592602612622632642652662672682692702712722732746 unmodified lines28128228328428528628728828929029129229329429529629729829930030130230367 unmodified lines371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416255 unmodified linestoken: Optional[str] = None,username: Optional[str] = None,description: Optional[str] = None,private: bool = False) -> Tuple[bool, str, Optional[str]]:"""Deploy code to HuggingFace SpacesArgs:code: Generated code to deploylanguage: Target language/framework (html, gradio, streamlit, react, transformers.js, comfyui)space_name: Name for the space (auto-generated if None)token: HuggingFace API tokenusername: HuggingFace usernamedescription: Space descriptionprivate: Whether to make the space privateReturns:Tuple of (success: bool, message: str, space_url: Optional[str])6 unmodified linestry:api = HfApi(token=token)# Get username if not providedif not username:try:user_info = api.whoami()username = user_info.get("name") or user_info.get("preferred_username") or "user"except Exception as e:return False, f"Failed to get user info: {str(e)}", None# Generate space name if not providedif not space_name:space_name = f"anycoder-{uuid.uuid4().hex[:8]}"# Clean space name (no spaces, lowercase, alphanumeric + hyphens)space_name = re.sub(r'[^a-z0-9-]', '-', space_name.lower())space_name = re.sub(r'-+', '-', space_name).strip('-')repo_id = f"{username}/{space_name}"# Detect SDKsdk = detect_sdk_from_code(code, language)67 unmodified lines# Don't create README - HuggingFace will auto-generate it# We'll add the anycoder tag after deployment# Create the spacetry:api.create_repo(repo_id=repo_id,repo_type="space",space_sdk=sdk,private=private,exist_ok=False)except Exception as e:if "already exists" in str(e).lower():# Space exists, we'll update itpasselse:return False, f"Failed to create space: {str(e)}", None# Upload all filestry:api.upload_folder(folder_path=str(temp_path),repo_id=repo_id,repo_type="space",commit_message="Deploy from anycoder")except Exception as e:return False, f"Failed to upload files: {str(e)}", None# After successful upload, modify the auto-generated README to add anycoder tag# HuggingFace automatically creates README.md when space is created# Wait a moment for it to be generated, then modify ittry:import timetime.sleep(2) # Give HF time to generate READMEadd_anycoder_tag_to_readme(api, repo_id, app_port)except Exception as e:# Don't fail deployment if README modification failsprint(f"Warning: Could not add anycoder tag to README: {e}")space_url = f"https://huggingface.co/spaces/{repo_id}"return True, f"✅ Successfully deployed to {repo_id}!", space_urlexcept Exception as e:return False, f"Deployment error: {str(e)}", None255 unmodified lines2562572582592602612622632642652662672682692702712722732742752762772786 unmodified lines28528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531667 unmodified lines384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435255 unmodified linestoken: Optional[str] = None,username: Optional[str] = None,description: Optional[str] = None,private: bool = False,existing_repo_id: Optional[str] = None,commit_message: Optional[str] = None) -> Tuple[bool, str, Optional[str]]:"""Deploy code to HuggingFace Spaces (create new or update existing)Args:code: Generated code to deploylanguage: Target language/framework (html, gradio, streamlit, react, transformers.js, comfyui)space_name: Name for the space (auto-generated if None, ignored if existing_repo_id provided)token: HuggingFace API tokenusername: HuggingFace usernamedescription: Space descriptionprivate: Whether to make the space private (only for new spaces)existing_repo_id: If provided (username/space-name), updates this space instead of creating new onecommit_message: Custom commit message (defaults to "Deploy from anycoder" or "Update from anycoder")Returns:Tuple of (success: bool, message: str, space_url: Optional[str])6 unmodified linestry:api = HfApi(token=token)# Determine if this is an update or new deploymentis_update = existing_repo_id is not Noneif is_update:# Use existing reporepo_id = existing_repo_idspace_name = existing_repo_id.split('/')[-1]username = existing_repo_id.split('/')[0] if '/' in existing_repo_id else usernameelse:# Get username if not providedif not username:try:user_info = api.whoami()username = user_info.get("name") or user_info.get("preferred_username") or "user"except Exception as e:return False, f"Failed to get user info: {str(e)}", None# Generate space name if not providedif not space_name:space_name = f"anycoder-{uuid.uuid4().hex[:8]}"# Clean space name (no spaces, lowercase, alphanumeric + hyphens)space_name = re.sub(r'[^a-z0-9-]', '-', space_name.lower())space_name = re.sub(r'-+', '-', space_name).strip('-')repo_id = f"{username}/{space_name}"# Detect SDKsdk = detect_sdk_from_code(code, language)67 unmodified lines# Don't create README - HuggingFace will auto-generate it# We'll add the anycoder tag after deployment# Create the space (only for new deployments)if not is_update:try:api.create_repo(repo_id=repo_id,repo_type="space",space_sdk=sdk,private=private,exist_ok=False)except Exception as e:if "already exists" in str(e).lower():# Space exists, treat as updateis_update = Trueelse:return False, f"Failed to create space: {str(e)}", None# Upload all filesif not commit_message:commit_message = "Update from anycoder" if is_update else "Deploy from anycoder"try:api.upload_folder(folder_path=str(temp_path),repo_id=repo_id,repo_type="space",commit_message=commit_message)except Exception as e:return False, f"Failed to upload files: {str(e)}", None# After successful upload, modify the auto-generated README to add anycoder tag# For new spaces: HF auto-generates README, wait and modify it# For updates: README should already exist, just add tag if missingtry:import timeif not is_update:time.sleep(2) # Give HF time to generate README for new spacesadd_anycoder_tag_to_readme(api, repo_id, app_port)except Exception as e:# Don't fail deployment if README modification failsprint(f"Warning: Could not add anycoder tag to README: {e}")space_url = f"https://huggingface.co/spaces/{repo_id}"action = "Updated" if is_update else "Deployed"return True, f"✅ {action} successfully to {repo_id}!", space_urlexcept Exception as e:return False, f"Deployment error: {str(e)}", None