"""Render src/ui/index.html headlessly with a mocked pywebview API and save a PNG screenshot. No window is shown and the real desktop/mouse is never touched. Usage: python tools/preview_ui.py # healthy state, 1180x790 python tools/preview_ui.py --state bad # broken state (health issues listed) python tools/preview_ui.py --tab opencode --size 1180x1000 --out shot.png python tools/preview_ui.py --view simple # Simple view (default unless --tab is given) python tools/preview_ui.py --page notify --notice hop # notification popup python tools/preview_ui.py --page tray --state bad # tray menu python tools/preview_ui.py --mode tor # connection type tor | custom | clean | warp python tools/preview_ui.py --eval "document.getElementById('btnUninstall').click()" python tools/preview_ui.py --modal report-files # Report-a-problem dialog (report | report-files | report-sent | report-error) Any JavaScript error (or console.error) is drawn as a red box in the top-left corner of the screenshot, so a clean screenshot means the page ran without errors. Open the PNG afterwards to review it. """ from __future__ import annotations import argparse import json import pathlib import re import subprocess import tempfile import time ROOT = pathlib.Path(__file__).resolve().parent.parent EDGE_CANDIDATES = ( r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", r"C:\Program Files\Microsoft\Edge\Application\msedge.exe", ) def mock_state(kind: str, mode: str) -> dict: now = int(time.time()) health = { "ok": {"status": "ok", "title": "Everything is working", "sub": "OpenCode is connected through Cloudflare WARP and auto-rotates when you hit the limit.", "issues": []}, "warn": {"status": "warn", "title": "Working, with warnings", "sub": "OpenCode works, but something below should be turned on.", "issues": [ {"level": "warn", "title": "Auto-rotation is off", "detail": "Zen Guard isn't running, so when you hit the free limit you'll have to rotate manually.", "fix": "start_guard", "fix_label": "Turn on"}]}, "bad": {"status": "bad", "title": "OpenCode needs attention", "sub": "Fix the problem below and OpenCode will work again.", "issues": [ {"level": "bad", "title": "OpenCode can't connect right now", "detail": "OpenCode is set to go through the local proxy (port 41987), but it isn't running. " "Messages fail with ECONNREFUSED until it's back.", "fix": "start_keeper", "fix_label": "Start it"}, {"level": "warn", "title": "Auto-rotation is off", "detail": "Zen Guard isn't running, so when you hit the free limit you'll have to rotate manually.", "fix": "start_guard", "fix_label": "Turn on"}]}, "busy": {"status": "busy", "title": "Rotating to a fresh IP…", "sub": "This takes about 10–15 seconds. OpenCode will continue automatically.", "issues": []}, }[kind] ok = kind in ("ok", "busy") long_line = ("11-15 12:04:31 hop: WARP registration deleted, new device key registered, reconnecting TUN; " "egress 2a09:bac5:499:a82::1f:3c -> 2a09:bac5:31f:12c::4a:9 (edge 2606:4700:30::ac43:a082, took 11.8s)") return { "health": health, "recent_errors": [ {"code": "rate_limited", "title": "Free usage limit reached", "detail": "OpenCode's free limit was hit for this IP. Zen Guard rotates to a fresh IP automatically; press Fix to rotate right now.", "fix": "hop", "ts": now - 420, "count": 3, "where": "chat"}, {"code": "conn_dropped", "title": "Connection dropped mid-reply", "detail": "The connection closed while the model was answering (often during an IP rotation). Just send 'continue' to resume.", "fix": None, "ts": now - 3900, "count": 1, "where": "chat"}, {"code": "proxy_down", "title": "OpenCode couldn't reach the local proxy", "detail": "Nothing was listening on 127.0.0.1:41987, usually because the background service was stopped or restarting.", "fix": "start_keeper", "ts": now - 86400 * 2, "count": 12, "where": "background"}], "warp": {"mode": "WarpProxy", "rotating": kind == "busy", "connected": kind != "bad", "is_cf": True, "adapter_v6": "", "egress_v6": "2a09:bac5:499:a82::1f:3c", "egress_prefix": "2a09:bac5:499:a82", "checking_egress": False}, "services": {"is_admin": False, "keeper_running": True, "guard_running": ok, "proxy_listening": ok, "firewall_installed": False, "keeper_task": True, "guard_task": True, "auto_resume": True}, "lane": {"pinned_edge": "2606:4700:30::ac43:a082", "edge_override": "auto", "edge_pool": ["2606:4700:30::ac43:a082", "2606:4700:30::6812:2c5b"], "desktop_service_wired": True, "strict_mode": False, "path_wired": True}, "stats": {"hops": 2, "db": {"projects": 5, "sessions": 46}, "blacklist_count": 3, "last_hop": now - 3600, "blacklist": ["2a09:bac5:499:a82", "2a09:bac1:76a0:5b8", "2a09:bac5:31f:12c"]}, "logs": {"guard": ["11-15 12:00:58 guard up (poll 10s, cooldown 75s, warp=found)", "11-15 12:03:12 wall detected in opencode.log (FreeUsageLimitError) -> rotating", long_line, "11-15 12:04:43 auto-resume: sent 'continue' to session ses_8f2a1c"], "keeper": ["11-15 12:00:58 keeper up (tick=45s, warp=found)", "11-15 12:00:59 proxy listening on 127.0.0.1:41987 (exclusive)"], "opencode": []}, "egress": {"mode": mode, "warp_scope": "isolated", "tor_active": mode == "tor", "tor_running": mode == "tor", "tor_target": "127.0.0.1:9050" if mode == "tor" else "Not running", "custom_proxy": "127.0.0.1:10808, 10.0.0.5:1080", "custom_type": "socks5", "custom_pool_count": 2, "custom_current_node": "127.0.0.1:10808 (#1/2)", "clean_endpoints": ["162.159.192.1:2408", "162.159.193.5:2408", "188.114.97.3:500"]}, } ERROR_OVERLAY = """""" # "Report a problem" dialog: mocked backend (report_preview / report_pick_files / send_report ...). REPORT_SAMPLE = """openhop diagnostic report Created: 2026-11-16 08:56:10 +0100 App: openhop 3.3.2 (exe) · Python 3.14.0 OS: Windows 11 Home build 26200 Personal data removed on the user's PC: home path, user name, tokens, last part of every IP. ===== Live route check (cloudflare.com/cdn-cgi/trace) ===== real_ip_leak: False proxy_same_as_direct: False routes: direct: warp: off colo: MAD ip: 203.0.113.x warp_socks_40000: warp: on colo: MAD ip: 2a09:bac5:499:a82::x local_proxy_41987: warp: on colo: MAD ip: 2a09:bac5:499:a82::x ===== Cloudflare WARP ===== Status update: Connected (user set) Mode: WarpProxy on port 40000 (consumer overrides) WARP tunnel protocol: MASQUE ===== Auto-rotate state (guard/state.json) ===== hops: 12 failed_hops: 0 blacklist_count: 9 last_hop_age: 17min ago ===== guard.log (last 200 lines) ===== 11-16 08:38:31 wall detected — rotating WARP /64 (was: 2a09:bac5:310b:3632::x) 11-16 08:38:35 rotated #12: 2a09:bac5:310b:3632::x -> 2a09:bac5:310a:3632::x ✓ """ def report_mock_script(modal: str) -> str: files = [{"name": "screenshot-limit.png", "size": 412_331}, {"name": "opencode-extra.log", "size": 88_204}] send = ({"ok": False, "code": "rate_limited", "message": "Too many reports from here right now. Please try again in a little while."} if modal == "report-error" else {"ok": True, "code": "sent"}) api = ( "" % (json.dumps(REPORT_SAMPLE), len(REPORT_SAMPLE.encode("utf-8")), json.dumps(files), json.dumps(send)) ) if not modal: return api steps = ["window.__openReport && window.__openReport();"] if modal in ("report-files", "report-sent", "report-error"): steps.append("document.getElementById('reportDesc').value='The chat keeps stopping with the limit message, " "even right after a new IP.';document.getElementById('reportContact').value='mydiscordname';" "document.getElementById('reportAttach').click();") if modal == "report-files": steps.append("document.getElementById('reportPreview').open=true;") if modal in ("report-sent", "report-error"): steps.append("setTimeout(function(){document.getElementById('reportSend').click();},150);") return api + "" % "".join(steps) def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--state", choices=("ok", "warn", "bad", "busy"), default="ok") ap.add_argument("--mode", choices=("warp", "tor", "custom", "clean"), default="warp", help="connection type") ap.add_argument("--view", choices=("simple", "advanced"), default=None, help="default: advanced when --tab is given (logs are Advanced-only), otherwise simple") ap.add_argument("--tab", default=None, help="log tab to open: guard | keeper | opencode | blacklist") ap.add_argument("--page", choices=("index", "notify", "tray"), default="index") ap.add_argument("--notice", choices=("problem", "hop", "update", "info"), default="problem", help="notify page: which variant to show") ap.add_argument("--size", default="1180x790") ap.add_argument("--eval", default="", help="JavaScript to run ~1 s after the page loaded (e.g. open a dialog)") ap.add_argument("--update", action="store_true", help="mock a downloaded update waiting (shows the update bar)") ap.add_argument("--post", action="store_true", help="mock 'just updated + checks passed' (shows the other bar)") ap.add_argument("--html", default="", help="index.html to render (default: src/ui/index.html). " "The website build passes the committed copy here.") ap.add_argument("--version", default="", help="version shown in the title bar (default: VERSION in ouc_common.py)") ap.add_argument("--scale", type=float, default=1.0, help="device pixel ratio, e.g. 2 for a sharp image") ap.add_argument("--modal", choices=("report", "report-files", "report-sent", "report-error"), default="", help="open the Report-a-problem dialog (empty, with files + preview, sent, or rate-limited)") ap.add_argument("--out", default=str(pathlib.Path(tempfile.gettempdir()) / "openhop_preview.png")) args = ap.parse_args() edge = next((e for e in EDGE_CANDIDATES if pathlib.Path(e).is_file()), None) if not edge: raise SystemExit("Microsoft Edge not found (needed for headless screenshots).") if args.page == "notify": return shoot_notify(edge, args) if args.page == "tray": return shoot_tray(edge, args) view = args.view or ("advanced" if args.tab else "simple") html = (pathlib.Path(args.html) if args.html else ROOT / "src" / "ui" / "index.html").read_text(encoding="utf-8") state = mock_state(args.state, args.mode) state["version"] = args.version or _own_version() settings = { "close_to_tray": True, "start_with_windows": True, "notify_problems": True, "notify_hops": True, "notify_updates": False, "desktop_brand": True, "hide_limit_banner": True, "auto_update": True, "tray_available": True, } post = None if args.post: post = {"at": int(time.time()), "from": "3.3.1", "to": "3.3.2", "version": "3.3.2", "ok": True, "passed": 8, "total": 8, "checks": []} update = {"ready": bool(args.update), "can_install": True, "available": bool(args.update or args.post), "latest": "3.3.2" if args.post else "3.1.2", "current": "3.3.2" if args.post else "3.1.1", "error": "", "post": post} # Realistic token totals for the TOKEN USAGE card (roughly this PC's real opencode.db numbers). tokens = {"ok": True, "total": 530_997_813, "input": 12_343_391, "output": 2_053_878, "cache_read": 516_600_544, "cache_write": 0, "reasoning": 2_542_823, "cost": 0.0, "sessions": 30, "projects": 9, "updated": int(time.time()) - 120} mock = ( ERROR_OVERLAY + "" % (json.dumps(view), json.dumps(state), json.dumps(settings), json.dumps(update), json.dumps(tokens)) ) html = html.replace("", mock + "", 1) html = html.replace("", report_mock_script(args.modal) + "", 1) if args.tab: html = re.sub(r'let activeTab = "[a-z]+";', f'let activeTab = "{args.tab}";', html, count=1) if args.eval: html = html.replace("", "" % args.eval, 1) shoot(edge, html, args.size, args.out, args.scale) return 0 def _own_version() -> str: m = re.search(r'^VERSION = "([^"]+)"', (ROOT / "src" / "ouc_common.py").read_text(encoding="utf-8"), re.M) return m.group(1) if m else "" def shoot_notify(edge: str, args) -> int: """Notification popup on a desktop-like backdrop (the real page background is transparent).""" html = (ROOT / "src" / "ui" / "notify.html").read_text(encoding="utf-8") backdrop = "" html = html.replace("", ERROR_OVERLAY + backdrop + "", 1) html = html.replace("", "" % json.dumps(args.notice), 1) shoot(edge, html, args.size if args.size != "1180x790" else "640x200", args.out) return 0 def shoot_tray(edge: str, args) -> int: """Tray menu (280x312) on a desktop-like backdrop, with a mocked renderMenu() call.""" st = mock_state(args.state, args.mode) h = st["health"] menu = {"status": h["status"], "title": h["title"], "sub": h["sub"], "hops": st["stats"]["hops"], "last_hop": st["stats"]["last_hop"]} html = (ROOT / "src" / "ui" / "traymenu.html").read_text(encoding="utf-8") backdrop = ("") html = html.replace("", ERROR_OVERLAY + backdrop + "", 1) html = html.replace("", "" % json.dumps(menu), 1) shoot(edge, html, args.size if args.size != "1180x790" else "560x380", args.out) return 0 def shoot(edge: str, html: str, size: str, out: str, scale: float = 1.0) -> None: work = pathlib.Path(tempfile.mkdtemp(prefix="openhop_preview_")) page = work / "preview.html" page.write_text(html, encoding="utf-8") w, h = size.split("x") subprocess.run( [edge, "--headless=new", "--disable-gpu", "--hide-scrollbars", f"--user-data-dir={work / 'profile'}", f"--window-size={w},{h}", f"--force-device-scale-factor={scale:g}", "--virtual-time-budget=3000", f"--screenshot={out}", page.as_uri()], capture_output=True, timeout=90, ) print(out) if __name__ == "__main__": raise SystemExit(main())