""" gui/sidebar.py ───────────────────────────────────────────────────────────────────────────── A-LEMS sidebar — Phase 3: 11 clean section buttons. Sidebar contains: • Brand panel (logo, name, version, connection dot) • Active session banner • Live Lab panel (connect/disconnect) • 11 section navigation buttons (coloured dot + name) • Theme toggle • Footer (RAPL spark bars + stats) Session state written here: nav_section — clicked section name | None nav_page — None (always cleared on section click → goes to landing) nav_last — preserved (not touched here) render_sidebar() returns None (dispatcher reads session state directly). ───────────────────────────────────────────────────────────────────────────── """ import streamlit as st from gui.config import SECTIONS, SECTION_PAGES, SECTION_ACCENTS, DB_PATH, STATUS_COLORS from gui.db import q1 from gui.connection import get_conn, verify_connection, disconnect from gui.theme import _tokens # ── CSS ─────────────────────────────────────────────────────────────────────── def _css(t: dict) -> str: return f""" """ # ── Helpers ─────────────────────────────────────────────────────────────────── def _read_live_url() -> dict: import json as _j from pathlib import Path as _P for p in [_P(__file__).parent.parent / "live_url.json", _P("live_url.json")]: if p.exists(): try: return _j.loads(p.read_text()) except Exception: pass return {} def _divider(t: dict): st.markdown( f"
", unsafe_allow_html=True) # ── Brand panel ─────────────────────────────────────────────────────────────── def _brand(t: dict, online: bool): dot_clr = "#22c55e" if online else t["t3"] dot_glow = "box-shadow:0 0 0 3px #22c55e22;" if online else "" # Logo click → go to overview (clear section) st.markdown( f"
" f"
" f"
" f"" f"" f"" f"" f"" f"" f"" f"" f"" f"" f"" f"" f"" f"
" f"A-LEMS" f"v2.1" f"
" f"
" f"
" f"AI Energy Measurement
" f"
", unsafe_allow_html=True) # Logo → overview if st.button("⌂ Home · Overview", key="nav_home", use_container_width=True): st.session_state["nav_section"] = None st.session_state["nav_page"] = None st.rerun() # ── Session banner ──────────────────────────────────────────────────────────── def _session_banner(t: dict): try: row = q1(""" SELECT group_id, COUNT(*) as total_exps, SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as done, SUM(CASE WHEN status='running' THEN 1 ELSE 0 END) as running, SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) as failed, SUM(runs_completed) as runs_done, SUM(runs_total) as runs_total FROM experiments WHERE group_id=(SELECT group_id FROM experiments ORDER BY exp_id DESC LIMIT 1) GROUP BY group_id """) if not row or not row.get("group_id"): return total = int(row.get("total_exps", 0)) done = int(row.get("done", 0)) run_ = int(row.get("running", 0)) fail_ = int(row.get("failed", 0)) runs_d = int(row.get("runs_done", 0) or 0) runs_t = int(row.get("runs_total", 1) or 1) if run_: status, clr = "RUNNING", STATUS_COLORS["running"] elif fail_: status, clr = "FAILED", STATUS_COLORS["failed"] elif done == total: status, clr = "COMPLETED", STATUS_COLORS["completed"] else: status, clr = "PENDING", STATUS_COLORS["pending"] short = row["group_id"].replace("session_", "").replace("_", " ", 1)[:18] pct = int(runs_d / max(runs_t, 1) * 100) st.markdown( f"
" f"
" f"
" f"" f"Active Session
" f"
{short}
" f"
" f"{status} · {done}/{total} exps · {runs_d}/{runs_t} runs
" f"
" f"
" f"
", unsafe_allow_html=True) except Exception: pass # ── Live Lab panel ──────────────────────────────────────────────────────────── def _live_lab(t: dict): conn = get_conn() online = conn.get("verified", False) _live = _read_live_url() lab_live = _live.get("online", False) clr = STATUS_COLORS["running"] if online else t["accent"] sub = ("Connected · " + conn["url"].replace("https://", "")[:26] if online else ("🟢 Lab online — click Connect" if lab_live else "Offline · analysis mode")) st.markdown( f"
" f"
" f"{'🟢' if online else '🔌'} Live Lab
" f"
{sub}
" f"
", unsafe_allow_html=True) if online: hclr = STATUS_COLORS["running"] if conn.get("harness") else STATUS_COLORS["pending"] st.markdown( f"
" f"● {'Harness ready' if conn.get('harness') else 'Harness unavailable'}
", unsafe_allow_html=True) if st.button("⏏ Disconnect", key="nav_disconnect", use_container_width=True): disconnect() st.rerun() else: if "show_connect" not in st.session_state: st.session_state["show_connect"] = False if st.button("⚡ Connect to Live Lab", key="toggle_connect", use_container_width=True): st.session_state["show_connect"] = not st.session_state["show_connect"] if st.session_state["show_connect"]: st.markdown( f"
" f"Run tunnel_agent.py on your lab machine.
" f"URL changes each session.
", unsafe_allow_html=True) _au = _live.get("url", "") if lab_live else "" _at = _live.get("token", "") if lab_live else "" if lab_live and _au: st.markdown( f"
" f"🟢 Auto-detected!
", unsafe_allow_html=True) _url = st.text_input("Lab URL", value=_au, placeholder="https://xxxx.trycloudflare.com", key="conn_url") _tok = st.text_input("Access token", value=_at, placeholder="alems-xxxxxxxxxxxxxxxx", type="password", key="conn_tok") if st.button("🔗 Connect", key="nav_connect", use_container_width=True): if not _url: st.error("Enter the lab URL") elif not _tok: st.error("Enter the access token") else: with st.spinner("Connecting..."): ok, msg, harness = verify_connection(_url, _tok) if ok: conn.update({"url": _url.rstrip("/"), "token": _tok, "verified": True, "harness": harness, "mode": "online", "error": ""}) st.session_state["conn"] = conn st.success(f"Connected · harness {'ready' if harness else 'unavailable'}") st.rerun() else: conn["error"] = msg st.session_state["conn"] = conn st.error(msg) if conn.get("error"): st.caption(f"Last error: {conn['error']}") # ── Section nav — THE MAIN CHANGE: 11 clean buttons ────────────────────────── def _nav(t: dict): """11 section buttons. Coloured dot + name. Active section highlighted.""" active_section = st.session_state.get("nav_section") for section in SECTIONS: data = SECTION_PAGES[section] accent = data["accent"] active = (section == active_section) # Wrap active item for CSS if active: st.markdown("
", unsafe_allow_html=True) # Button label: coloured dot + section name # We can't put HTML in button labels — use unicode bullet styled via CSS label = f" {section}" # spaces reserved for ::before dot #_icons = {"COMMAND CENTRE":":material/terminal:","ENERGY & SILICON":":material/bolt:","AGENTIC INTELLIGENCE":":material/psychology:","DATA MOVEMENT":":material/swap_horiz:","SESSIONS & RUNS":":material/history:","RESEARCH & INSIGHTS":":material/biotech:","ENVIRONMENT":":material/eco:","DATA QUALITY":":material/fact_check:","SILICON LAB":":material/memory:","DEVELOPER TOOLS":":material/code:","SETTINGS":":material/settings:"} if st.button(label, key=f"sec_{section}", use_container_width=True): st.session_state["nav_section"] = section st.session_state["nav_page"] = None # always show landing first st.rerun() if active: st.markdown("
", unsafe_allow_html=True) # Inject dot colours via CSS targeted at each button's aria-label dot_css = "" for section in SECTIONS: accent = SECTION_PAGES[section]["accent"] safe = section.replace("'", "\\'").replace("&", "\\&") dot_css += f""" [data-testid="stSidebar"] button[aria-label=" {safe}"] p {{ color: {accent}cc !important; text-align: left !important; }} [data-testid="stSidebar"] button[aria-label="{safe}"]::before {{ display: none !important; }} [data-testid="stSidebar"] button[aria-label=" {safe}"]:hover {{ border-left: 2px solid {accent}66 !important; }} [data-testid="stSidebar"] button[aria-label=" {safe}"]:hover p {{ color: {accent} !important; }} """ # Active section gets full accent border active_sec = st.session_state.get("nav_section", "") if active_sec and active_sec in SECTION_PAGES: acc = SECTION_PAGES[active_sec]["accent"] safe_a = active_sec.replace("'", "\\'").replace("&", "\\&") dot_css += f""" .alems-active [data-testid="stButton"] > button[aria-label=" {safe_a}"] {{ border-left: 2px solid {acc} !important; }}""" dot_css += """ [data-testid="stSidebar"] .stButton > button { -webkit-user-select: none; } [data-testid="stSidebar"] .stButton > button::after { display: none !important; } [data-testid="stSidebar"] .stButton > button p { pointer-events: none; text-align: left !important; } """ st.markdown(f"", unsafe_allow_html=True) # ── Settings ────────────────────────────────────────────────────────────────── def _settings(t: dict): dark = st.session_state.get("theme", "dark") == "dark" if st.button("☀ Light mode" if dark else "☾ Dark mode", key="sidebar_theme_toggle", use_container_width=True): st.session_state["theme"] = "light" if dark else "dark" st.rerun() # ── Footer ──────────────────────────────────────────────────────────────────── def _footer(t: dict): _divider(t) _h = [6,8,10,7,12,9,11,8,14,10,13,9,11,8,10,12,9,7,11,13,10,8,12,9,11,10,8,13] _c = [SECTION_ACCENTS["ENERGY & SILICON"], SECTION_ACCENTS["COMMAND CENTRE"], SECTION_ACCENTS["AGENTIC INTELLIGENCE"], SECTION_ACCENTS["DATA MOVEMENT"]] bars = "".join( f"
" for i, h in enumerate(_h)) st.markdown( f"
{bars}
", unsafe_allow_html=True) try: nr = q1("SELECT COUNT(*) AS n FROM runs").get("n", "—") ne = q1("SELECT COUNT(*) AS n FROM experiments").get("n", "—") ns = q1("SELECT COUNT(DISTINCT group_id) AS n FROM experiments").get("n", "—") st.markdown( f"
" + "".join( f"
{v}
" f"
{l}
" for v, l in [(nr, "Runs"), (ne, "Exps"), (ns, "Sessions")] ) + "
" f"
" f"{DB_PATH.name} · RAPL · perf · psutil
", unsafe_allow_html=True) except Exception: pass if st.button("⟳ Refresh", key="nav_refresh", use_container_width=True): st.cache_data.clear() st.rerun() # ── Entry point ─────────────────────────────────────────────────────────────── def render_sidebar() -> None: """Render sidebar. Sets nav_section + nav_page in session_state.""" dark = st.session_state.get("theme", "dark") == "dark" t = _tokens(dark) # Initialise state on first load if "nav_section" not in st.session_state: st.session_state["nav_section"] = None if "nav_page" not in st.session_state: st.session_state["nav_page"] = None if "nav_last" not in st.session_state: st.session_state["nav_last"] = {} with st.sidebar: st.markdown(_css(t), unsafe_allow_html=True) conn = get_conn() online = conn.get("verified", False) _brand(t, online) _session_banner(t) _live_lab(t) st.markdown( f"
", unsafe_allow_html=True) _nav(t) st.markdown( f"
", unsafe_allow_html=True) _settings(t) _footer(t)