hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
hop / Linux / tests / combined_check.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Independent measurements of the built Linux app, using a private desktop. |
| 3 | |
| 4 | Python, Xvfb and xdotool are verification instruments, never installed components. |
| 5 | """ |
| 6 | import argparse |
| 7 | import hashlib |
| 8 | import http.server |
| 9 | import json |
| 10 | import os |
| 11 | from pathlib import Path |
| 12 | import secrets |
| 13 | import shutil |
| 14 | import socket |
| 15 | import struct |
| 16 | import subprocess |
| 17 | import threading |
| 18 | import time |
| 19 | |
| 20 | |
| 21 | def run(args, env, **kwargs): |
| 22 | return subprocess.run(args, env=env, capture_output=True, timeout=20, **kwargs) |
| 23 | |
| 24 | |
| 25 | def wait_for(predicate, explanation, timeout=8): |
| 26 | deadline = time.monotonic() + timeout |
| 27 | while time.monotonic() < deadline: |
| 28 | result = predicate() |
| 29 | if result: |
| 30 | return result |
| 31 | time.sleep(.025) |
| 32 | raise AssertionError(explanation) |
| 33 | |
| 34 | |
| 35 | def check(binary, evidence): |
| 36 | binary = binary.resolve() |
| 37 | root = Path(__file__).resolve().parents[2] |
| 38 | evidence.mkdir(parents=True, exist_ok=False) |
| 39 | checks = [] |
| 40 | home = evidence / 'home' |
| 41 | apps = home / 'data' / 'applications' |
| 42 | apps.mkdir(parents=True) |
| 43 | marker = evidence / 'launched' |
| 44 | (apps / 'hop-probe.desktop').write_text( |
| 45 | '[Desktop Entry]\nType=Application\nName=Hop Test Editor\n' |
| 46 | f'Exec=/usr/bin/touch "{marker}"\n') |
| 47 | env = {k: v for k, v in os.environ.items() |
| 48 | if not k.startswith('HOP_') and k not in ('DISPLAY', 'XAUTHORITY')} |
| 49 | config = home / 'config' |
| 50 | config.mkdir() |
| 51 | opened_file = evidence / 'file-opened' |
| 52 | (apps / 'hop-test-viewer.desktop').write_text( |
| 53 | '[Desktop Entry]\nType=Application\nName=Hop Test Viewer\nNoDisplay=true\n' |
| 54 | 'MimeType=text/plain;\n' + f'Exec=/usr/bin/touch "{opened_file}"\n') |
| 55 | (apps / 'mimeinfo.cache').write_text('[MIME Cache]\ntext/plain=hop-test-viewer.desktop;\n') |
| 56 | (config / 'mimeapps.list').write_text('[Default Applications]\ntext/plain=hop-test-viewer.desktop;\n') |
| 57 | files = home / 'Documents' |
| 58 | files.mkdir() |
| 59 | report_file = files / 'Report July.txt' |
| 60 | report_file.write_text('A private file-search fixture.\n') |
| 61 | env.update(HOME=str(home), XDG_DATA_HOME=str(home / 'data'), |
| 62 | XDG_CACHE_HOME=str(home / 'cache'), XDG_CONFIG_HOME=str(config), |
| 63 | XDG_DATA_DIRS=str(home / 'empty'), XDG_CURRENT_DESKTOP='GNOME', |
| 64 | GIO_USE_VFS='local', DBUS_SESSION_BUS_ADDRESS='unix:path=' + str(home / 'no-session-bus')) |
| 65 | got = run([str(binary), '--selftest'], env) |
| 66 | assert got.returncode == 0, got.stderr |
| 67 | checks.append('built program talks to its actual shared matching helper') |
| 68 | got = run([str(binary), '--search', 'Hop Test Editor'], env) |
| 69 | assert got.returncode == 0 and got.stdout == b'Hop Test Editor\n', (got.stdout, got.stderr) |
| 70 | checks.append('headless search reads the same application fixture as the desktop') |
| 71 | got = run([str(binary), '--reindex', str(files)], env) |
| 72 | assert got.returncode == 0, (got.stdout, got.stderr) |
| 73 | got = run([str(binary), '--find', 'report'], env) |
| 74 | assert got.returncode == 0 and json.loads(got.stdout) == [str(report_file)], (got.stdout, got.stderr) |
| 75 | checks.append('built command indexes fixture files and returns the exact path through Find JSON') |
| 76 | broken = evidence / 'missing-helper' |
| 77 | broken.mkdir() |
| 78 | shutil.copy2(binary, broken / 'hop') |
| 79 | got = run([str(broken / 'hop'), '--selftest'], env) |
| 80 | assert got.returncode != 0 and b'helper' in got.stderr, (got.stdout, got.stderr) |
| 81 | checks.append('missing matching helper refuses visibly') |
| 82 | |
| 83 | mutated = evidence / 'changed-helper' |
| 84 | mutated.mkdir() |
| 85 | shutil.copy2(binary, mutated / 'hop') |
| 86 | source = (root / 'Omega/hopcore.om').read_bytes() |
| 87 | old = b'ret sub 160 minu 30 sub nl ql' |
| 88 | assert source.count(old) == 1 |
| 89 | changed = source.replace(old, b'ret sub 161 minu 30 sub nl ql') |
| 90 | ng = binary.parent / 'ng' |
| 91 | ir = subprocess.run([str(ng)], input=b'@ng front-ir\n' + changed, |
| 92 | capture_output=True, check=True).stdout |
| 93 | opt = subprocess.run([str(ng)], input=b'@ng opt\n' + ir, |
| 94 | capture_output=True, check=True).stdout |
| 95 | core = subprocess.run([str(ng)], input=b'@ng a64\n' + opt, |
| 96 | capture_output=True, check=True).stdout |
| 97 | (mutated / 'hopcore').write_bytes(core) |
| 98 | (mutated / 'hopcore').chmod(0o755) |
| 99 | got = run([str(mutated / 'hop'), '--selftest'], env) |
| 100 | assert got.returncode != 0 and b'FAIL' in got.stderr, (got.stdout, got.stderr) |
| 101 | checks.append('changed real shared-core scoring rule fails the application self-test') |
| 102 | |
| 103 | class Model(http.server.BaseHTTPRequestHandler): |
| 104 | requests = [] |
| 105 | |
| 106 | def do_POST(self): |
| 107 | body = json.loads(self.rfile.read(int(self.headers['Content-Length']))) |
| 108 | self.requests.append((self.path, body)) |
| 109 | answer = json.dumps({'choices': [{'message': {'content': 'Local test answer.'}}]}).encode() |
| 110 | self.send_response(200) |
| 111 | self.send_header('Content-Type', 'application/json') |
| 112 | self.send_header('Content-Length', str(len(answer))) |
| 113 | self.end_headers() |
| 114 | self.wfile.write(answer) |
| 115 | |
| 116 | def log_message(self, *args): |
| 117 | pass |
| 118 | |
| 119 | httpd = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Model) |
| 120 | threading.Thread(target=httpd.serve_forever, daemon=True).start() |
| 121 | env.update(HOP_MODEL_URL=f'http://127.0.0.1:{httpd.server_port}/v1', HOP_MODEL='fixture-model') |
| 122 | display = next(n for n in range(210, 510) if not Path(f'/tmp/.X11-unix/X{n}').exists()) |
| 123 | auth = evidence / 'Xauthority' |
| 124 | fields = [socket.gethostname().encode(), str(display).encode(), |
| 125 | b'MIT-MAGIC-COOKIE-1', secrets.token_bytes(16)] |
| 126 | auth.write_bytes(struct.pack('>H', 256) + b''.join(struct.pack('>H', len(v)) + v for v in fields)) |
| 127 | auth.chmod(0o600) |
| 128 | env.update(DISPLAY=f':{display}.0', XAUTHORITY=str(auth)) |
| 129 | server_log = open(evidence / 'xvfb.log', 'wb') |
| 130 | xserver = subprocess.Popen(['Xvfb', f':{display}', '-screen', '0', '1024x768x24', |
| 131 | '-nolisten', 'tcp', '-auth', str(auth)], |
| 132 | stdout=server_log, stderr=server_log) |
| 133 | app = None |
| 134 | try: |
| 135 | wait_for(lambda: Path(f'/tmp/.X11-unix/X{display}').exists(), 'private display did not start') |
| 136 | |
| 137 | def start_app(): |
| 138 | proc = subprocess.Popen([str(binary)], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 139 | def find_window(): |
| 140 | if proc.poll() is not None: |
| 141 | raise AssertionError(proc.communicate()) |
| 142 | q = run(['xdotool', 'search', '--name', '^Hop$'], env) |
| 143 | return q.stdout.splitlines()[-1].decode() if q.stdout.strip() else None |
| 144 | win = wait_for(find_window, 'combined Hop window did not appear') |
| 145 | run(['xdotool', 'windowfocus', '--sync', win], env, check=True) |
| 146 | return proc, win |
| 147 | |
| 148 | app, win = start_app() |
| 149 | run(['xdotool', 'type', '--clearmodifiers', '--delay', '8', 'Hop Test Editor'], env, check=True) |
| 150 | run(['xdotool', 'key', 'Return'], env, check=True) |
| 151 | wait_for(marker.exists, 'Enter did not launch the selected real desktop entry') |
| 152 | out, err = app.communicate(timeout=5) |
| 153 | assert app.returncode == 0 and not err, (out, err) |
| 154 | app = None |
| 155 | checks.append('combined desktop: typing finds an app and Enter launches the selected desktop entry') |
| 156 | |
| 157 | app, win = start_app() |
| 158 | run(['xdotool', 'type', '--clearmodifiers', '--delay', '8', 'find report'], env, check=True) |
| 159 | run(['xdotool', 'key', 'Return'], env, check=True) |
| 160 | wait_for(opened_file.exists, 'Find did not open the selected file through its configured test handler') |
| 161 | out, err = app.communicate(timeout=5) |
| 162 | assert app.returncode == 0 and not err, (out, err) |
| 163 | app = None |
| 164 | checks.append('combined desktop: Find opens the selected raw path through the configured file handler') |
| 165 | |
| 166 | app, win = start_app() |
| 167 | run(['xdotool', 'type', '--clearmodifiers', '--delay', '8', 'ask Does Linux work?'], env, check=True) |
| 168 | run(['xdotool', 'key', 'Return'], env, check=True) |
| 169 | wait_for(lambda: Model.requests, 'Ask did not reach the private model stand-in') |
| 170 | path, body = Model.requests[0] |
| 171 | assert path == '/v1/chat/completions' |
| 172 | assert body['model'] == 'fixture-model' |
| 173 | assert body['messages'] == [{'role': 'user', 'content': 'Does Linux work?'}] |
| 174 | time.sleep(.2) |
| 175 | assert app.poll() is None, 'window unexpectedly quit after the answer' |
| 176 | xwd = run(['xwd', '-silent', '-id', win], env, check=True).stdout |
| 177 | (evidence / 'ask-window.xwd').write_bytes(xwd) |
| 178 | from PIL import Image |
| 179 | header = struct.unpack('>25I', xwd[:100]) |
| 180 | Image.frombytes('RGB', (header[4], header[5]), |
| 181 | xwd[header[0] + header[19] * 12:], 'raw', 'BGRX', header[12]).save(evidence / 'ask-window.png') |
| 182 | run(['xdotool', 'key', 'Escape'], env, check=True) |
| 183 | out, err = app.communicate(timeout=5) |
| 184 | assert app.returncode == 0 and not err, (out, err) |
| 185 | app = None |
| 186 | checks.append('combined desktop: Ask sends the typed question, remains open with the answer, and Escape exits') |
| 187 | finally: |
| 188 | if app is not None and app.poll() is None: |
| 189 | app.terminate() |
| 190 | app.communicate(timeout=5) |
| 191 | xserver.terminate() |
| 192 | xserver.wait(timeout=5) |
| 193 | server_log.close() |
| 194 | httpd.shutdown() |
| 195 | httpd.server_close() |
| 196 | result = {'status': 'PASS', 'checks': checks, |
| 197 | 'binary_sha256': hashlib.sha256(binary.read_bytes()).hexdigest(), |
| 198 | 'core_sha256': hashlib.sha256((binary.parent / 'hopcore').read_bytes()).hexdigest(), |
| 199 | 'not_run': ['physical desktop session', 'XWayland', 'native Wayland', 'live AI provider']} |
| 200 | (evidence / 'result.json').write_text(json.dumps(result, indent=2) + '\n') |
| 201 | print(json.dumps(result, indent=2)) |
| 202 | |
| 203 | |
| 204 | if __name__ == '__main__': |
| 205 | p = argparse.ArgumentParser(description=__doc__) |
| 206 | p.add_argument('--binary', type=Path, required=True) |
| 207 | p.add_argument('--evidence', type=Path, required=True) |
| 208 | options = p.parse_args() |
| 209 | check(options.binary, options.evidence.resolve()) |