aien-sovereign-core
Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark
Brought by drakestapleton
aien-sovereign-core / scripts / browser_mirror_test.py
| 1 | """Sovereign Browser Mirror Self-Testing Harness for AIEN.""" |
| 2 | |
| 3 | import asyncio |
| 4 | import base64 |
| 5 | import json |
| 6 | import os |
| 7 | import signal |
| 8 | import subprocess |
| 9 | import time |
| 10 | import urllib.request |
| 11 | import websockets |
| 12 | |
| 13 | TARGET_URL = "http://127.0.0.1:18095/" |
| 14 | CDP_HOST = "127.0.0.1" |
| 15 | CDP_PORT = 9222 |
| 16 | OUT_DIR = "/home/drakestapleton/basecamp/ui-tests" |
| 17 | |
| 18 | os.makedirs(OUT_DIR, exist_ok=True) |
| 19 | |
| 20 | class CDPClient: |
| 21 | def __init__(self, ws_url): |
| 22 | self.ws_url = ws_url |
| 23 | self.ws = None |
| 24 | self.req_id = 1 |
| 25 | |
| 26 | async def connect(self): |
| 27 | self.ws = await websockets.connect(self.ws_url, max_size=50 * 1024 * 1024) |
| 28 | |
| 29 | async def send(self, method, params=None): |
| 30 | mid = self.req_id |
| 31 | self.req_id += 1 |
| 32 | msg = {"id": mid, "method": method} |
| 33 | if params: |
| 34 | msg["params"] = params |
| 35 | await self.ws.send(json.dumps(msg)) |
| 36 | while True: |
| 37 | resp = json.loads(await self.ws.recv()) |
| 38 | if resp.get("id") == mid: |
| 39 | return resp.get("result", {}) |
| 40 | |
| 41 | async def eval_js(self, expr, await_promise=False): |
| 42 | res = await self.send("Runtime.evaluate", { |
| 43 | "expression": expr, |
| 44 | "returnByValue": True, |
| 45 | "awaitPromise": await_promise |
| 46 | }) |
| 47 | val = res.get("result", {}).get("value") |
| 48 | return val |
| 49 | |
| 50 | async def capture_screenshot(self, filename): |
| 51 | path = os.path.join(OUT_DIR, filename) |
| 52 | res = await self.send("Page.captureScreenshot", {"format": "png"}) |
| 53 | data = res.get("data") |
| 54 | if data: |
| 55 | with open(path, "wb") as f: |
| 56 | f.write(base64.b64decode(data)) |
| 57 | print(f"[mirror] Saved screenshot: {path}") |
| 58 | return path |
| 59 | return None |
| 60 | |
| 61 | async def close(self): |
| 62 | if self.ws: |
| 63 | await self.ws.close() |
| 64 | |
| 65 | |
| 66 | async def run_mirror_test(): |
| 67 | report = { |
| 68 | "timestamp": time.time(), |
| 69 | "target": TARGET_URL, |
| 70 | "assertions": [], |
| 71 | "screenshots": [], |
| 72 | "status": "in_progress" |
| 73 | } |
| 74 | |
| 75 | # 1. Launch Chrome Headless |
| 76 | chrome_cmd = [ |
| 77 | "google-chrome", |
| 78 | "--headless", |
| 79 | f"--remote-debugging-port={CDP_PORT}", |
| 80 | "--disable-gpu", |
| 81 | "--no-sandbox", |
| 82 | "--window-size=1280,900", |
| 83 | TARGET_URL |
| 84 | ] |
| 85 | print(f"[mirror] Spawning headless Chrome on port {CDP_PORT}") |
| 86 | proc = subprocess.Popen(chrome_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 87 | |
| 88 | try: |
| 89 | ws_url = None |
| 90 | for _ in range(30): |
| 91 | try: |
| 92 | with urllib.request.urlopen(f"http://{CDP_HOST}:{CDP_PORT}/json") as r: |
| 93 | pages = json.loads(r.read().decode()) |
| 94 | for p in pages: |
| 95 | if p.get("type") == "page" and "18095" in p.get("url", ""): |
| 96 | ws_url = p.get("webSocketDebuggerUrl") |
| 97 | break |
| 98 | if ws_url: |
| 99 | break |
| 100 | except Exception: |
| 101 | pass |
| 102 | await asyncio.sleep(0.2) |
| 103 | |
| 104 | if not ws_url: |
| 105 | raise RuntimeError("Failed to obtain Chrome CDP WebSocketDebuggerUrl") |
| 106 | |
| 107 | print(f"[mirror] Connected to CDP session: {ws_url}") |
| 108 | client = CDPClient(ws_url) |
| 109 | await client.connect() |
| 110 | |
| 111 | await client.send("Page.enable") |
| 112 | await client.send("Runtime.enable") |
| 113 | await client.send("DOM.enable") |
| 114 | |
| 115 | # Wait for hydration |
| 116 | await asyncio.sleep(2.0) |
| 117 | |
| 118 | # Assertion 1: Title and Header Telemetry |
| 119 | title = await client.eval_js("document.title") |
| 120 | bpm = await client.eval_js("document.getElementById('badge-heartbeat-text')?.textContent?.trim()") |
| 121 | coherence = await client.eval_js("document.getElementById('badge-coherence-text')?.textContent?.trim()") |
| 122 | print(f"[mirror] Page Title: '{title}', BPM: '{bpm}', Coherence: '{coherence}'") |
| 123 | |
| 124 | assert_title = "AIEN" in (title or "") |
| 125 | report["assertions"].append({ |
| 126 | "name": "initial_page_hydration", |
| 127 | "passed": assert_title, |
| 128 | "title": title, |
| 129 | "bpm": bpm, |
| 130 | "coherence": coherence |
| 131 | }) |
| 132 | |
| 133 | p1 = await client.capture_screenshot("cockpit_init.png") |
| 134 | if p1: |
| 135 | report["screenshots"].append(p1) |
| 136 | |
| 137 | # Assertion 2: Chat input and live streaming response |
| 138 | prompt = "Hello AIEN, please report current sovereign status." |
| 139 | print(f"[mirror] Submitting Chat message: '{prompt}'") |
| 140 | js_send = f""" |
| 141 | document.getElementById('chat-input').value = {json.dumps(prompt)}; |
| 142 | sendMessage(); |
| 143 | """ |
| 144 | await client.eval_js(js_send) |
| 145 | |
| 146 | # Poll for stream completion |
| 147 | response_text = "" |
| 148 | for i in range(50): |
| 149 | await asyncio.sleep(0.5) |
| 150 | is_streaming = await client.eval_js("window.isStreaming") |
| 151 | msgs = await client.eval_js(""" |
| 152 | Array.from(document.querySelectorAll('.chat-msg.assistant')).map(el => el.textContent.trim()) |
| 153 | """) |
| 154 | if msgs and len(msgs) > 1: |
| 155 | last_msg = msgs[-1] |
| 156 | if len(last_msg) > 30 and (is_streaming is False or i > 25): |
| 157 | response_text = last_msg |
| 158 | break |
| 159 | |
| 160 | print(f"[mirror] Assistant Response Length: {len(response_text)} chars") |
| 161 | has_response = len(response_text) > 20 |
| 162 | report["assertions"].append({ |
| 163 | "name": "chat_live_stream", |
| 164 | "passed": has_response, |
| 165 | "response_snippet": response_text[:180] |
| 166 | }) |
| 167 | |
| 168 | p2 = await client.capture_screenshot("cockpit_chat_stream.png") |
| 169 | if p2: |
| 170 | report["screenshots"].append(p2) |
| 171 | |
| 172 | # Assertion 3: Tactile Action Pill |
| 173 | print("[mirror] Clicking 'Run Doctor' tactile button") |
| 174 | await client.eval_js(""" |
| 175 | const pills = Array.from(document.querySelectorAll('.action-pill')); |
| 176 | const docPill = pills.find(p => p.textContent.includes('Doctor')); |
| 177 | if (docPill) docPill.click(); |
| 178 | """) |
| 179 | await asyncio.sleep(1.5) |
| 180 | |
| 181 | # Assertion 4: Tab Navigation |
| 182 | print("[mirror] Switching to Goals tab") |
| 183 | await client.eval_js(""" |
| 184 | const btn = document.querySelector('button[data-tab="goals"]'); |
| 185 | if (btn) btn.click(); |
| 186 | """) |
| 187 | await asyncio.sleep(1.0) |
| 188 | goals_content = await client.eval_js("document.getElementById('pane-goals')?.textContent?.trim()") |
| 189 | has_goals = len(goals_content or "") > 20 |
| 190 | |
| 191 | print("[mirror] Switching to Skills tab") |
| 192 | await client.eval_js(""" |
| 193 | const btn = document.querySelector('button[data-tab="skills"]'); |
| 194 | if (btn) btn.click(); |
| 195 | """) |
| 196 | await asyncio.sleep(1.0) |
| 197 | skills_content = await client.eval_js("document.getElementById('pane-skills')?.textContent?.trim()") |
| 198 | has_skills = len(skills_content or "") > 20 |
| 199 | |
| 200 | print(f"[mirror] Goals Tab Content: {has_goals}, Skills Tab Content: {has_skills}") |
| 201 | |
| 202 | report["assertions"].append({ |
| 203 | "name": "tab_navigation_and_actions", |
| 204 | "passed": has_goals and has_skills, |
| 205 | "has_goals": has_goals, |
| 206 | "has_skills": has_skills |
| 207 | }) |
| 208 | |
| 209 | p3 = await client.capture_screenshot("cockpit_actions.png") |
| 210 | if p3: |
| 211 | report["screenshots"].append(p3) |
| 212 | |
| 213 | all_passed = all(a.get("passed", False) for a in report["assertions"]) |
| 214 | report["status"] = "PASSED" if all_passed else "FAILED" |
| 215 | print(f"[mirror] Mirror Self-Test Result: {report['status']}") |
| 216 | |
| 217 | await client.close() |
| 218 | finally: |
| 219 | try: |
| 220 | proc.terminate() |
| 221 | proc.wait(timeout=3) |
| 222 | except Exception: |
| 223 | proc.kill() |
| 224 | |
| 225 | report_path = os.path.join(OUT_DIR, "report.json") |
| 226 | with open(report_path, "w") as f: |
| 227 | json.dump(report, f, indent=2) |
| 228 | print(f"[mirror] Test Report written to: {report_path}") |
| 229 | return report |
| 230 | |
| 231 | |
| 232 | if __name__ == "__main__": |
| 233 | rep = asyncio.run(run_mirror_test()) |
| 234 | print("\n" + json.dumps(rep, indent=2)) |