web_stack_test.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. #!/usr/bin/env python3
  2. """Self-contained web-stack feature tests: app + fake saddle daemon.
  3. Unlike integration_test.py (which needs a real saddle daemon and a mock
  4. LLM), this suite spawns everything it needs:
  5. - the clanker-saddle app binary (path from argv[1], or builddir default)
  6. in a scratch directory with its own web-config.json (statum keys copied
  7. from the repo, plus `saddle_callback_base_url`) and SQLite database
  8. - an in-process fake saddle daemon speaking the wire contract: POST
  9. /start (captures the payload), GET /status (scripted state machine),
  10. GET /output (empty), GET /log?since= (raw PTY chunks, one new chunk
  11. per request so since-paging is exercised)
  12. It then drives the app the way statum.js does (entrypoint loads + action
  13. POSTs) and asserts the Workstream B features against the wire contract:
  14. 3. plan-review blocks hide their duplicate body preview
  15. 5. rules CRUD/attach + the effective `rules` array in /start
  16. 6. project notes, POST /api/saddle/note, `project_notes` + `callback`
  17. in /start
  18. plus the raw-log side: session_raw_log polling + terminal raw view
  19. Prints PASS/FAIL lines Statum-style; exits non-zero on any failure.
  20. """
  21. import json
  22. import os
  23. import shutil
  24. import socket
  25. import sqlite3
  26. import subprocess
  27. import sys
  28. import threading
  29. import time
  30. import urllib.error
  31. import urllib.parse
  32. import urllib.request
  33. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  34. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  35. APP = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.join(REPO, "builddir", "clanker-saddle")
  36. WORK = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  37. DB_PATH = os.path.join(WORK, "web.sqlite")
  38. passes = 0
  39. failures = 0
  40. def check(condition, label):
  41. global passes, failures
  42. if condition:
  43. passes += 1
  44. print("PASS %s" % label)
  45. else:
  46. failures += 1
  47. print("FAIL %s" % label)
  48. def free_port():
  49. with socket.socket() as sock:
  50. sock.bind(("127.0.0.1", 0))
  51. return sock.getsockname()[1]
  52. APP_PORT = free_port()
  53. DAEMON_PORT = free_port()
  54. WEB = "http://127.0.0.1:%d" % APP_PORT
  55. def http(method, url, data=None, headers=None, timeout=30):
  56. body = None
  57. if data is not None:
  58. body = "&".join("%s=%s" % (k, urllib.parse.quote(str(v))) for k, v in data.items()).encode()
  59. request = urllib.request.Request(WEB + url if url.startswith("/") else url,
  60. data=body, method=method)
  61. if data is not None:
  62. request.add_header("Content-Type", "application/x-www-form-urlencoded")
  63. for key, value in (headers or {}).items():
  64. request.add_header(key, value)
  65. try:
  66. with urllib.request.urlopen(request, timeout=timeout) as response:
  67. return response.status, response.read().decode()
  68. except urllib.error.HTTPError as error:
  69. return error.code, error.read().decode()
  70. def directives(uri, auth=None):
  71. headers = {}
  72. if auth:
  73. headers["X-Statum-Slot"] = "key=%s; as_at=%s" % (auth["key"], auth["as_at"])
  74. status, body = http("GET", "/_statum/entrypoint?uri=" + urllib.parse.quote(uri.split("?")[0]),
  75. headers=headers)
  76. if status != 200:
  77. raise SystemExit("entrypoint %s -> HTTP %d: %s" % (uri, status, body[:300]))
  78. return json.loads(body)
  79. def slot_public(auth, uri, type_name):
  80. for directive in directives(uri, auth):
  81. if directive["type"] == "set":
  82. content = json.loads(directive["snapshot_frame"]["content"])
  83. if content["slot"]["type"] == type_name:
  84. return content["public"]
  85. raise SystemExit("no %s slot in entrypoint state for %s" % (type_name, uri))
  86. def act(auth, action, fields):
  87. headers = {"X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}
  88. if action.get("private"):
  89. headers["X-Statum-Private"] = action["private"]
  90. status, body = http(action.get("method", "POST"), action["uri"], fields, headers)
  91. if status != 200:
  92. raise SystemExit("action %s -> HTTP %d: %s" % (action["uri"], status, body[:300]))
  93. return json.loads(body)
  94. def login(username, password):
  95. frames = directives("/login")
  96. content = json.loads(frames[0]["snapshot_frame"]["content"])
  97. action = content["public"]["login"]
  98. status, body = http(action.get("method", "POST"), action["uri"],
  99. {"username": username, "password": password})
  100. if status != 200:
  101. raise SystemExit("login -> HTTP %d: %s" % (status, body[:300]))
  102. for directive in json.loads(body):
  103. if directive["type"] == "set":
  104. frame = json.loads(directive["snapshot_frame"]["content"])
  105. if frame["slot"]["type"] == "auth":
  106. return {"key": frame["slot"]["key"], "as_at": frame["as_at"]}
  107. raise SystemExit("login response carried no auth slot: " + body[:300])
  108. def wait_for(predicate, timeout=60, what="condition", interval=0.5):
  109. deadline = time.monotonic() + timeout
  110. last = None
  111. while time.monotonic() < deadline:
  112. last = predicate()
  113. if last is not False and last is not None:
  114. return last
  115. time.sleep(interval)
  116. print(" (timeout waiting for %s; last: %s)" % (what, last))
  117. return None
  118. def task_state(auth, task_id):
  119. return slot_public(auth, "/tasks/%d" % task_id, "task")
  120. def saddle_api(method, path, token, payload=None):
  121. """Raw call against the saddle ingest API; returns (status, json)."""
  122. request = urllib.request.Request(WEB + path,
  123. data=json.dumps(payload or {}).encode(), method=method)
  124. request.add_header("Content-Type", "application/json")
  125. if token is not None:
  126. request.add_header("Authorization", "Bearer " + token)
  127. try:
  128. with urllib.request.urlopen(request, timeout=15) as response:
  129. return response.status, json.loads(response.read().decode() or "{}")
  130. except urllib.error.HTTPError as error:
  131. body = error.read().decode()
  132. try:
  133. return error.code, json.loads(body)
  134. except ValueError:
  135. return error.code, {"raw": body}
  136. def db():
  137. return sqlite3.connect(DB_PATH)
  138. class FakeSaddle:
  139. """In-process saddle daemon implementing the wire contract."""
  140. PROMPT = "bbarrow@fedora:/workspace/task-1$ "
  141. def __init__(self):
  142. self.lock = threading.Lock()
  143. self.start_payloads = [] # captured POST /start bodies
  144. self.chunks = [] # [{seq, text}] — the raw log ring
  145. self.next_seq = 1
  146. self.state = "idle"
  147. self.summary = ""
  148. self.status_polls_after_start = 0
  149. def append_chunk(self, text):
  150. with self.lock:
  151. self.chunks.append({"seq": self.next_seq, "text": text})
  152. self.next_seq += 1
  153. def log_since(self, since):
  154. with self.lock:
  155. chunks = [c for c in self.chunks if c["seq"] > since]
  156. return chunks, self.next_seq
  157. class Handler(BaseHTTPRequestHandler):
  158. daemon = None # set on the class before serving
  159. def log_message(self, fmt, *args):
  160. pass
  161. def _send(self, status, obj):
  162. body = json.dumps(obj).encode()
  163. self.send_response(status)
  164. self.send_header("Content-Type", "application/json")
  165. self.send_header("Content-Length", str(len(body)))
  166. self.end_headers()
  167. self.wfile.write(body)
  168. def do_POST(self):
  169. length = int(self.headers.get("Content-Length") or 0)
  170. raw = self.rfile.read(length).decode() if length else "{}"
  171. if self.path == "/start":
  172. try:
  173. payload = json.loads(raw)
  174. except ValueError:
  175. payload = {"raw": raw}
  176. self.daemon.start_payloads.append(payload)
  177. self.daemon.append_chunk(self.daemon.PROMPT)
  178. self.daemon.append_chunk("echo hello\r\n")
  179. self.daemon.append_chunk("hello\r\n")
  180. self.daemon.state = "working"
  181. self.daemon.status_polls_after_start = 0
  182. self._send(200, {})
  183. elif self.path == "/answer":
  184. self._send(200, {})
  185. else:
  186. self._send(404, {"error": "no such route"})
  187. def do_GET(self):
  188. if self.path == "/status":
  189. if self.daemon.state == "working":
  190. self.daemon.status_polls_after_start += 1
  191. if self.daemon.status_polls_after_start >= 2:
  192. self.daemon.state = "done"
  193. self.daemon.summary = "fake daemon finished"
  194. self._send(200, {"state": self.daemon.state,
  195. "summary": self.daemon.summary})
  196. elif self.path.startswith("/output"):
  197. self._send(200, [])
  198. elif self.path.startswith("/log"):
  199. query = urllib.parse.urlparse(self.path).query
  200. since = int(urllib.parse.parse_qs(query).get("since", ["0"])[0])
  201. chunks, nxt = self.daemon.log_since(since)
  202. # Simulate the live PTY: each poll produces one more chunk.
  203. self.daemon.append_chunk("stream-line-%d\r\n" % self.daemon.next_seq)
  204. self._send(200, {"chunks": chunks, "next": nxt})
  205. else:
  206. self._send(404, {"error": "no such route"})
  207. def serve(self):
  208. handler = type("BoundHandler", (FakeSaddle.Handler,), {"daemon": self})
  209. server = ThreadingHTTPServer(("127.0.0.1", DAEMON_PORT), handler)
  210. threading.Thread(target=server.serve_forever, daemon=True).start()
  211. return server
  212. def start_app():
  213. config = json.load(open(os.path.join(REPO, "web-config.json")))
  214. config["saddle_callback_base_url"] = WEB
  215. with open(os.path.join(WORK, "web-config.json"), "w") as handle:
  216. json.dump(config, handle)
  217. env = dict(os.environ)
  218. env.update({
  219. "SPRY_DB_PATH": DB_PATH,
  220. "SPRY_SEED_ADMIN_USERNAME": "admin",
  221. "SPRY_SEED_ADMIN_PASSWORD": "adminpass123",
  222. "SADDLE_LLM_BASE_URL": "http://127.0.0.1:%d" % DAEMON_PORT,
  223. "SADDLE_PROJECTS_ROOT": os.path.join(WORK, "workspace"),
  224. })
  225. log = open(os.path.join(WORK, "app.log"), "w")
  226. process = subprocess.Popen([APP, str(APP_PORT)], cwd=WORK, env=env,
  227. stdout=log, stderr=subprocess.STDOUT)
  228. if wait_for(lambda: app_ready() or False, timeout=30, what="app ready") is None:
  229. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  230. return process
  231. def app_ready():
  232. try:
  233. status, _ = http("GET", "/login", timeout=3)
  234. return status == 200
  235. except (urllib.error.URLError, OSError):
  236. return False
  237. def main():
  238. if not os.path.exists(APP):
  239. raise SystemExit("app binary not found at %s (build first)" % APP)
  240. if os.path.exists(WORK):
  241. shutil.rmtree(WORK)
  242. os.makedirs(os.path.join(WORK, "workspace"))
  243. fake = FakeSaddle()
  244. fake.serve()
  245. app = start_app()
  246. try:
  247. auth = login("admin", "adminpass123")
  248. check(True, "login yields an auth slot")
  249. print("== feature 3: plan review hides duplicate body ==")
  250. state = slot_public(auth, "/projects", "projects")
  251. act(auth, state["create"], {
  252. "name": "demo",
  253. "git_url": "https://example.com/demo.git",
  254. "default_branch": "main",
  255. })
  256. conn = db()
  257. conn.execute("insert into tasks (project_id, title, status, priority,"
  258. " is_design_task, plan, created_at)"
  259. " values (1, 'Plan review task', 'working', 5, 1, '# The plan\n\n1. Do it',"
  260. " strftime('%s','now'))")
  261. conn.commit()
  262. plan_task = conn.execute("select max(id) from tasks").fetchone()[0]
  263. saddles_state = slot_public(auth, "/saddles", "saddles")
  264. act(auth, saddles_state["register"], {"name": "fake-saddle",
  265. "host": "127.0.0.1:%d" % DAEMON_PORT})
  266. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  267. if s["name"] == "fake-saddle"]
  268. check(len(registered) == 1 and registered[0]["token"].startswith("saddle-"),
  269. "fake saddle registered with an API token")
  270. fake_id = int(registered[0]["id"])
  271. fake_token = registered[0]["token"]
  272. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  273. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  274. (plan_task, fake_id))
  275. conn.commit()
  276. session_id = conn.execute("select max(id) from sessions").fetchone()[0]
  277. conn.close()
  278. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  279. {"type": "block", "session_id": session_id, "data": {
  280. "question": "Plan submitted for review",
  281. "type": "rfc",
  282. "body": "# The plan\n\n1. Do it"}})
  283. check(status == 200 and body.get("block_id"), "plan-review block raised")
  284. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  285. {"type": "block", "session_id": session_id, "data": {
  286. "question": "Which database?",
  287. "type": "question",
  288. "options": ["SQLite", "Postgres"],
  289. "body": "# Storage choice"}})
  290. check(status == 200, "question block raised")
  291. detail = task_state(auth, plan_task)
  292. blocks = {b["block_type"]: b for b in detail["blocks"]}
  293. check(blocks["rfc"].get("is_plan_review") is True,
  294. "rfc block flagged as the plan review")
  295. check(blocks["rfc"].get("show_body") is False,
  296. "pending plan review hides the duplicate body preview")
  297. check(blocks["question"].get("show_body") is True,
  298. "question block keeps its body preview")
  299. act(auth, blocks["rfc"]["answer_action"], {"answer": "Plan approved. Proceed."})
  300. detail = task_state(auth, plan_task)
  301. rfc = [b for b in detail["blocks"] if b["block_type"] == "rfc"][0]
  302. check(rfc.get("show_body") is True,
  303. "answered plan review shows the body again (review section gone)")
  304. finally:
  305. app.terminate()
  306. try:
  307. app.wait(timeout=5)
  308. except subprocess.TimeoutExpired:
  309. app.kill()
  310. print("%d passed, %d failed" % (passes, failures))
  311. return 1 if failures else 0
  312. if __name__ == "__main__":
  313. sys.exit(main())