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 / chat_check.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Independent fake-server and JSON oracle for Linux/chat.om. No model calls.""" |
| 3 | import argparse |
| 4 | import http.server |
| 5 | import json |
| 6 | import os |
| 7 | from pathlib import Path |
| 8 | import subprocess |
| 9 | import tempfile |
| 10 | import threading |
| 11 | |
| 12 | ROOT = Path(__file__).resolve().parents[2] |
| 13 | PRE = """om2 |
| 14 | global lx_query uchar * |
| 15 | global lx_rows uchar * |
| 16 | global lx_qn ulong 1 |
| 17 | global lx_rn ulong 1 |
| 18 | global lx_pick ulong 1 |
| 19 | """ |
| 20 | POST = """ |
| 21 | text ht_parse "parse" |
| 22 | text ht_bad "BAD" |
| 23 | fn main to int |
| 24 | n = argread 1 hc_io 0 len hc_io |
| 25 | if eq n 5 |
| 26 | if eq get hc_io 0 112 |
| 27 | while true bound 9223372036854775807 |
| 28 | r = read 0 hc_io 0 len hc_io |
| 29 | if le r 0 |
| 30 | break |
| 31 | end |
| 32 | for i ulong ulong r bound 8192 |
| 33 | hc_add 1 get hc_io i |
| 34 | end |
| 35 | end |
| 36 | ok = hc_value 1 |
| 37 | hc_space |
| 38 | if and ok and eq get hc_found 0 1 eq get hc_pos 0 get hc_n 1 |
| 39 | r = write 1 hc_ans 0 get hc_n 7 |
| 40 | ret 0 |
| 41 | end |
| 42 | r = write 1 ht_bad 0 len ht_bad |
| 43 | ret 1 |
| 44 | end |
| 45 | end |
| 46 | r = enlarge lx_query ulong n |
| 47 | for i ulong ulong n bound 8192 |
| 48 | put lx_query i get hc_io i |
| 49 | end |
| 50 | put lx_qn 0 ulong n |
| 51 | if eq hc_query 0 |
| 52 | ret 2 |
| 53 | end |
| 54 | if gt argcnt 2 |
| 55 | r = write 1 lx_rows 0 get lx_rn 0 |
| 56 | ret 0 |
| 57 | end |
| 58 | k = hc_activate |
| 59 | r = write 1 lx_rows 0 get lx_rn 0 |
| 60 | ret 0 |
| 61 | end |
| 62 | """ |
| 63 | |
| 64 | |
| 65 | def check(omc): |
| 66 | passed = 0 |
| 67 | |
| 68 | def verify(condition, name): |
| 69 | nonlocal passed |
| 70 | if not condition: |
| 71 | raise AssertionError(name) |
| 72 | passed += 1 |
| 73 | |
| 74 | with tempfile.TemporaryDirectory(prefix="hop-chat-") as td: |
| 75 | binary = Path(td) / "chat" |
| 76 | source = PRE + (ROOT / "Linux/chat.om").read_text() + POST |
| 77 | result = subprocess.run([omc], input=source.encode(), capture_output=True) |
| 78 | if result.returncode: |
| 79 | raise RuntimeError(result.stderr.decode()) |
| 80 | binary.write_bytes(result.stdout) |
| 81 | binary.chmod(0o700) |
| 82 | env = {k: v for k, v in os.environ.items() if not k.startswith("HOP_")} |
| 83 | |
| 84 | def run(query="ask hello", settings=None, **kwargs): |
| 85 | return subprocess.run([str(binary), query], env=env | (settings or {}), |
| 86 | capture_output=True, timeout=15, **kwargs) |
| 87 | |
| 88 | missing = run() |
| 89 | verify(missing.returncode == 0 and b"Set HOP_MODEL_URL" in missing.stdout, |
| 90 | "missing configuration is explained") |
| 91 | verify(run("hello").returncode == 2, "plain searches do not become network requests") |
| 92 | action = subprocess.run([str(binary), "ask hello", "action"], capture_output=True) |
| 93 | verify(action.stdout == b"Ask: hello", "query is offered as an explicit Ask action") |
| 94 | settings = {"HOP_MODEL_URL": "file:///etc/passwd", "HOP_MODEL": "test"} |
| 95 | verify(b"use an http://" in run(settings=settings).stdout, "non-HTTP URL refused") |
| 96 | settings["HOP_MODEL_URL"] = "https://example.invalid/v1?foo=bar" |
| 97 | verify(b"use an http://" in run(settings=settings).stdout, "query-bearing base URL refused") |
| 98 | settings["HOP_MODEL_URL"] = "http://127.0.0.1:1/v1" |
| 99 | settings["HOP_API_KEY"] = "secret\r\nInjected: header" |
| 100 | bad = run(settings=settings) |
| 101 | verify(b"control character" in bad.stdout and b"secret" not in bad.stdout, |
| 102 | "header injection refused without echoing key") |
| 103 | |
| 104 | answers = ["plain", "line\nnext\tend", 'quote " slash \\ /', "Ξ© π δΈζ", "", |
| 105 | "backspace\bformfeed\freturn\r", "x" * 50000] |
| 106 | for answer in answers: |
| 107 | body = json.dumps({"ignored": [True, None, -1.25e3, {"content": "wrong"}], |
| 108 | "choices": [{"message": {"content": answer}}]}).encode() |
| 109 | r = run("parse", input=body) |
| 110 | verify(r.returncode == 0 and r.stdout == answer.encode(), |
| 111 | "independent JSON decoding " + repr(answer[:20])) |
| 112 | valid = b'{"choices":[{"message":{"content":"yes"}}]}' |
| 113 | bad_json = [valid + b"garbage", valid[:-1], b"[]", b"{}", |
| 114 | b'{"choices":[{"message":{"content":null}}]}', |
| 115 | b'{"choices":[{}, {"message":{"content":"wrong choice"}}]}', |
| 116 | b'{"choices":[{"message":{"content":"\\ud800"}}]}', |
| 117 | b'{"choices":[{"message":{"content":"\\udc00"}}]}', |
| 118 | b'{"choices":[{"message":{"content":"\\ud800\\u0041"}}]}', |
| 119 | b'{"choices":[{"message":{"content":"\\x42"}}]}', |
| 120 | b'{"choices":[{"message":{"content":"a","content":"b"}}]}', |
| 121 | valid.replace(b'"yes"', b'"bad\nstring"'), |
| 122 | b'{"ignore":01,"choices":[{"message":{"content":"yes"}}]}', |
| 123 | b'{"ignore":1.,"choices":[{"message":{"content":"yes"}}]}'] |
| 124 | for idx, body in enumerate(bad_json): |
| 125 | r = run("parse", input=body) |
| 126 | verify(r.returncode == 1 and r.stdout == b"BAD", f"malformed/mismatched JSON {idx}") |
| 127 | |
| 128 | observed = [] |
| 129 | response = {"status": 200, "body": valid} |
| 130 | |
| 131 | class Handler(http.server.BaseHTTPRequestHandler): |
| 132 | def log_message(self, *_): |
| 133 | pass |
| 134 | |
| 135 | def do_POST(self): |
| 136 | body = self.rfile.read(int(self.headers["Content-Length"])) |
| 137 | observed.append((self.path, dict(self.headers), body)) |
| 138 | out = response["body"] |
| 139 | self.send_response(response["status"]) |
| 140 | if response["status"] == 302: |
| 141 | self.send_header("Location", "/must-not-be-followed") |
| 142 | self.send_header("Content-Length", str(len(out))) |
| 143 | self.end_headers() |
| 144 | self.wfile.write(out) |
| 145 | |
| 146 | server = http.server.HTTPServer(("127.0.0.1", 0), Handler) |
| 147 | thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 148 | thread.start() |
| 149 | try: |
| 150 | query = 'What?\n"quote" \\slash Ξ© $(touch NEVER_RUN) `touch NEVER_RUN`' |
| 151 | key = 'test"key\\other' |
| 152 | model = 'model"quote\\slash' |
| 153 | settings = {"HOP_MODEL_URL": f"http://127.0.0.1:{server.server_port}/v1/", |
| 154 | "HOP_MODEL": model, "HOP_API_KEY": key} |
| 155 | result = run("ask " + query, settings) |
| 156 | verify(result.returncode == 0 and result.stdout == b"yes" and result.stderr == b"", |
| 157 | "configured fake-server response reaches Hop") |
| 158 | path, headers, body = observed[-1] |
| 159 | verify(path == "/v1/chat/completions", "base URL and slash normalized") |
| 160 | verify(headers["Authorization"] == "Bearer " + key, "API key transmitted literally") |
| 161 | verify(json.loads(body) == {"model": model, |
| 162 | "messages": [{"role": "user", "content": query}], |
| 163 | "stream": False}, "prompt/model escape to exact independent JSON") |
| 164 | verify(not (Path.cwd() / "NEVER_RUN").exists(), "prompt is not evaluated by a shell") |
| 165 | settings.pop("HOP_API_KEY") |
| 166 | response["body"] = json.dumps({"choices": [{"message": {"content": "Ξ© π"}}]}).encode() |
| 167 | verify(run(settings=settings).stdout == "Ξ© π".encode(), "Unicode reaches UI through transport") |
| 168 | verify("Authorization" not in observed[-1][1], "absent key sends no authorization") |
| 169 | response["body"] = b'{"error":{"message":"private server details"}}' |
| 170 | response["status"] = 401 |
| 171 | result = run(settings=settings) |
| 172 | verify(b"HTTP 401" in result.stdout and b"private" not in result.stdout, |
| 173 | "HTTP authentication failure is explicit and does not expose server details") |
| 174 | response["status"] = 200 |
| 175 | verify(b"valid chat answer" in run(settings=settings).stdout, |
| 176 | "success status without an answer fails explicitly") |
| 177 | response["body"] = valid |
| 178 | response["status"] = 302 |
| 179 | before = len(observed) |
| 180 | verify(b"HTTP 302" in run(settings=settings).stdout, |
| 181 | "redirect response is an explicit failure") |
| 182 | verify(len(observed) == before + 1, "transport never follows redirects") |
| 183 | finally: |
| 184 | server.shutdown() |
| 185 | server.server_close() |
| 186 | thread.join() |
| 187 | print(f"PASS Linux Ask checks={passed}; local fake server only") |
| 188 | |
| 189 | |
| 190 | if __name__ == "__main__": |
| 191 | parser = argparse.ArgumentParser() |
| 192 | parser.add_argument("omc") |
| 193 | check(parser.parse_args().omc) |