#!/usr/bin/env python3 """ test_tier4_chrome_web_e2e.py — Tier 4 Real Headless Chrome 156 CDP Web Frontend E2E Drives real Chromium 156 (`/root/.cache/puppeteer/chrome/linux-156.0.8078.47/chrome-linux64/chrome`) over Chrome DevTools Protocol (CDP WebSocket) against live `stl_native_server` + HIL cluster: 1. Real password login (`#login-form`, `xjkj123456!`) & workbench initialization (0 JS exceptions) 2. Tab 5 Watchdog settings UI (`#wd-link-lost-s`, `#wd-dense-silence-s`, `#btn-save-watchdog`) persisting via `ConfigureWatchdog` RPC to `stl_native_server` 3. Live Overview DOM alerting during >5s dual-disconnect (`#watchdog-alert-banner` `dataset.alertKind == "link_offline_waiting"`) -> recovery (`dataset.alertKind == "serial_gap_detected"`) 4. Live RMT hard-hang DOM alerting (`dataset.alertKind == "stage_hang_timeout"`, scene-preserved & `0x08 00` cooling badges, AND G27 fix keeping `#dimm-replacement-banner` visible) """ import asyncio import contextlib import json import os from pathlib import Path import shutil import subprocess import sys import tempfile import time from typing import Any, Callable, Dict, List, Optional import aiohttp ROOT_DIR = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster")) from cluster_harness import HilClusterStack # noqa: E402 CHROME_CANDIDATES = [ "/root/.cache/puppeteer/chrome/linux-156.0.8078.47/chrome-linux64/chrome", shutil.which("google-chrome") or "", shutil.which("chromium") or "", shutil.which("chromium-browser") or "", ] def find_chrome_binary() -> str: for c in CHROME_CANDIDATES: if c and os.path.isfile(c) and os.access(c, os.X_OK): return c raise FileNotFoundError("Headless Chrome binary not found") async def wait_until( pred: Callable[[], Any], timeout_s: float = 25.0, interval_s: float = 0.25, desc: str = "condition", ) -> Any: deadline = time.monotonic() + timeout_s last_val = None while time.monotonic() < deadline: res = pred() if asyncio.iscoroutine(res): res = await res last_val = res if res: return res await asyncio.sleep(interval_s) raise AssertionError(f"Timed out ({timeout_s}s) waiting for {desc}; last={last_val}") class CdpPageClient: """Lightweight async Chrome DevTools Protocol (CDP) page controller over `aiohttp`.""" def __init__(self, http: aiohttp.ClientSession, debug_port: int): self.http = http self.debug_port = debug_port self.ws: Optional[aiohttp.ClientWebSocketResponse] = None self.reader_task: Optional[asyncio.Task] = None self.seq = 0 self.pending: Dict[int, asyncio.Future] = {} self.js_exceptions: List[str] = [] async def connect_first_page(self, target_url: str, timeout_s: float = 12.0) -> None: deadline = time.monotonic() + timeout_s ws_url = "" while time.monotonic() < deadline: try: async with self.http.put( f"http://127.0.0.1:{self.debug_port}/json/new?{target_url}", timeout=aiohttp.ClientTimeout(total=2.0), ) as r: if r.status == 200: info = await r.json() ws_url = info.get("webSocketDebuggerUrl", "") if ws_url: break except Exception: pass await asyncio.sleep(0.2) if not ws_url: raise TimeoutError("Failed to open CDP page target") self.ws = await self.http.ws_connect(ws_url, max_msg_size=16 * 1024 * 1024) self.reader_task = asyncio.create_task(self._read_loop()) await self.send("Page.enable") await self.send("Runtime.enable") async def _read_loop(self) -> None: assert self.ws is not None try: async for msg in self.ws: if msg.type != aiohttp.WSMsgType.TEXT: continue data = json.loads(msg.data) if "id" in data and data["id"] in self.pending: fut = self.pending.pop(data["id"]) if not fut.done(): fut.set_result(data) elif data.get("method") == "Runtime.exceptionThrown": details = (data.get("params") or {}).get("exceptionDetails") or {} self.js_exceptions.append(json.dumps(details, ensure_ascii=False)) except Exception as exc: for fut in self.pending.values(): if not fut.done(): fut.set_exception(exc) async def send(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: float = 10.0) -> Dict[str, Any]: assert self.ws is not None self.seq += 1 cid = self.seq fut = asyncio.get_running_loop().create_future() self.pending[cid] = fut await self.ws.send_json({"id": cid, "method": method, "params": params or {}}) try: resp = await asyncio.wait_for(fut, timeout=timeout) finally: self.pending.pop(cid, None) if "error" in resp: raise RuntimeError(f"CDP {method} error: {resp['error']}") return resp.get("result") or {} async def eval_js(self, expression: str) -> Any: res = await self.send( "Runtime.evaluate", {"expression": expression, "returnByValue": True, "awaitPromise": True}, ) if "exceptionDetails" in res: raise RuntimeError(f"JS eval exception: {res['exceptionDetails']}") return (res.get("result") or {}).get("value") async def close(self) -> None: if self.ws is not None: with contextlib.suppress(Exception): await self.ws.close() if self.reader_task is not None: self.reader_task.cancel() with contextlib.suppress(asyncio.CancelledError, Exception): await self.reader_task async def run_tier4_web_suite() -> Dict[str, Any]: t0 = time.monotonic() chrome_bin = find_chrome_binary() cdp_port = 19322 user_data_dir = Path(tempfile.mkdtemp(prefix="xjkj_stl_chrome_")) chrome_proc: Optional[subprocess.Popen] = None results = [] try: async with HilClusterStack( web_port=18984, tftp_port=19074, bmc_ctrl_port=19299, hil_http_port=19298, uart_base=19240, web_password="xjkj123456!", speed_scale=0.18, station_ips=["127.0.3.166", "127.0.3.165", "127.0.3.167", "127.0.3.168"], ) as stack: assert stack.admin_ws is not None assert stack.http_session is not None await stack.wait_station_online("S1", timeout_s=15.0) env = dict(os.environ) for k in ( "LD_LIBRARY_PATH", "http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY", "all_proxy", "ALL_PROXY", ): env.pop(k, None) chrome_proc = subprocess.Popen( [ chrome_bin, "--headless=new", "--no-sandbox", "--no-proxy-server", "--disable-gpu", "--disable-dev-shm-usage", "--no-first-run", "--window-size=1600,1080", f"--user-data-dir={user_data_dir}", f"--remote-debugging-port={cdp_port}", "about:blank", ], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=env, ) cdp = CdpPageClient(stack.http_session, cdp_port) await cdp.connect_first_page(f"http://127.0.0.1:{stack.web_port}/") try: # ============================================================ # Scenario 1: Real Web Login Flow (`#login-form` -> Workbench) # ============================================================ print("[Tier4][1/4] Verifying Chrome 156 password login gate & live workbench initialization...", flush=True) await wait_until( lambda: cdp.eval_js("!!document.getElementById('admin-password')"), timeout_s=10.0, desc="Login page #admin-password", ) await cdp.eval_js( """(() => { const inp = document.getElementById('admin-password'); inp.value = 'xjkj123456!'; document.getElementById('login-form').requestSubmit(); return true; })()""" ) await wait_until( lambda: cdp.eval_js("!!document.getElementById('watchdog-alert-banner') && document.querySelectorAll('#cpu0-grid .dimm-slot').length === 12"), timeout_s=15.0, desc="Main workbench loaded with 24 DIMM slots", ) assert not cdp.js_exceptions, f"Unexpected JS exceptions after login: {cdp.js_exceptions}" results.append({"scenario": "1_chrome_login_and_workbench_boot", "status": "PASS"}) print(" -> PASS", flush=True) # ============================================================ # Scenario 2: Tab 5 Watchdog Settings Panel -> `ConfigureWatchdog` # ============================================================ print("[Tier4][2/4] Verifying Tab 5 Watchdog settings UI & persistence in Chrome...", flush=True) await cdp.eval_js( """(() => { const tabBtn = document.querySelector('[data-page="plans"], [data-nav-page="plans"]'); if (tabBtn) tabBtn.click(); return !!tabBtn; })()""" ) await wait_until( lambda: cdp.eval_js("!!document.getElementById('btn-save-watchdog')"), timeout_s=8.0, desc="#btn-save-watchdog present", ) await cdp.eval_js( """(() => { document.getElementById('wd-link-lost-s').value = '180'; document.getElementById('wd-dense-silence-s').value = '95'; document.getElementById('wd-hang-action').value = 'retry_current_task'; document.getElementById('wd-max-hangs').value = '3'; document.getElementById('btn-save-watchdog').click(); return true; })()""" ) async def _wd_persisted(): ctrl = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"}) wd = ctrl.get("watchdog") or {} return wd if wd.get("link_lost_timeout_ms") == 180000 and wd.get("dense_stage_silence_timeout_ms") == 95000 and wd.get("hang_action") == "retry_current_task" and wd.get("max_consecutive_hangs") == 3 else None await wait_until(_wd_persisted, timeout_s=8.0, desc="Watchdog config persisted via Web UI") # Switch back to Overview tab (`overview`) await cdp.eval_js( """(() => { const ovBtn = document.querySelector('[data-page="overview"], [data-nav-page="overview"]'); if (ovBtn) ovBtn.click(); return true; })()""" ) results.append({"scenario": "2_tab5_watchdog_config_save", "status": "PASS"}) print(" -> PASS", flush=True) # ============================================================ # Scenario 3: Live `link_offline_waiting` -> `serial_gap_detected` Banner in Chrome # ============================================================ print("[Tier4][3/4] Verifying live `link_offline_waiting` & `serial_gap_detected` banners in Chrome DOM...", flush=True) await stack.enqueue_cmd( "S1", "ConfigureWatchdog", {"watchdog": {"link_lost_timeout_ms": 45000, "dense_stage_silence_timeout_ms": 40000, "reboot_on_hang": False}}, ) await stack.trigger_dut_boot(0, reason="tier4_dual_drop") await asyncio.sleep(0.3) await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "start"}) await stack.set_link(0, bmc_up=False, serial_up=False) async def _dom_link_waiting(): return await cdp.eval_js( """(() => { const b = document.getElementById('watchdog-alert-banner'); if (!b || b.classList.contains('hidden')) return null; return b.dataset.alertKind === 'link_offline_waiting' ? b.textContent : null; })()""" ) banner_wait_txt = await wait_until(_dom_link_waiting, timeout_s=35.0, desc="Chrome #watchdog-alert-banner link_offline_waiting") assert "同时断联保护中" in banner_wait_txt, f"Unexpected banner text: {banner_wait_txt}" # Restore S1 links -> verify banner switches live to `serial_gap_detected`! await stack.set_link(0, bmc_up=True, serial_up=True) async def _dom_serial_gap(): return await cdp.eval_js( """(() => { const b = document.getElementById('watchdog-alert-banner'); if (!b || b.classList.contains('hidden')) return null; return b.dataset.alertKind === 'serial_gap_detected' ? b.textContent : null; })()""" ) banner_gap_txt = await wait_until(_dom_serial_gap, timeout_s=15.0, desc="Chrome #watchdog-alert-banner serial_gap_detected") assert "serial_gap_detected" in banner_gap_txt, f"Unexpected gap banner text: {banner_gap_txt}" results.append({"scenario": "3_chrome_live_dual_drop_and_serial_gap_banners", "status": "PASS"}) print(" -> PASS", flush=True) # ============================================================ # Scenario 4: Live RMT Hard-Hang `stage_hang_timeout` Banner + G27 Fix # ============================================================ print("[Tier4][4/4] Verifying live `stage_hang_timeout` red alert banner + G27 `#dimm-replacement-banner` visibility in Chrome...", flush=True) await stack.connect_and_heat_backend_hood("S1", 0, target_c=70) await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.15) await stack.enqueue_cmd( "S1", "SaveBootPlan", { "plan": { "preset": "auto", "mt_enabled": False, "run_rmt": True, "stages": {"uip1": "auto", "amt": "auto", "uip2": "auto", "uefi": "auto"}, }, "watchdog": {"dense_stage_silence_timeout_ms": 2200, "reboot_on_hang": False}, }, ) await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "restart"}) async def _dom_hang_alert(): return await cdp.eval_js( """(() => { const wb = document.getElementById('watchdog-alert-banner'); const db = document.getElementById('dimm-replacement-banner'); if (!wb || wb.classList.contains('hidden')) return null; if (wb.dataset.alertKind !== 'stage_hang_timeout') return null; return { wdText: wb.textContent, dimmBannerVisible: !!(db && !db.classList.contains('hidden')), dimmBannerText: db ? db.textContent : '' }; })()""" ) hang_dom = await wait_until(_dom_hang_alert, timeout_s=25.0, desc="Chrome #watchdog-alert-banner stage_hang_timeout") assert "stage_hang_timeout" in hang_dom["wdText"] assert "保留死机现场" in hang_dom["wdText"] assert "0x08 00" in hang_dom["wdText"] assert hang_dom["dimmBannerVisible"] is True, f"G27 regression: #dimm-replacement-banner hidden on hang fault! {hang_dom}" assert not cdp.js_exceptions, f"Uncaught JS exceptions during Web E2E: {cdp.js_exceptions}" results.append({"scenario": "4_chrome_stage_hang_alert_and_g27_banner_fix", "status": "PASS"}) print(" -> PASS", flush=True) # ============================================================ # Scenario 5: Phase 1 Production/Engineering Switch, Single-DIMM Curve & Excel Export # ============================================================ print("[Tier4][5/5] Verifying Production/Engineering view switch, single-DIMM curve modal & alarms.xlsx...", flush=True) await cdp.eval_js( """(() => { document.getElementById('btn-mode-production').click(); return document.body.dataset.uiMode; })()""" ) prod_cards = await wait_until( lambda: cdp.eval_js("document.querySelectorAll('#prod-stations-grid .prod-station-card').length >= 4 && document.querySelectorAll('#prod-stations-grid .prod-dimm-cell').length >= 96"), timeout_s=8.0, desc="Production dashboard 4+ cards and 96+ DIMM cells", ) assert prod_cards is True # Click first DIMM cell to open single-DIMM temperature curve modal await cdp.eval_js( """(() => { document.querySelector('#prod-stations-grid .prod-dimm-cell').click(); return true; })()""" ) curve_open = await wait_until( lambda: cdp.eval_js("!document.getElementById('stl-dimm-curve-modal').classList.contains('hidden') && !!document.getElementById('dimm-curve-canvas')"), timeout_s=6.0, desc="Single-DIMM temperature curve modal open", ) assert curve_open is True await cdp.eval_js("document.getElementById('dimm-curve-close').click(); document.getElementById('btn-mode-engineering').click(); true") # Verify alarms.xlsx download via browser authenticated fetch (valid PK ZIP signature) xlsx_ok = await cdp.eval_js( """(async () => { const r = await fetch('/api/stations/S1/alarms.xlsx', { credentials: 'same-origin' }); if (!r.ok) return { ok: false, status: r.status }; const buf = new Uint8Array(await r.arrayBuffer()); return { ok: buf.length > 500 && buf[0] === 0x50 && buf[1] === 0x4b, size: buf.length }; })()""" ) assert xlsx_ok and xlsx_ok.get("ok") is True, f"alarms.xlsx export failed: {xlsx_ok}" assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 5: {cdp.js_exceptions}" results.append({"scenario": "5_production_view_dimm_curve_and_xlsx", "status": "PASS", "xlsx_size": xlsx_ok.get("size")}) print(f" -> PASS (alarms.xlsx={xlsx_ok.get('size')} bytes)", flush=True) # ============================================================ # Scenario 6: Phase 2 Full-Detail Frontend + Backend Trace, Dynamic Toggle & .tar Bundle # ============================================================ print("[Tier4][6/6] Verifying Phase 2 full-detail frontend+backend trace ingestion, toggle OFF & .tar bundle...", flush=True) await cdp.eval_js("window.stlTrace && window.stlTrace.flush(false)") trace_st = await wait_until( lambda: cdp.eval_js( """(async () => { const r = await fetch('/api/trace/status', { credentials: 'same-origin' }); if (!r.ok) return null; const d = await r.json(); return (d.frontend_events_ingested > 0 && d.written_events > 0) ? d : null; })()""" ), timeout_s=10.0, desc="Frontend trace events ingested on disk", ) # Verify .tar diagnostic bundle download tar_ok = await cdp.eval_js( """(async () => { const r = await fetch('/api/trace/bundle?station_id=S1', { credentials: 'same-origin' }); if (!r.ok) return { ok: false, status: r.status }; const txt = await r.text(); return { ok: txt.includes('trace/config.json') && txt.includes('frontend.0001.jsonl') && txt.includes('backend.0001.jsonl'), size: txt.length }; })()""" ) assert tar_ok and tar_ok.get("ok") is True, f"Diagnostic .tar bundle invalid: {tar_ok}" # Toggle trace OFF dynamically via UI/HTTP and verify WS broadcast syncs browser trace.js immediately await cdp.eval_js( """(async () => { await fetch('/api/trace/config', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled: false }), }); return true; })()""" ) toggled_off = await wait_until( lambda: cdp.eval_js("window.stlTrace && window.stlTrace.isActive() === false"), timeout_s=6.0, desc="Browser stlTrace dynamically disabled via WS broadcast", ) assert toggled_off is True # Verify Phase 3 6-tier hardware info endpoint hw_ok = await cdp.eval_js( """(async () => { const r = await fetch('/api/hw/info', { credentials: 'same-origin' }); if (!r.ok) return null; const d = await r.json(); return (d.available === true && typeof d.tier_name === 'string' && d.opencl_igpu) ? d : null; })()""" ) assert hw_ok and hw_ok.get("available") is True, f"/api/hw/info invalid: {hw_ok}" # Re-enable so default state remains intact await cdp.eval_js( """(async () => { await fetch('/api/trace/config', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled: true }), }); return true; })()""" ) assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 6: {cdp.js_exceptions}" results.append({"scenario": "6_full_detail_trace_frontend_backend_and_toggle", "status": "PASS", "fe_events": trace_st.get("frontend_events_ingested"), "tar_size": tar_ok.get("size")}) print(f" -> PASS (fe_events={trace_st.get('frontend_events_ingested')}, tar={tar_ok.get('size')}B)", flush=True) # ============================================================ # Scenario 7: Phase 4 Built-in PXE/ProxyDHCP UI, Full BMC Sensor Table & Console-Expand Tab Fix # ============================================================ print("[Tier4][7/7] Verifying Phase 4 BMC Full Sensor Table, Console-Expand Tab Fix & Built-in PXE/ProxyDHCP UI...", flush=True) # 7a. Full BMC sensor table on Overview shows Voltage/Fan/Power from live RMCP+ SDR bmc_dom = await wait_until( lambda: cdp.eval_js( """(() => { const tb = document.getElementById('bmc-sensors-tbody'); if (!tb) return null; const txt = tb.textContent || ''; return (txt.includes('P12V') && txt.includes('FAN1_RPM') && txt.includes('PSU1_PIN_W')) ? txt.length : null; })()""" ), timeout_s=10.0, desc="BMC full sensor table (P12V, FAN1_RPM, PSU1_PIN_W) in Chrome", ) assert bmc_dom and bmc_dom > 50 # 7b. Console expand on Overview must NOT hide Testing page when switching tabs! await cdp.eval_js( """(() => { document.getElementById('btn-console-expand')?.click(); document.querySelector('[data-page="testing"]')?.click(); return true; })()""" ) pxe_ui_ok = await wait_until( lambda: cdp.eval_js( """(() => { const left = document.querySelector('.workspace-left'); const card = document.getElementById('pxe-dhcp-card'); const modeSel = document.getElementById('pxe-dhcp-mode'); const portTxt = document.getElementById('pxe-port-status')?.textContent || ''; if (!left || !card || !modeSel) return null; const visible = getComputedStyle(left).display !== 'none'; return (visible && portTxt.includes('HTTP Boot:')) ? { visible, mode: modeSel.value, portTxt } : null; })()""" ), timeout_s=8.0, desc="Built-in PXE/ProxyDHCP panel visible after console-expand tab switch", ) assert pxe_ui_ok and pxe_ui_ok.get("visible") is True # 7c. Trigger 1-click LAN DHCP/PXE self-check in Chrome and verify result renders await cdp.eval_js("document.getElementById('btn-probe-pxe-network')?.click(); true") probe_txt = await wait_until( lambda: cdp.eval_js( """(() => { const b = document.getElementById('pxe-probe-result'); if (!b || b.classList.contains('hidden')) return null; return b.textContent.includes('诊断结论:') ? b.textContent : null; })()""" ), timeout_s=10.0, desc="LAN DHCP/PXE self-check output in Chrome", ) assert "诊断结论:" in probe_txt assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 7: {cdp.js_exceptions}" results.append({"scenario": "7_phase4_bmc_sensors_console_tab_fix_and_builtin_pxe_ui", "status": "PASS"}) print(" -> PASS", flush=True) finally: await cdp.close() elapsed_s = round(time.monotonic() - t0, 2) summary = {"tier": "Tier4_Headless_Chrome156_Web_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results} print(f"\n[Tier4] ALL 7 HEADLESS CHROME 156 WEB E2E SCENARIOS PASSED in {elapsed_s}s!", flush=True) return summary finally: if chrome_proc and chrome_proc.poll() is None: with contextlib.suppress(Exception): chrome_proc.terminate() chrome_proc.wait(timeout=3.0) if chrome_proc.poll() is None: with contextlib.suppress(Exception): chrome_proc.kill() shutil.rmtree(user_data_dir, ignore_errors=True) if __name__ == "__main__": res = asyncio.run(run_tier4_web_suite()) out_file = ROOT_DIR / "build" / "sim" / "tier4_chrome_web_report.json" out_file.parent.mkdir(parents=True, exist_ok=True) out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")