interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Linux / tests / chat_check.py

193 lines · 8217 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent fake-server and JSON oracle for Linux/chat.om. No model calls."""
3import argparse
4import http.server
5import json
6import os
7from pathlib import Path
8import subprocess
9import tempfile
10import threading
11
12ROOT = Path(__file__).resolve().parents[2]
13PRE = """om2
14global lx_query uchar *
15global lx_rows uchar *
16global lx_qn ulong 1
17global lx_rn ulong 1
18global lx_pick ulong 1
19"""
20POST = """
21text ht_parse "parse"
22text ht_bad "BAD"
23fn main to int
24n = argread 1 hc_io 0 len hc_io
25if eq n 5
26if eq get hc_io 0 112
27while true bound 9223372036854775807
28r = read 0 hc_io 0 len hc_io
29if le r 0
30break
31end
32for i ulong ulong r bound 8192
33hc_add 1 get hc_io i
34end
35end
36ok = hc_value 1
37hc_space
38if and ok and eq get hc_found 0 1 eq get hc_pos 0 get hc_n 1
39r = write 1 hc_ans 0 get hc_n 7
40ret 0
41end
42r = write 1 ht_bad 0 len ht_bad
43ret 1
44end
45end
46r = enlarge lx_query ulong n
47for i ulong ulong n bound 8192
48put lx_query i get hc_io i
49end
50put lx_qn 0 ulong n
51if eq hc_query 0
52ret 2
53end
54if gt argcnt 2
55r = write 1 lx_rows 0 get lx_rn 0
56ret 0
57end
58k = hc_activate
59r = write 1 lx_rows 0 get lx_rn 0
60ret 0
61end
62"""
63
64
65def 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
190if __name__ == "__main__":
191 parser = argparse.ArgumentParser()
192 parser.add_argument("omc")
193 check(parser.parse_args().omc)