Update tfa_ui/app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753"""TFA - Test Failure Analysis Streamlit UIA comprehensive web interface for the multi-agent TFA system.Supports Gmail Android, Web, and iOS test failure analysis.Run from project root: streamlit run tfa_ui/app.py"""import streamlit as stimport asyncioimport timeimport jsonimport osfrom datetime import datetimefrom typing import Optionalfrom pathlib import Pathimport sys# Add project root to path for imports# Works whether run from project root or tfa_ui directory_current_file = Path(__file__).resolve()_project_root = _current_file.parent.parentif str(_project_root) not in sys.path:sys.path.insert(0, str(_project_root))# Page config must be first Streamlit commandst.set_page_config(page_title="TFA - Test Failure Analysis",page_icon="π",layout="wide",initial_sidebar_state="expanded",)# Import TFA componentstry:from tfa_agents import TFARunnerfrom tfa_agents.tools.sponge_mock import use_mock_clientfrom tfa_agents.shared.memory import get_memoryfrom tfa_agents.tools.metrics_client import get_metrics_client, MetricsTimeframefrom tfa_agents.agents.metrics_analyzer import metrics_analyzerfrom tfa_agents.shared.models import Platformfrom tfa_agents.config import get_configTFA_AVAILABLE = Trueexcept ImportError as e:TFA_AVAILABLE = FalseIMPORT_ERROR = str(e)def init_session_state():"""Initialize Streamlit session state."""if "runner" not in st.session_state:st.session_state.runner = Noneif "analysis_history" not in st.session_state:st.session_state.analysis_history = []if "current_result" not in st.session_state:st.session_state.current_result = Noneif "is_analyzing" not in st.session_state:st.session_state.is_analyzing = Falsedef render_sidebar():"""Render the sidebar with configuration options."""with st.sidebar:st.image("https://img.icons8.com/color/96/000000/test-tube.png", width=80)st.title("TFA Configuration")# Configuration statusif TFA_AVAILABLE:config = get_config()api_key = config.get_google_api_key()# Show Hugging Face Spaces specific infoif os.environ.get("SPACE_ID"):st.info("π€ **Hugging Face Spaces Demo**")st.markdown("Using mock data for demonstration")if api_key and api_key not in ["test-key-for-mock-data", "demo-key-for-huggingface-spaces"]:st.success("π API Key: Configured")else:st.warning("π API Key: Using demo key")if not os.environ.get("SPACE_ID"):st.info("Set GOOGLE_API_KEY for full functionality")st.divider()# Platform selectionst.subheader("π― Platform")platform = st.selectbox("Select Platform",options=["Auto-detect", "Android", "Web", "iOS"],help="Platform will be auto-detected if not specified")# Mock data togglest.subheader("π§ͺ Test Mode")use_mock = st.toggle("Use Mock Data", value=True, help="Use simulated data for testing")if use_mock:mock_scenario = st.selectbox("Mock Scenario",options=["code_regression", "infrastructure", "flaky_test", "configuration"],help="Select a test scenario")else:mock_scenario = Nonest.divider()# Daily Metrics Dashboardst.subheader("π Daily Metrics")if TFA_AVAILABLE:render_daily_metrics_sidebar()st.divider()# Memory statsst.subheader("πΎ Memory Stats")if TFA_AVAILABLE:memory = get_memory()stats = memory.stats()col1, col2 = st.columns(2)with col1:st.metric("Analysis", stats.get("analysis", {}).get("valid_entries", 0))st.metric("Patterns", stats.get("patterns", {}).get("valid_entries", 0))with col2:st.metric("Cache", stats.get("cache", {}).get("valid_entries", 0))st.metric("Session", stats.get("session", {}).get("valid_entries", 0))if st.button("ποΈ Clear Memory", use_container_width=True):memory.clear_namespace("analysis")memory.clear_namespace("cache")st.success("Memory cleared!")st.divider()# About sectionst.subheader("βΉοΈ About")st.markdown("""**TFA v2.0** - Multi-PlatformSupports:- π€ Android (Copycat, Espresso)- π Web (Selenium, Playwright)- π iOS (XCUITest, EarlGrey)""")return platform, use_mock, mock_scenariodef render_daily_metrics_sidebar():"""Render daily metrics in the sidebar."""try:client = get_metrics_client()daily_metrics = client.get_daily_failure_percentage()st.markdown("**Yesterday's Failure Rates**")# Color coding for failure ratesfor platform, rate in daily_metrics.items():if rate < 10:color = "π’"elif rate < 20:color = "π‘"else:color = "π΄"st.metric(f"{color} {platform.value}",f"{rate:.1f}%",delta=None,help=f"Daily failure rate for {platform.value} platform")# Quick health checkavg_rate = sum(daily_metrics.values()) / len(daily_metrics) if daily_metrics else 0if avg_rate > 15:st.warning(f"β οΈ High average failure rate: {avg_rate:.1f}%")elif avg_rate < 8:st.success(f"β Good average failure rate: {avg_rate:.1f}%")if st.button("π View Full Metrics Dashboard", use_container_width=True):st.session_state.show_metrics_dashboard = Trueexcept Exception as e:st.error(f"Error loading metrics: {str(e)}")def render_metrics_dashboard():"""Render the comprehensive metrics dashboard."""st.title("π Platform Metrics Dashboard")# Timeframe selectioncol1, col2, col3 = st.columns([2, 1, 1])with col1:timeframe = st.selectbox("Analysis Timeframe",options=["7d", "30d", "90d", "month", "quarter"],index=1, # Default to 30dhelp="Select time period for analysis")with col2:if st.button("π Refresh Data"):st.rerun()with col3:auto_refresh = st.toggle("Auto Refresh", value=False)st.divider()try:client = get_metrics_client()# Get comprehensive reportreport = client.get_comparative_report(MetricsTimeframe(timeframe))# Overview metricsst.subheader("π Overview")col1, col2, col3, col4 = st.columns(4)with col1:st.metric("Overall Avg Failure Rate",f"{report['overall_average_failure_rate']:.1f}%",help="Average failure rate across all platforms")with col2:best_platform = report.get('best_performing_platform', 'N/A')st.metric("Best Platform",best_platform,help="Platform with lowest failure rate")with col3:worst_platform = report.get('worst_performing_platform', 'N/A')st.metric("Worst Platform",worst_platform,help="Platform with highest failure rate")with col4:improving_count = len(report.get('platforms_improving', []))degrading_count = len(report.get('platforms_degrading', []))st.metric("Trend Status",f"+{improving_count} / -{degrading_count}",help="Platforms improving vs degrading")# Platform detailsst.subheader("π― Platform Performance")platform_tabs = st.tabs(["π€ Android", "π Web", "π iOS"])platforms = [Platform.ANDROID, Platform.WEB, Platform.IOS]for i, (tab, platform) in enumerate(zip(platform_tabs, platforms)):with tab:render_platform_details(platform, timeframe, report)# Insights and recommendationsst.subheader("π‘ Insights & Recommendations")if 'insights' in report and report['insights']:for insight in report['insights']:if insight['type'] == 'critical':st.error(f"π¨ {insight['message']}")st.info(f"**Action:** {insight['action']}")elif insight['type'] == 'warning':st.warning(f"β οΈ {insight['message']}")st.info(f"**Action:** {insight['action']}")elif insight['type'] == 'positive':st.success(f"β {insight['message']}")st.info(f"**Action:** {insight['action']}")if 'recommendations' in report and report['recommendations']:st.markdown("**Platform-Specific Recommendations:**")for rec in report['recommendations']:priority_color = "π΄" if rec['priority'] == 'high' else "π‘"st.markdown(f"{priority_color} **{rec['platform']}**: {rec['message']}")for action in rec['suggested_actions']:st.markdown(f" β’ {action}")# Historical trends chart (mock data visualization)st.subheader("π Trend Visualization")render_trends_chart(timeframe)except Exception as e:st.error(f"Error loading metrics dashboard: {str(e)}")st.exception(e)def render_platform_details(platform: Platform, timeframe: str, report: dict):"""Render detailed metrics for a specific platform."""platform_key = platform.valueif platform_key in report.get('platform_summaries', {}):summary = report['platform_summaries'][platform_key]col1, col2 = st.columns(2)with col1:st.metric("Average Failure Rate",f"{summary['average_failure_rate']:.1f}%")trend_emoji = {"improving": "π","degrading": "π","stable": "β‘οΈ"}.get(summary['trend_direction'], "β")st.metric("Trend Direction",f"{trend_emoji} {summary['trend_direction'].title()}")with col2:if summary.get('worst_day'):st.metric("Worst Day",f"{summary['worst_day']['failure_rate']:.1f}%",delta=f"on {summary['worst_day']['date']}")if summary.get('best_day'):st.metric("Best Day",f"{summary['best_day']['failure_rate']:.1f}%",delta=f"on {summary['best_day']['date']}")# Health scoretry:client = get_metrics_client()trends = client.get_platform_trends(MetricsTimeframe(timeframe), [platform])if platform in trends:trend = trends[platform]# Calculate simple health scorehealth_score = max(0, 100 - (trend.average_failure_rate * 2))if health_score >= 80:health_color = "π’"health_status = "Excellent"elif health_score >= 60:health_color = "π‘"health_status = "Good"elif health_score >= 40:health_color = "π "health_status = "Fair"else:health_color = "π΄"health_status = "Poor"st.metric("Health Score",f"{health_color} {health_score:.0f}/100",delta=health_status)except Exception:pass # Skip health score if calculation failselse:st.info(f"No data available for {platform_key}")def render_trends_chart(timeframe: str):"""Render a simple trends visualization."""# This is a placeholder for actual chart rendering# In a real implementation, you'd use plotly, matplotlib, or similarst.info("π Trend charts would be displayed here with actual data visualization libraries like Plotly or Matplotlib")# Mock chart data descriptionst.markdown("""**Chart would show:**- Daily failure rates for each platform over the selected timeframe- Trend lines showing improvement/degradation- Annotations for significant events or changes- Comparative view across all platforms""")def render_header():"""Render the main header."""# Add Hugging Face Spaces infoif os.environ.get("SPACE_ID"):st.info("π€ **Running on Hugging Face Spaces** - This demo uses mock data to showcase TFA capabilities!")col1, col2, col3 = st.columns([1, 3, 1])with col2:st.title("π Test Failure Analysis")st.markdown("*AI-powered multi-agent system for Gmail test failure triage*")# Add navigation tabstab1, tab2 = st.tabs(["π Failure Analysis", "π Metrics Dashboard"])return tab1, tab2def render_input_form():"""Render the input form for analysis."""st.subheader("π Analysis Input")col1, col2 = st.columns(2)with col1:invocation_id = st.text_input("Invocation ID",value="fe3e0b7f-7bb9-4524-8a79-3c62cf028243",help="UUID of the test invocation from Sponge")with col2:test_name = st.text_input("Test Name",value="mark_multiple_emails_as_read",help="Name or target ID of the failing test")additional_context = st.text_area("Additional Context (optional)",placeholder="Any additional information about the failure...",height=100)return invocation_id, test_name, additional_contextdef render_agent_pipeline():"""Render the agent pipeline visualization."""st.subheader("π Agent Pipeline")cols = st.columns(4)agents = [("π₯", "Information Collector", "Gathers logs, artifacts, history"),("π·οΈ", "Failure Classifier", "Categorizes with confidence"),("β‘", "Action Determiner", "Decides next steps"),("π", "Summarizer", "Generates reports"),]for i, (icon, name, desc) in enumerate(agents):with cols[i]:status = "π΅" if st.session_state.is_analyzing else "βͺ"st.markdown(f"""<div style="text-align: center; padding: 10px; border: 1px solid #ddd; border-radius: 10px;"><h2>{icon}</h2><h4>{name}</h4><p style="font-size: 12px; color: gray;">{desc}</p><p>{status}</p></div>""", unsafe_allow_html=True)def render_results(result: str):"""Render the analysis results."""st.subheader("π Analysis Results")# Create tabs for different viewstab1, tab2, tab3, tab4 = st.tabs(["π Full Report", "π¬ Slack", "π Ticket", "π Details"])with tab1:st.markdown(result)with tab2:# Extract Slack-style summaryst.markdown("### Slack Message Preview")st.code(f"""π΄ *Test Failure Alert*Analysis complete. See full report for details.π Full Analysis | π Bug Ticket | π Test Logs""")with tab3:st.markdown("### Bug Ticket Template")st.text_area("Copy this to your bug tracker:",value=f"## Test Failure Analysis\n\n{result[:500]}...",height=300)with tab4:render_analysis_details()def render_analysis_details():"""Render detailed analysis information."""if st.session_state.runner:context = st.session_state.runner.get_last_analysis_context()col1, col2 = st.columns(2)with col1:st.markdown("**Analysis Context**")st.json(context)with col2:st.markdown("**Memory Statistics**")stats = st.session_state.runner.get_memory_stats()st.json(stats)def render_classification_categories():"""Render the classification categories reference."""with st.expander("π Classification Categories Reference"):categories = {"Infrastructure": {"icon": "ποΈ","description": "Network, storage, device, test lab issues","examples": ["SocketTimeoutException", "Storage < 500MB", "Device offline"]},"Code Regression": {"icon": "π","description": "Recent CL broke functionality","examples": ["Pass rate drop after CL", "State management errors"]},"UI Regression": {"icon": "π¨","description": "UI/layout changes broke tests","examples": ["Element not found", "CSS changes", "Layout shifts"]},"Configuration": {"icon": "βοΈ","description": "Missing packages, wrong flags","examples": ["ActivityNotFoundException", "Feature flag mismatch"]},"Dependency": {"icon": "π¦","description": "External library/service issues","examples": ["ClassNotFoundException", "Version mismatch"]},"Test Logic Error": {"icon": "π§ͺ","description": "Bug in test code itself","examples": ["Wrong selector", "Race condition", "Always flaky"]},"Unknown": {"icon": "β","description": "Insufficient evidence","examples": ["Intermittent", "Non-reproducible"]}}cols = st.columns(3)for i, (cat, info) in enumerate(categories.items()):with cols[i % 3]:st.markdown(f"""**{info['icon']} {cat}**{info['description']}*Examples:* {', '.join(info['examples'][:2])}""")def render_history():"""Render analysis history sidebar."""if st.session_state.analysis_history:st.subheader("π Recent Analyses")for i, entry in enumerate(reversed(st.session_state.analysis_history[-5:])):with st.expander(f"{entry['test_name'][:25]}... ({entry['timestamp']})", expanded=False):st.markdown(f"**Invocation:** `{entry['invocation_id'][:8]}...`")st.markdown(f"**Platform:** {entry['platform']}")st.markdown(f"**Duration:** {entry['duration']:.1f}s")if st.button(f"View Result", key=f"view_{i}"):st.session_state.current_result = entry['result']async def run_analysis_async(invocation_id: str,test_name: str,additional_context: str,platform: str,use_mock: bool,mock_scenario: Optional[str],) -> tuple[str, float]:"""Run the TFA analysis pipeline asynchronously.Returns:Tuple of (result_string, duration_seconds)"""start_time = time.time()# Configure mock if enabledif use_mock and mock_scenario:use_mock_client(mock_scenario)# Initialize runner if neededif st.session_state.runner is None:st.session_state.runner = TFARunner()runner = st.session_state.runner# Determine platformplatform_hint = None if platform == "Auto-detect" else platform# Run analysisresult = await runner.analyze_failure_async(invocation_id=invocation_id,test_name=test_name,additional_context=additional_context,platform=platform_hint,)duration = time.time() - start_timereturn result, durationdef run_analysis(invocation_id: str,test_name: str,additional_context: str,platform: str,use_mock: bool,mock_scenario: Optional[str],) -> tuple[str, float]:"""Synchronous wrapper for run_analysis_async."""return asyncio.run(run_analysis_async(invocation_id=invocation_id,test_name=test_name,additional_context=additional_context,platform=platform,use_mock=use_mock,mock_scenario=mock_scenario,))def main():"""Main Streamlit application entry point."""# Initialize session stateinit_session_state()# Initialize metrics dashboard stateif "show_metrics_dashboard" not in st.session_state:st.session_state.show_metrics_dashboard = False# Check TFA availabilityif not TFA_AVAILABLE:st.error(f"β οΈ TFA modules not available: {IMPORT_ERROR}")st.info("Make sure you're running from the project root and dependencies are installed.")st.code("pip install -r requirements.txt", language="bash")return# Render sidebar and get configplatform, use_mock, mock_scenario = render_sidebar()# Main content area with tabsanalysis_tab, metrics_tab = render_header()with analysis_tab:render_analysis_page(platform, use_mock, mock_scenario)with metrics_tab:render_metrics_dashboard()def render_analysis_page(platform, use_mock, mock_scenario):"""Render the main failure analysis page."""st.divider()# Input forminvocation_id, test_name, additional_context = render_input_form()# Analysis buttoncol1, col2, col3 = st.columns([1, 2, 1])with col2:analyze_button = st.button("π Run Analysis",type="primary",use_container_width=True,disabled=st.session_state.is_analyzing,)st.divider()# Agent pipeline visualizationrender_agent_pipeline()st.divider()# Run analysis when button clickedif analyze_button and invocation_id and test_name:st.session_state.is_analyzing = Truewith st.spinner("π Analyzing test failure... This may take a moment."):try:# Progress indicatorsprogress_bar = st.progress(0)status_text = st.empty()# Simulate progress (actual analysis is async)status_text.text("π₯ Information Collector gathering data...")progress_bar.progress(25)result, duration = run_analysis(invocation_id=invocation_id,test_name=test_name,additional_context=additional_context,platform=platform,use_mock=use_mock,mock_scenario=mock_scenario,)progress_bar.progress(100)status_text.text("β Analysis complete!")# Store resultst.session_state.current_result = result# Add to historyst.session_state.analysis_history.append({"invocation_id": invocation_id,"test_name": test_name,"platform": platform,"result": result,"duration": duration,"timestamp": datetime.now().strftime("%H:%M:%S"),})st.success(f"β Analysis completed in {duration:.1f} seconds")except Exception as e:st.error(f"β Analysis failed: {str(e)}")st.exception(e)finally:st.session_state.is_analyzing = False# Display resultsif st.session_state.current_result:render_results(st.session_state.current_result)# Classification referencerender_classification_categories()# History in sidebarwith st.sidebar:render_history()if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753"""TFA - Test Failure Analysis Streamlit UIA comprehensive web interface for the multi-agent TFA system.Supports Gmail Android, Web, and iOS test failure analysis.Run from project root: streamlit run tfa_ui/app.py"""import streamlit as stimport asyncioimport timeimport jsonimport osfrom datetime import datetimefrom typing import Optionalfrom pathlib import Pathimport sys# Add project root to path for imports# Works whether run from project root or tfa_ui directory_current_file = Path(__file__).resolve()_project_root = _current_file.parent.parentif str(_project_root) not in sys.path:sys.path.insert(0, str(_project_root))# Page config must be first Streamlit commandst.set_page_config(page_title="TFA - Test Failure Analysis",page_icon="π",layout="wide",initial_sidebar_state="expanded",)# Import TFA componentstry:from tfa_agents import TFARunnerfrom tfa_agents.tools.sponge_mock import use_mock_clientfrom tfa_agents.shared.memory import get_memoryfrom tfa_agents.tools.metrics_client import get_metrics_client, MetricsTimeframefrom tfa_agents.agents.metrics_analyzer import metrics_analyzerfrom tfa_agents.shared.models import Platformfrom tfa_agents.config import get_configTFA_AVAILABLE = Trueexcept ImportError as e:TFA_AVAILABLE = FalseIMPORT_ERROR = str(e)def init_session_state():"""Initialize Streamlit session state."""if "runner" not in st.session_state:st.session_state.runner = Noneif "analysis_history" not in st.session_state:st.session_state.analysis_history = []if "current_result" not in st.session_state:st.session_state.current_result = Noneif "is_analyzing" not in st.session_state:st.session_state.is_analyzing = Falsedef render_sidebar():"""Render the sidebar with configuration options."""with st.sidebar:st.image("https://img.icons8.com/color/96/000000/test-tube.png", width=80)st.title("TFA Configuration")# Configuration statusif TFA_AVAILABLE:config = get_config()api_key = config.get_google_api_key()# Show Hugging Face Spaces specific infoif os.environ.get("SPACE_ID"):st.info("π€ **Hugging Face Spaces Demo**")st.markdown("Using mock data for demonstration")if api_key and api_key not in ["test-key-for-mock-data", "demo-key-for-huggingface-spaces"]:st.success("π API Key: Configured")else:st.warning("π API Key: Using demo key")if not os.environ.get("SPACE_ID"):st.info("Set GOOGLE_API_KEY for full functionality")st.divider()# Platform selectionst.subheader("π― Platform")platform = st.selectbox("Select Platform",options=["Auto-detect", "Android", "Web", "iOS"],help="Platform will be auto-detected if not specified")# Mock data togglest.subheader("π§ͺ Test Mode")use_mock = st.toggle("Use Mock Data", value=True, help="Use simulated data for testing")if use_mock:mock_scenario = st.selectbox("Mock Scenario",options=["code_regression", "infrastructure", "flaky_test", "configuration"],help="Select a test scenario")else:mock_scenario = Nonest.divider()# Daily Metrics Dashboardst.subheader("π Daily Metrics")if TFA_AVAILABLE:render_daily_metrics_sidebar()st.divider()# Memory statsst.subheader("πΎ Memory Stats")if TFA_AVAILABLE:memory = get_memory()stats = memory.stats()col1, col2 = st.columns(2)with col1:st.metric("Analysis", stats.get("analysis", {}).get("valid_entries", 0))st.metric("Patterns", stats.get("patterns", {}).get("valid_entries", 0))with col2:st.metric("Cache", stats.get("cache", {}).get("valid_entries", 0))st.metric("Session", stats.get("session", {}).get("valid_entries", 0))if st.button("ποΈ Clear Memory", use_container_width=True):memory.clear_namespace("analysis")memory.clear_namespace("cache")st.success("Memory cleared!")st.divider()# About sectionst.subheader("βΉοΈ About")st.markdown("""**TFA v2.0** - Multi-PlatformSupports:- π€ Android (Copycat, Espresso)- π Web (Selenium, Playwright)- π iOS (XCUITest, EarlGrey)""")return platform, use_mock, mock_scenariodef render_daily_metrics_sidebar():"""Render daily metrics in the sidebar."""try:client = get_metrics_client()daily_metrics = client.get_daily_failure_percentage()st.markdown("**Yesterday's Failure Rates**")# Color coding for failure ratesfor platform, rate in daily_metrics.items():if rate < 10:color = "π’"elif rate < 20:color = "π‘"else:color = "π΄"st.metric(f"{color} {platform.value}",f"{rate:.1f}%",delta=None,help=f"Daily failure rate for {platform.value} platform")# Quick health checkavg_rate = sum(daily_metrics.values()) / len(daily_metrics) if daily_metrics else 0if avg_rate > 15:st.warning(f"β οΈ High average failure rate: {avg_rate:.1f}%")elif avg_rate < 8:st.success(f"β Good average failure rate: {avg_rate:.1f}%")if st.button("π View Full Metrics Dashboard", use_container_width=True):st.session_state.show_metrics_dashboard = Trueexcept Exception as e:st.error(f"Error loading metrics: {str(e)}")def render_metrics_dashboard():"""Render the comprehensive metrics dashboard."""st.title("π Platform Metrics Dashboard")# Timeframe selectioncol1, col2, col3 = st.columns([2, 1, 1])with col1:timeframe = st.selectbox("Analysis Timeframe",options=["7d", "30d", "90d", "month", "quarter"],index=1, # Default to 30dhelp="Select time period for analysis")with col2:if st.button("π Refresh Data"):st.rerun()with col3:auto_refresh = st.toggle("Auto Refresh", value=False)st.divider()try:client = get_metrics_client()# Get comprehensive reportreport = client.get_comparative_report(MetricsTimeframe(timeframe))# Overview metricsst.subheader("π Overview")col1, col2, col3, col4 = st.columns(4)with col1:st.metric("Overall Avg Failure Rate",f"{report['overall_average_failure_rate']:.1f}%",help="Average failure rate across all platforms")with col2:best_platform = report.get('best_performing_platform', 'N/A')st.metric("Best Platform",best_platform,help="Platform with lowest failure rate")with col3:worst_platform = report.get('worst_performing_platform', 'N/A')st.metric("Worst Platform",worst_platform,help="Platform with highest failure rate")with col4:improving_count = len(report.get('platforms_improving', []))degrading_count = len(report.get('platforms_degrading', []))st.metric("Trend Status",f"+{improving_count} / -{degrading_count}",help="Platforms improving vs degrading")# Platform detailsst.subheader("π― Platform Performance")platform_tabs = st.tabs(["π€ Android", "π Web", "π iOS"])platforms = [Platform.ANDROID, Platform.WEB, Platform.IOS]for i, (tab, platform) in enumerate(zip(platform_tabs, platforms)):with tab:render_platform_details(platform, timeframe, report)# Insights and recommendationsst.subheader("π‘ Insights & Recommendations")if 'insights' in report and report['insights']:for insight in report['insights']:if insight['type'] == 'critical':st.error(f"π¨ {insight['message']}")st.info(f"**Action:** {insight['action']}")elif insight['type'] == 'warning':st.warning(f"β οΈ {insight['message']}")st.info(f"**Action:** {insight['action']}")elif insight['type'] == 'positive':st.success(f"β {insight['message']}")st.info(f"**Action:** {insight['action']}")if 'recommendations' in report and report['recommendations']:st.markdown("**Platform-Specific Recommendations:**")for rec in report['recommendations']:priority_color = "π΄" if rec['priority'] == 'high' else "π‘"st.markdown(f"{priority_color} **{rec['platform']}**: {rec['message']}")for action in rec['suggested_actions']:st.markdown(f" β’ {action}")# Historical trends chart (mock data visualization)st.subheader("π Trend Visualization")render_trends_chart(timeframe)except Exception as e:st.error(f"Error loading metrics dashboard: {str(e)}")st.exception(e)def render_platform_details(platform: Platform, timeframe: str, report: dict):"""Render detailed metrics for a specific platform."""platform_key = platform.valueif platform_key in report.get('platform_summaries', {}):summary = report['platform_summaries'][platform_key]col1, col2 = st.columns(2)with col1:st.metric("Average Failure Rate",f"{summary['average_failure_rate']:.1f}%")trend_emoji = {"improving": "π","degrading": "π","stable": "β‘οΈ"}.get(summary['trend_direction'], "β")st.metric("Trend Direction",f"{trend_emoji} {summary['trend_direction'].title()}")with col2:if summary.get('worst_day'):st.metric("Worst Day",f"{summary['worst_day']['failure_rate']:.1f}%",delta=f"on {summary['worst_day']['date']}")if summary.get('best_day'):st.metric("Best Day",f"{summary['best_day']['failure_rate']:.1f}%",delta=f"on {summary['best_day']['date']}")# Health scoretry:client = get_metrics_client()trends = client.get_platform_trends(MetricsTimeframe(timeframe), [platform])if platform in trends:trend = trends[platform]# Calculate simple health scorehealth_score = max(0, 100 - (trend.average_failure_rate * 2))if health_score >= 80:health_color = "π’"health_status = "Excellent"elif health_score >= 60:health_color = "π‘"health_status = "Good"elif health_score >= 40:health_color = "π "health_status = "Fair"else:health_color = "π΄"health_status = "Poor"st.metric("Health Score",f"{health_color} {health_score:.0f}/100",delta=health_status)except Exception:pass # Skip health score if calculation failselse:st.info(f"No data available for {platform_key}")def render_trends_chart(timeframe: str):"""Render a simple trends visualization."""# This is a placeholder for actual chart rendering# In a real implementation, you'd use plotly, matplotlib, or similarst.info("π Trend charts would be displayed here with actual data visualization libraries like Plotly or Matplotlib")# Mock chart data descriptionst.markdown("""**Chart would show:**- Daily failure rates for each platform over the selected timeframe- Trend lines showing improvement/degradation- Annotations for significant events or changes- Comparative view across all platforms""")def render_header():"""Render the main header."""# Add Hugging Face Spaces infoif os.environ.get("SPACE_ID"):#st.info("π€ **Running on Hugging Face Spaces** - This demo uses mock data to showcase TFA capabilities!")col1, col2, col3 = st.columns([1, 3, 1])with col2:st.title("π Test Failure Analysis")st.markdown("*AI-powered multi-agent system for Gmail test failure triage*")# Add navigation tabstab1, tab2 = st.tabs(["π Failure Analysis", "π Metrics Dashboard"])return tab1, tab2def render_input_form():"""Render the input form for analysis."""st.subheader("π Analysis Input")col1, col2 = st.columns(2)with col1:invocation_id = st.text_input("Invocation ID",value="fe3e0b7f-7bb9-4524-8a79-3c62cf028243",help="UUID of the test invocation from Sponge")with col2:test_name = st.text_input("Test Name",value="mark_multiple_emails_as_read",help="Name or target ID of the failing test")additional_context = st.text_area("Additional Context (optional)",placeholder="Any additional information about the failure...",height=100)return invocation_id, test_name, additional_contextdef render_agent_pipeline():"""Render the agent pipeline visualization."""st.subheader("π Agent Pipeline")cols = st.columns(4)agents = [("π₯", "Information Collector", "Gathers logs, artifacts, history"),("π·οΈ", "Failure Classifier", "Categorizes with confidence"),("β‘", "Action Determiner", "Decides next steps"),("π", "Summarizer", "Generates reports"),]for i, (icon, name, desc) in enumerate(agents):with cols[i]:status = "π΅" if st.session_state.is_analyzing else "βͺ"st.markdown(f"""<div style="text-align: center; padding: 10px; border: 1px solid #ddd; border-radius: 10px;"><h2>{icon}</h2><h4>{name}</h4><p style="font-size: 12px; color: gray;">{desc}</p><p>{status}</p></div>""", unsafe_allow_html=True)def render_results(result: str):"""Render the analysis results."""st.subheader("π Analysis Results")# Create tabs for different viewstab1, tab2, tab3, tab4 = st.tabs(["π Full Report", "π¬ Slack", "π Ticket", "π Details"])with tab1:st.markdown(result)with tab2:# Extract Slack-style summaryst.markdown("### Slack Message Preview")st.code(f"""π΄ *Test Failure Alert*Analysis complete. See full report for details.π Full Analysis | π Bug Ticket | π Test Logs""")with tab3:st.markdown("### Bug Ticket Template")st.text_area("Copy this to your bug tracker:",value=f"## Test Failure Analysis\n\n{result[:500]}...",height=300)with tab4:render_analysis_details()def render_analysis_details():"""Render detailed analysis information."""if st.session_state.runner:context = st.session_state.runner.get_last_analysis_context()col1, col2 = st.columns(2)with col1:st.markdown("**Analysis Context**")st.json(context)with col2:st.markdown("**Memory Statistics**")stats = st.session_state.runner.get_memory_stats()st.json(stats)def render_classification_categories():"""Render the classification categories reference."""with st.expander("π Classification Categories Reference"):categories = {"Infrastructure": {"icon": "ποΈ","description": "Network, storage, device, test lab issues","examples": ["SocketTimeoutException", "Storage < 500MB", "Device offline"]},"Code Regression": {"icon": "π","description": "Recent CL broke functionality","examples": ["Pass rate drop after CL", "State management errors"]},"UI Regression": {"icon": "π¨","description": "UI/layout changes broke tests","examples": ["Element not found", "CSS changes", "Layout shifts"]},"Configuration": {"icon": "βοΈ","description": "Missing packages, wrong flags","examples": ["ActivityNotFoundException", "Feature flag mismatch"]},"Dependency": {"icon": "π¦","description": "External library/service issues","examples": ["ClassNotFoundException", "Version mismatch"]},"Test Logic Error": {"icon": "π§ͺ","description": "Bug in test code itself","examples": ["Wrong selector", "Race condition", "Always flaky"]},"Unknown": {"icon": "β","description": "Insufficient evidence","examples": ["Intermittent", "Non-reproducible"]}}cols = st.columns(3)for i, (cat, info) in enumerate(categories.items()):with cols[i % 3]:st.markdown(f"""**{info['icon']} {cat}**{info['description']}*Examples:* {', '.join(info['examples'][:2])}""")def render_history():"""Render analysis history sidebar."""if st.session_state.analysis_history:st.subheader("π Recent Analyses")for i, entry in enumerate(reversed(st.session_state.analysis_history[-5:])):with st.expander(f"{entry['test_name'][:25]}... ({entry['timestamp']})", expanded=False):st.markdown(f"**Invocation:** `{entry['invocation_id'][:8]}...`")st.markdown(f"**Platform:** {entry['platform']}")st.markdown(f"**Duration:** {entry['duration']:.1f}s")if st.button(f"View Result", key=f"view_{i}"):st.session_state.current_result = entry['result']async def run_analysis_async(invocation_id: str,test_name: str,additional_context: str,platform: str,use_mock: bool,mock_scenario: Optional[str],) -> tuple[str, float]:"""Run the TFA analysis pipeline asynchronously.Returns:Tuple of (result_string, duration_seconds)"""start_time = time.time()# Configure mock if enabledif use_mock and mock_scenario:use_mock_client(mock_scenario)# Initialize runner if neededif st.session_state.runner is None:st.session_state.runner = TFARunner()runner = st.session_state.runner# Determine platformplatform_hint = None if platform == "Auto-detect" else platform# Run analysisresult = await runner.analyze_failure_async(invocation_id=invocation_id,test_name=test_name,additional_context=additional_context,platform=platform_hint,)duration = time.time() - start_timereturn result, durationdef run_analysis(invocation_id: str,test_name: str,additional_context: str,platform: str,use_mock: bool,mock_scenario: Optional[str],) -> tuple[str, float]:"""Synchronous wrapper for run_analysis_async."""return asyncio.run(run_analysis_async(invocation_id=invocation_id,test_name=test_name,additional_context=additional_context,platform=platform,use_mock=use_mock,mock_scenario=mock_scenario,))def main():"""Main Streamlit application entry point."""# Initialize session stateinit_session_state()# Initialize metrics dashboard stateif "show_metrics_dashboard" not in st.session_state:st.session_state.show_metrics_dashboard = False# Check TFA availabilityif not TFA_AVAILABLE:st.error(f"β οΈ TFA modules not available: {IMPORT_ERROR}")st.info("Make sure you're running from the project root and dependencies are installed.")st.code("pip install -r requirements.txt", language="bash")return# Render sidebar and get configplatform, use_mock, mock_scenario = render_sidebar()# Main content area with tabsanalysis_tab, metrics_tab = render_header()with analysis_tab:render_analysis_page(platform, use_mock, mock_scenario)with metrics_tab:render_metrics_dashboard()def render_analysis_page(platform, use_mock, mock_scenario):"""Render the main failure analysis page."""st.divider()# Input forminvocation_id, test_name, additional_context = render_input_form()# Analysis buttoncol1, col2, col3 = st.columns([1, 2, 1])with col2:analyze_button = st.button("π Run Analysis",type="primary",use_container_width=True,disabled=st.session_state.is_analyzing,)st.divider()# Agent pipeline visualizationrender_agent_pipeline()st.divider()# Run analysis when button clickedif analyze_button and invocation_id and test_name:st.session_state.is_analyzing = Truewith st.spinner("π Analyzing test failure... This may take a moment."):try:# Progress indicatorsprogress_bar = st.progress(0)status_text = st.empty()# Simulate progress (actual analysis is async)status_text.text("π₯ Information Collector gathering data...")progress_bar.progress(25)result, duration = run_analysis(invocation_id=invocation_id,test_name=test_name,additional_context=additional_context,platform=platform,use_mock=use_mock,mock_scenario=mock_scenario,)progress_bar.progress(100)status_text.text("β Analysis complete!")# Store resultst.session_state.current_result = result# Add to historyst.session_state.analysis_history.append({"invocation_id": invocation_id,"test_name": test_name,"platform": platform,"result": result,"duration": duration,"timestamp": datetime.now().strftime("%H:%M:%S"),})st.success(f"β Analysis completed in {duration:.1f} seconds")except Exception as e:st.error(f"β Analysis failed: {str(e)}")st.exception(e)finally:st.session_state.is_analyzing = False# Display resultsif st.session_state.current_result:render_results(st.session_state.current_result)# Classification referencerender_classification_categories()# History in sidebarwith st.sidebar:render_history()if __name__ == "__main__":main()
tfa_ui/app.py+753-753