# app.py """ Streamlit frontend application for orchestrating an AI-driven SDLC workflow. This application manages the user interface, state transitions, and calls backend logic functions defined in SDLC.py to generate project artifacts. """ import streamlit as st import os import shutil import logging from datetime import datetime import time import zipfile # Standard library zipfile # --- Import core logic from SDLC.py --- try: import SDLC from SDLC import ( # State and Models MainState, GeneratedCode, PlantUMLCode, TestCase, CodeFile, TestCases, # NEW: Initialization function initialize_llm_clients, # Workflow Functions generate_questions, refine_prompt, generate_initial_user_stories, generate_user_story_feedback, refine_user_stories, save_final_user_story, generate_initial_product_review, generate_product_review_feedback, refine_product_review, save_final_product_review, generate_initial_design_doc, generate_design_doc_feedback, refine_design_doc, save_final_design_doc, select_uml_diagrams, generate_initial_uml_codes, generate_uml_feedback, refine_uml_codes, save_final_uml_diagrams, generate_initial_code, web_search_code, generate_code_feedback, refine_code, code_review, security_check, refine_code_with_reviews, save_review_security_outputs, generate_initial_test_cases, generate_test_cases_feedback, refine_test_cases_and_code, save_testing_outputs, generate_initial_quality_analysis, generate_quality_feedback, refine_quality_and_code, save_final_quality_analysis, generate_initial_deployment, generate_deployment_feedback, refine_deployment, save_final_deployment_plan, # Message Types HumanMessage, AIMessage ) logging.info("Successfully imported components from SDLC.py.") except ImportError as e: st.error(f"Import Error: {e}. Critical file 'SDLC.py' not found or contains errors.") logging.critical(f"Failed to import SDLC.py: {e}", exc_info=True) st.stop() except Exception as e: st.error(f"An unexpected error occurred during import from SDLC: {e}") logging.critical(f"Unexpected error during import from SDLC: {e}", exc_info=True) st.stop() # --- Application Setup --- st.set_page_config(layout="wide", page_title="AI SDLC Workflow") logger = logging.getLogger(__name__) if not logger.handlers: logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger.info("Streamlit app logger configured.") # --- Constants for Configuration --- # Define available providers and their models AVAILABLE_MODELS = { "OpenAI": [ "gpt-4o-mini", "gpt-4o-mini-2024-07-18", "gpt-4o", "gpt-4o-2024-08-06", "o1-mini", "o1-mini-2024-09-12", "o3-mini", "o3-mini-2025-01-31", ], "Groq": [ "llama3-8b-8192", "llama3-70b-8192", "llama-3.1-8b-instant", "llama-3.2-1b-preview", "llama-3.2-3b-preview", "llama-3.3-70b-specdec", "llama-3.3-70b-versatile", "mistral-saba-24b", "gemma2-9b-it", "deepseek-r1-distill-llama-70b", "deepseek-r1-distill-qwen-32b", "qwen-2.5-32b", "qwen-2.5-coder-32b", "qwen-qwq-32b", "mixtral-8x7b-32768", ], "Google": [ "gemini-1.5-pro-latest", "gemini-1.5-flash-latest", "gemini-1.0-pro", "gemini-1.0-flash", "gemini-2.5-pro-exp-03-25", "gemini-2.0-flash", ], "Anthropic": [ # Use API Identifiers (usually include date) "claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307", "claude-3-5-haiku-latest", "claude-3-5-sonnet-latest", "claude-3-7-sonnet-latest" ], "xAI": [ "grok-1", # Primary model available via API "grok-2-latest", "grok-3", "grok-3-mini" ] } LLM_PROVIDERS = list(AVAILABLE_MODELS.keys()) # --- Define Cycle Order and Stage-to-Cycle Mapping --- CYCLE_ORDER = [ "Requirements", "User Story", "Product Review", "Design", "UML", "Code Generation", "Review & Security", "Testing", "Quality Analysis", "Deployment" ] STAGE_TO_CYCLE = { "initial_setup": "Requirements", "run_generate_questions": "Requirements", "collect_answers": "Requirements", "run_refine_prompt": "Requirements", "run_generate_initial_user_stories": "User Story", "run_generate_user_story_feedback": "User Story", "collect_user_story_human_feedback": "User Story", "run_refine_user_stories": "User Story", "collect_user_story_decision": "User Story", "run_generate_initial_product_review": "Product Review", "run_generate_product_review_feedback": "Product Review", "collect_product_review_human_feedback": "Product Review", "run_refine_product_review": "Product Review", "collect_product_review_decision": "Product Review", "run_generate_initial_design_doc": "Design", "run_generate_design_doc_feedback": "Design", "collect_design_doc_human_feedback": "Design", "run_refine_design_doc": "Design", "collect_design_doc_decision": "Design", "run_select_uml_diagrams": "UML", "run_generate_initial_uml_codes": "UML", "run_generate_uml_feedback": "UML", "collect_uml_human_feedback": "UML", "run_refine_uml_codes": "UML", "collect_uml_decision": "UML", "run_generate_initial_code": "Code Generation", "collect_code_human_input": "Code Generation", "run_web_search_code": "Code Generation", "run_generate_code_feedback": "Code Generation", "collect_code_human_feedback": "Code Generation", "run_refine_code": "Code Generation", "collect_code_decision": "Code Generation", "run_code_review": "Review & Security", "run_security_check": "Review & Security", "merge_review_security_feedback": "Review & Security", "run_refine_code_with_reviews": "Review & Security", "collect_review_security_decision": "Review & Security", "run_generate_initial_test_cases": "Testing", "run_generate_test_cases_feedback": "Testing", "collect_test_cases_human_feedback": "Testing", "run_refine_test_cases_and_code": "Testing", "run_save_testing_outputs": "Testing", "run_generate_initial_quality_analysis": "Quality Analysis", "run_generate_quality_feedback": "Quality Analysis", "collect_quality_human_feedback": "Quality Analysis", "run_refine_quality_and_code": "Quality Analysis", "collect_quality_decision": "Quality Analysis", "generate_initial_deployment": "Deployment", "run_generate_initial_deployment": "Deployment", "run_generate_deployment_feedback": "Deployment", "collect_deployment_human_feedback": "Deployment", "run_refine_deployment": "Deployment", "collect_deployment_decision": "Deployment", "END": "END" } # --- Helper Functions --- def initialize_state(): """Initializes or resets the Streamlit session state.""" timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") default_project_folder = f"ai_sdlc_project_{timestamp}" st.session_state.clear() st.session_state.stage = "initial_setup" st.session_state.workflow_state = {} st.session_state.user_input = "" st.session_state.display_content = "Welcome! Please configure API keys and project details to start." st.session_state.project_folder_base = default_project_folder st.session_state.current_prefs = "" st.session_state.zip_path = None; st.session_state.review_code_zip_path = None; st.session_state.testing_code_zip_path = None; st.session_state.final_code_zip_path = None # Configuration state st.session_state.config_applied = False st.session_state.selected_provider = LLM_PROVIDERS[0] st.session_state.selected_model = AVAILABLE_MODELS[LLM_PROVIDERS[0]][0] st.session_state.llm_api_key = "" st.session_state.tavily_api_key = "" st.session_state.llm_instance = None st.session_state.tavily_instance = None logger.info("Streamlit session state initialized.") def update_display(new_content: str): st.session_state.display_content = new_content; logger.debug("Main display updated.") def create_download_button(file_path: str, label: str, mime: str, key_suffix: str, help_text: str = ""): if not file_path or not isinstance(file_path, str): return abs_file_path = os.path.abspath(file_path) if os.path.exists(abs_file_path) and os.path.isfile(abs_file_path): try: with open(abs_file_path, "rb") as fp: safe_label = "".join(c for c in label if c.isalnum())[:10] button_key = f"dl_{key_suffix}_{safe_label}" st.download_button(label=f"Download {label}", data=fp, file_name=os.path.basename(abs_file_path), mime=mime, key=button_key, help=help_text or f"Download {label}") except FileNotFoundError: logger.warning(f"FileNotFound after check: {abs_file_path}") except Exception as e: logger.error(f"Error prepping download btn for {abs_file_path}: {e}", exc_info=True); st.warning(f"DL Button error for {label}: {e}") def create_zip_and_download_button(folder_path_key: str, zip_path_key: str, zip_basename: str, button_label_prefix: str, sidebar_context): folder_path = st.session_state.workflow_state.get(folder_path_key) abs_folder_path = os.path.abspath(folder_path) if folder_path and isinstance(folder_path, str) else None if abs_folder_path and os.path.exists(abs_folder_path) and os.path.isdir(abs_folder_path): zip_label = f"Generate & Download {button_label_prefix} ZIP" existing_zip = st.session_state.get(zip_path_key) if existing_zip and os.path.exists(existing_zip): zip_label = f"Download {button_label_prefix} ZIP" zip_gen_key = f"zip_gen_{zip_path_key}" if sidebar_context.button(zip_label, key=zip_gen_key): with st.spinner(f"Creating {button_label_prefix} archive..."): try: out_dir = os.path.dirname(abs_folder_path); archive_base = os.path.join(out_dir, zip_basename) root_dir = os.path.dirname(abs_folder_path); base_dir = os.path.basename(abs_folder_path) logger.info(f"Zipping: base='{archive_base}', root='{root_dir}', dir='{base_dir}'") zip_file = archive_base + ".zip" if os.path.exists(zip_file): try: os.remove(zip_file); logger.info(f"Removed old ZIP: {zip_file}") except Exception as del_e: logger.warning(f"Could not remove old ZIP {zip_file}: {del_e}") archive_path = shutil.make_archive(base_name=archive_base, format='zip', root_dir=root_dir, base_dir=base_dir) if not os.path.exists(archive_path): raise OSError(f"ZIP not found after make_archive: {archive_path}") st.session_state[zip_path_key] = archive_path; st.success(f"{button_label_prefix} ZIP created!"); st.rerun() except Exception as e: sidebar_context.error(f"ZIP Error: {e}"); logger.error(f"ZIP failed for '{abs_folder_path}': {e}", exc_info=True) generated_zip = st.session_state.get(zip_path_key) if generated_zip and os.path.exists(generated_zip): try: with open(generated_zip, "rb") as fp: safe_prefix = "".join(c for c in button_label_prefix if c.isalnum())[:10] dl_key = f"dl_zip_{zip_path_key}_{safe_prefix}" sidebar_context.download_button(label=f"Download {button_label_prefix} ZIP", data=fp, file_name=os.path.basename(generated_zip), mime="application/zip", key=dl_key) except Exception as e: sidebar_context.warning(f"Error reading ZIP: {e}"); logger.error(f"Error reading ZIP {generated_zip}: {e}", exc_info=True) # --- Initialization --- if 'stage' not in st.session_state: initialize_state() # --- Sidebar UI --- with st.sidebar: st.header("AI SDLC Orchestrator") st.divider() # --- Configuration Section --- with st.expander("Configuration", expanded=not st.session_state.get('config_applied', False)): st.subheader("LLM & API Keys") selected_provider = st.selectbox("Select LLM Provider", options=LLM_PROVIDERS, key="selected_provider", help="Choose primary LLM provider.") available_models = AVAILABLE_MODELS.get(selected_provider, ["N/A"]) selected_model = st.selectbox(f"Select Model ({selected_provider})", options=available_models, key="selected_model", help=f"Choose model from {selected_provider}.") llm_api_key_input = st.text_input(f"{selected_provider} API Key", type="password", key="llm_api_key_input", help=f"Enter API key for {selected_provider}.", value=st.session_state.get("llm_api_key","")) tavily_api_key_input = st.text_input("Tavily API Key (Optional)", type="password", key="tavily_api_key_input", help="Enter Tavily key for web search.", value=st.session_state.get("tavily_api_key","")) if st.button("Apply Configuration", key="apply_config"): with st.spinner("Initializing..."): st.session_state.llm_api_key = llm_api_key_input # Update actual keys used st.session_state.tavily_api_key = tavily_api_key_input llm_inst, tav_inst, error_msg = SDLC.initialize_llm_clients( provider=st.session_state.selected_provider, model_name=st.session_state.selected_model, llm_api_key=st.session_state.llm_api_key, tavily_api_key=st.session_state.tavily_api_key ) if llm_inst: st.session_state.llm_instance = llm_inst; st.session_state.tavily_instance = tav_inst; st.session_state.config_applied = True st.success("Configuration Applied!"); logger.info("LLM/Tavily configured via UI.") time.sleep(1); st.rerun() # Give time to see success, then rerun to potentially hide expander else: st.session_state.config_applied = False; st.session_state.llm_instance = None; st.session_state.tavily_instance = None error_display = f"Config Failed: {error_msg or 'Unknown error.'}"; st.error(error_display); logger.error(error_display) # --- END Configuration Section --- st.divider() st.header("Downloads"); st.caption("Generated artifacts and code snapshots.") # Documents st.markdown("---"); st.subheader("Documents") create_download_button(st.session_state.workflow_state.get("final_user_story_path"), "User Story", "text/markdown", "us") create_download_button(st.session_state.workflow_state.get("final_product_review_path"), "Product Review", "text/markdown", "pr") create_download_button(st.session_state.workflow_state.get("final_design_document_path"), "Design Document", "text/markdown", "dd") create_download_button(st.session_state.workflow_state.get("final_quality_analysis_path"), "QA Report", "text/markdown", "qa") create_download_button(st.session_state.workflow_state.get("final_deployment_path"), "Deployment Plan", "text/markdown", "deploy") # UML st.markdown("---"); st.subheader("UML Diagrams") uml_png_paths = st.session_state.workflow_state.get("final_uml_png_paths", []); uml_folder = st.session_state.workflow_state.get("final_uml_diagram_folder") if uml_png_paths: st.caption("Download PNG images:"); [create_download_button(p, f"UML: {'_'.join(os.path.basename(p).split('_')[2:]).replace('.png', '').replace('_', ' ').title() or f'Diagram {i+1}'}", "image/png", f"uml_{i}") for i, p in enumerate(uml_png_paths)] elif uml_folder and os.path.exists(uml_folder): st.caption("*No PNGs generated/found.*") else: st.caption("*UML diagrams not generated.*") # Code Snapshots st.markdown("---"); st.subheader("Code Snapshots (ZIP)"); st.caption("Code versions from key stages.") create_zip_and_download_button("review_code_snapshot_folder", "review_code_zip_path", "code_snapshot_review", "Review Stage Code", st.sidebar) create_zip_and_download_button("testing_passed_code_folder", "testing_code_zip_path", "code_snapshot_testing", "Testing Stage Code", st.sidebar) create_zip_and_download_button("final_code_folder", "final_code_zip_path", "code_snapshot_final", "Final Code", st.sidebar) st.divider() # Final Project ZIP if st.session_state.stage == "END": st.markdown("**Full Project Archive**"); proj_folder = st.session_state.workflow_state.get("project_folder"); abs_proj = os.path.abspath(proj_folder) if proj_folder and isinstance(proj_folder, str) else None if abs_proj and os.path.isdir(abs_proj): zip_label = "Generate & Download Full Project ZIP"; if st.session_state.get("zip_path") and os.path.exists(st.session_state.zip_path): zip_label = "Download Full Project ZIP" if st.sidebar.button(zip_label, key="zip_gen_final"): with st.spinner("Creating full project archive..."): try: zip_base = os.path.abspath(st.session_state.project_folder_base); out_dir = os.path.dirname(zip_base); os.makedirs(out_dir, exist_ok=True) root_dir = os.path.dirname(abs_proj); base_dir = os.path.basename(abs_proj) logger.info(f"Zipping full project: base='{zip_base}', root='{root_dir}', dir='{base_dir}'") zip_file = zip_base + ".zip"; if os.path.exists(zip_file): try: os.remove(zip_file); logger.info(f"Removed old final ZIP: {zip_file}") except Exception as del_e: logger.warning(f"Could not remove old final ZIP {zip_file}: {del_e}") archive_path = shutil.make_archive(base_name=zip_base, format='zip', root_dir=root_dir, base_dir=base_dir) if not os.path.exists(archive_path): raise OSError(f"Final ZIP failed: {archive_path} not found.") st.session_state.zip_path = archive_path; st.success(f"Full project ZIP created: {os.path.basename(archive_path)}"); st.rerun() except Exception as e: st.sidebar.error(f"Final ZIP Error: {e}"); logger.error(f"Final ZIP creation failed: {e}", exc_info=True) if st.session_state.get("zip_path") and os.path.exists(st.session_state.zip_path): try: with open(st.session_state.zip_path, "rb") as fp: st.sidebar.download_button(label="Download Full Project ZIP", data=fp, file_name=os.path.basename(st.session_state.zip_path), mime="application/zip", key="dl_zip_final") except Exception as read_e: st.sidebar.warning(f"Error reading final ZIP: {read_e}"); logger.error(f"Error reading final ZIP {st.session_state.zip_path}: {read_e}", exc_info=True) elif proj_folder: st.sidebar.warning(f"Project folder '{proj_folder}' not found.") else: st.sidebar.caption("*Project folder undefined.*") st.divider() if st.sidebar.button("Restart Workflow", key="restart_sb", help="Clear progress and start over."): logger.info("Workflow restart requested."); initialize_state(); st.rerun() # --- Main Layout & Controls --- main_col, indicator_col = st.columns([4, 1]) input_needed = {"collect_answers", "collect_user_story_human_feedback", "collect_product_review_human_feedback", "collect_design_doc_human_feedback", "collect_uml_human_feedback", "collect_code_human_input", "collect_code_human_feedback", "merge_review_security_feedback", "collect_quality_human_feedback", "collect_deployment_human_feedback"} decision_needed = {"collect_user_story_decision", "collect_product_review_decision", "collect_design_doc_decision", "collect_uml_decision", "collect_code_decision", "collect_review_security_decision", "collect_quality_decision", "collect_deployment_decision"} current_stage = st.session_state.stage show_input_box = current_stage in input_needed; show_decision_btns = current_stage in decision_needed; show_test_fb = current_stage == "collect_test_cases_human_feedback"; show_setup_form = current_stage == "initial_setup"; show_deploy_prefs = current_stage == "generate_initial_deployment" with main_col: st.header(f"Stage: {current_stage.replace('_', ' ').title()}") st.markdown("### AI Output / Current Task:") display_area = st.container(height=400, border=False) with display_area: st.markdown(str(st.session_state.get("display_content", "Initializing...")), unsafe_allow_html=False) st.divider() # --- GATING --- if not st.session_state.get('config_applied', False): st.warning("👈 Please configure LLM Provider & API Keys in the sidebar first.") else: # --- Workflow UI --- if show_setup_form: with st.form("setup_form"): st.markdown("### Project Configuration") proj_folder = st.text_input("Project Folder Name", value=st.session_state.project_folder_base, help="Directory name. No spaces/special chars.") proj_name = st.text_input("Project Description", value="Web Task Manager Example") proj_cat = st.text_input("Category", value="Web Development") proj_subcat = st.text_input("Subcategory", value="Productivity Tool") proj_lang = st.text_input("Coding Language", value="Python") min_iter = st.number_input("Min Q&A Rounds", 1, 5, 2) submitted = st.form_submit_button("Start Workflow") if submitted: if not all([proj_folder, proj_name, proj_cat, proj_subcat, proj_lang]): st.error("Fill all fields.") elif any(c in proj_folder for c in r'/\:*?"<>| '): st.error("Invalid chars in folder name.") else: try: abs_proj = os.path.abspath(proj_folder) if os.path.exists(abs_proj) and not os.path.isdir(abs_proj): st.error(f"File exists: '{proj_folder}'.") else: if os.path.exists(abs_proj): st.warning(f"Folder exists: '{abs_proj}'.") else: os.makedirs(abs_proj, exist_ok=True); st.success(f"Folder ready: '{abs_proj}'") # Initialize state including LLM/Tavily instances initial_workflow_state = { "llm_instance": st.session_state.llm_instance, "tavily_instance": st.session_state.tavily_instance, "messages": [SDLC.HumanMessage(content=f"Setup:\nProject:{proj_name}\nCat:{proj_cat}\nSub:{proj_subcat}\nLang:{proj_lang}")], "project_folder": proj_folder, "project": proj_name, "category": proj_cat, "subcategory": proj_subcat, "coding_language": proj_lang, "user_input_iteration": 0, "user_input_min_iterations": min_iter, **{k: None for k in SDLC.MainState.__annotations__ if k not in ["llm_instance", "tavily_instance", "messages", "project_folder", "project", "category", "subcategory", "coding_language", "user_input_iteration", "user_input_min_iterations"]}, "user_input_questions": [], "user_input_answers": [], "user_input_done": False, "final_uml_codes": [], "final_code_files": [], "final_test_code_files": [], "test_cases_current": [], "uml_selected_diagrams": [], "uml_current_codes": [], "uml_feedback": {}, "uml_human_feedback": {}, "final_uml_png_paths": [], "code_current": SDLC.GeneratedCode(files=[], instructions=""), "user_story_done": False, "product_review_done": False, "design_doc_done": False, "uml_done": False, "code_done": False, "review_security_done": False, "test_cases_passed": False, "quality_done": False, "deployment_done": False } st.session_state.workflow_state = initial_workflow_state; st.session_state.project_folder_base = proj_folder; st.session_state.stage = "run_generate_questions"; logger.info(f"Setup complete. Starting workflow for '{proj_name}'."); st.rerun() except OSError as oe: st.error(f"Folder error '{proj_folder}': {oe}."); logger.error(f"OSError creating folder: {oe}", exc_info=True) except Exception as e: st.error(f"Setup error: {e}"); logger.error(f"Setup error: {e}", exc_info=True) elif show_deploy_prefs: with st.form("deploy_prefs_form"): st.markdown("### Deployment Preferences"); st.info("Specify target environment.") deploy_target = st.selectbox("Target", ["Localhost", "Docker", "AWS EC2", "AWS Lambda", "GCP Run", "Azure App Service", "Other"], key="deploy_target") deploy_details = st.text_area("Details:", height=100, key="deploy_details", placeholder="e.g., AWS region, Nginx, DB connection") submitted = st.form_submit_button("Generate Plan") if submitted: prefs = f"Target: {deploy_target}\nDetails: {deploy_details}"; st.session_state.current_prefs = prefs; st.session_state.stage = "run_generate_initial_deployment"; logger.info(f"Deploy prefs: {deploy_target}"); st.rerun() elif show_input_box: input_key = f"input_{current_stage}"; user_val = st.text_area("Input / Feedback:", height=150, key=input_key, value=st.session_state.get('user_input', ''), help="Provide feedback/answers. For Q&A, use #DONE when finished.") submit_key = f"submit_{current_stage}" if st.button("Submit", key=submit_key): user_text = user_val.strip(); state = st.session_state.workflow_state if not isinstance(state, dict): st.error("State invalid."); logger.critical("workflow_state invalid."); initialize_state(); st.rerun() try: next_stage = None; state['messages'] = state.get('messages', []) map = { "collect_answers": ("user_input_answers", "run_generate_questions", True), "collect_user_story_human_feedback": ("user_story_human_feedback", "run_refine_user_stories", False), "collect_product_review_human_feedback": ("product_review_human_feedback", "run_refine_product_review", False), "collect_design_doc_human_feedback": ("design_doc_human_feedback", "run_refine_design_doc", False), "collect_uml_human_feedback": ("uml_human_feedback", "run_refine_uml_codes", False), "collect_code_human_input": ("code_human_input", "run_web_search_code", False), "collect_code_human_feedback": ("code_human_feedback", "run_refine_code", False), "merge_review_security_feedback": ("review_security_human_feedback", "run_refine_code_with_reviews", False), "collect_quality_human_feedback": ("quality_human_feedback", "run_refine_quality_and_code", False), "collect_deployment_human_feedback": ("deployment_human_feedback", "run_refine_deployment", False) } if current_stage in map: key, next_run, is_list = map[current_stage] if is_list: state[key] = state.get(key, []) + [user_text] elif key == "uml_human_feedback": state[key] = {"all": user_text} else: state[key] = user_text state["messages"].append(SDLC.HumanMessage(content=user_text)); next_stage = next_run if current_stage == "collect_answers": state["user_input_iteration"] = state.get("user_input_iteration", 0) + 1; min_i = state.get("user_input_min_iterations", 1) lines = [l for l in user_text.splitlines() if l.strip()]; last = lines[-1].strip().upper() if lines else ""; done = "#DONE" in last logger.debug(f"Q&A Iter:{state['user_input_iteration']}/{min_i}. Done:{done}") if state["user_input_iteration"] >= min_i and done: state["user_input_done"] = True; next_stage = "run_refine_prompt"; logger.info("Q&A done.") else: state["user_input_done"] = False; logger.info("Continuing Q&A.") if current_stage == "collect_code_human_input" and not state.get('tavily_instance'): state["code_web_search_results"] = "Skipped (Tavily N/A)"; next_stage = "run_generate_code_feedback"; logger.info("Skipping web search.") else: st.error(f"Input logic undefined: {current_stage}"); logger.error(f"Input logic missing: {current_stage}") if next_stage: st.session_state.workflow_state = state; st.session_state.user_input = ""; st.session_state.stage = next_stage; logger.info(f"Input '{current_stage}'. -> '{next_stage}'."); st.rerun() except Exception as e: st.error(f"Input error: {e}"); logger.error(f"Input error {current_stage}: {e}", exc_info=True) elif show_test_fb: st.markdown("### Test Execution & Feedback"); st.info("Execute tests, provide feedback & outcome.") ai_fb = st.session_state.workflow_state.get("test_cases_feedback", "*N/A*") with st.expander("AI Feedback on Tests"): st.markdown(ai_fb) human_fb = st.text_area("Feedback & Results:", height=150, key="tc_fb") pf_status = st.radio("Core Tests Passed?", ("PASS", "FAIL"), index=1, key="tc_pf", horizontal=True) c1, c2 = st.columns(2) with c1: # Submit Results if st.button("Submit Results", key="submit_test"): state = st.session_state.workflow_state; state['messages'] = state.get('messages', []) fb = f"Res: {pf_status}\nFB:{human_fb}"; state["test_cases_human_feedback"] = fb; state["test_cases_passed"] = (pf_status == "PASS") state["messages"].append(SDLC.HumanMessage(content=fb)); logger.info(f"Test res: {pf_status}.") next_s = "run_save_testing_outputs" if state["test_cases_passed"] else "run_refine_test_cases_and_code" st.session_state.stage = next_s; st.session_state.workflow_state = state; st.rerun() with c2: # Regen Code if st.button("Submit & Regenerate Code", key="regen_test"): state = st.session_state.workflow_state; state['messages'] = state.get('messages', []) fb = f"Res: {pf_status}\nFB:{human_fb}\nDecision: Regen Code."; state["test_cases_human_feedback"] = fb; state["test_cases_passed"] = False state["messages"].append(SDLC.HumanMessage(content=fb)); logger.info(f"Test FB ({pf_status}), regen code.") ctx = f"From Testing:\nRes:{pf_status}\nFB:{human_fb}\nAI Test FB:{ai_fb}\nRegen code."; state["code_human_input"] = ctx; state["messages"].append(SDLC.HumanMessage(content=f"Regen Context: {ctx[:200]}...")) st.session_state.stage = "collect_code_human_input"; st.session_state.workflow_state = state; st.rerun() elif show_decision_btns: st.markdown("### Decision Point"); st.info("Review output. Refine or proceed.") refine_map = { "collect_user_story_decision": "run_generate_user_story_feedback", "collect_product_review_decision": "run_generate_product_review_feedback", "collect_design_doc_decision": "run_generate_design_doc_feedback", "collect_uml_decision": "run_generate_uml_feedback", "collect_code_decision": "collect_code_human_input", "collect_review_security_decision": "run_code_review", "collect_quality_decision": "run_generate_quality_feedback", "collect_deployment_decision": "run_generate_deployment_feedback", } proceed_map = { "collect_user_story_decision": ("user_story_done", SDLC.save_final_user_story, "run_generate_initial_product_review"), "collect_product_review_decision": ("product_review_done", SDLC.save_final_product_review, "run_generate_initial_design_doc"), "collect_design_doc_decision": ("design_doc_done", SDLC.save_final_design_doc, "run_select_uml_diagrams"), "collect_uml_decision": ("uml_done", SDLC.save_final_uml_diagrams, "run_generate_initial_code"), "collect_code_decision": ("code_done", None, "run_code_review"), "collect_review_security_decision": ("review_security_done", SDLC.save_review_security_outputs, "run_generate_initial_test_cases"), "collect_quality_decision": ("quality_done", SDLC.save_final_quality_analysis, "generate_initial_deployment"), "collect_deployment_decision": ("deployment_done", SDLC.save_final_deployment_plan, "END"), } cols = st.columns(3 if current_stage == "collect_quality_decision" else 2) with cols[0]: # Refine if st.button("Refine", key=f"refine_{current_stage}"): if current_stage in refine_map: state = st.session_state.workflow_state; done_key = current_stage.replace("collect_", "").replace("_decision", "_done"); state[done_key]=False; next_refine = refine_map[current_stage]; st.session_state.stage = next_refine; st.session_state.workflow_state = state; logger.info(f"Decision: Refine '{current_stage}'. -> '{next_refine}'."); st.rerun() else: st.warning("Refine undefined."); logger.warning(f"Refine undefined for {current_stage}") with cols[1]: # Proceed if st.button("Proceed", key=f"proceed_{current_stage}"): if current_stage in proceed_map: state = st.session_state.workflow_state; done_key, save_func, next_stage = proceed_map[current_stage]; err = False try: state[done_key] = True; logger.info(f"Decision: Proceed from '{current_stage}'. Marked '{done_key}'=True.") if current_stage == "collect_code_decision": # Promote code code_obj = state.get("code_current"); if code_obj and isinstance(code_obj, SDLC.GeneratedCode) and code_obj.files: state["final_code_files"] = code_obj.files; logger.info(f"Promoted {len(code_obj.files)} files.") else: st.warning("Proceed code gen, but 'code_current' invalid."); logger.warning("Proceed code gen, invalid."); state["final_code_files"] = [] if save_func: # Save artifact fn = getattr(save_func, '__name__', 'save_func'); logger.info(f"Saving: {fn}") with st.spinner(f"Saving..."): state = save_func(state); st.session_state.workflow_state = state # Post-save check (basic) map_paths = { SDLC.save_final_user_story: "final_user_story_path", SDLC.save_final_product_review: "final_product_review_path", SDLC.save_final_design_doc: "final_design_document_path", SDLC.save_final_uml_diagrams: "final_uml_diagram_folder", SDLC.save_review_security_outputs: "final_review_security_folder", SDLC.save_testing_outputs: "final_testing_folder", SDLC.save_final_quality_analysis: "final_quality_analysis_path", SDLC.save_final_deployment_plan: "final_deployment_path", }; path_key = map_paths.get(save_func); path_val = state.get(path_key) if path_key else True; qa_ok = True if save_func != SDLC.save_final_quality_analysis else bool(state.get("final_code_folder")) if (path_key and not path_val) or not qa_ok: st.warning(f"Saving for '{current_stage}' may have failed."); logger.warning(f"Save check failed for {fn}.") else: logger.info(f"Save {fn} ok.") except Exception as e: st.error(f"Finalize error '{current_stage}': {e}"); logger.error(f"Proceed error {current_stage}: {e}", exc_info=True); err = True if not err: st.session_state.stage = next_stage; logger.info(f"-> {next_stage}"); st.rerun() else: st.warning("Proceed undefined."); logger.warning(f"Proceed undefined for {current_stage}") if current_stage == "collect_quality_decision": # QA Regen with cols[2]: if st.button("Regen Code", key="regen_qa"): state = st.session_state.workflow_state; state['messages'] = state.get('messages', []); logger.info("Decision: Regen Code from QA.") qa_sum = state.get('quality_current_analysis', 'N/A')[:1000] ctx = f"From QA:\nFindings:\n{qa_sum}...\nRegen code."; state["code_human_input"] = ctx; state["messages"].append(SDLC.HumanMessage(content=f"Regen Context: {ctx[:200]}...")) st.session_state.stage = "collect_code_human_input"; st.session_state.workflow_state = state; st.rerun() elif current_stage == "END": st.balloons(); final_msg = "## Workflow Completed!\n\nUse sidebar downloads or restart."; update_display(final_msg); st.markdown(final_msg); logger.info("Workflow END.") elif not current_stage.startswith("run_"): st.error(f"Unknown UI stage: '{current_stage}'. Restart?"); logger.error(f"Unknown UI stage: {current_stage}") # --- Cycle Indicator --- with indicator_col: st.subheader("Workflow Cycles") current_major = STAGE_TO_CYCLE.get(current_stage, "Unknown"); current_idx = -1 if current_major in CYCLE_ORDER: current_idx = CYCLE_ORDER.index(current_major) elif current_major == "END": current_idx = len(CYCLE_ORDER) st.markdown("""""", unsafe_allow_html=True) win_before, win_after = 2, 4; start = max(0, current_idx - win_before); end = min(len(CYCLE_ORDER), start + win_before + win_after); start = max(0, end - (win_before + win_after)) for i, name in enumerate(CYCLE_ORDER): if start <= i < end : css = "cycle-item"; display = name if i < current_idx: css += " cycle-past" elif i == current_idx and current_major != "END": css += " cycle-current"; display = f"➡️ {name}" else: css += " cycle-future" st.markdown(f'