web_stack_test.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. # One retry on a dropped connection: the freshly started app can
  66. # close a very early keep-alive connection once while warming up.
  67. for attempt in range(2):
  68. try:
  69. with urllib.request.urlopen(request, timeout=timeout) as response:
  70. return response.status, response.read().decode()
  71. except urllib.error.HTTPError as error:
  72. return error.code, error.read().decode()
  73. except (urllib.error.URLError, OSError):
  74. if attempt > 0:
  75. raise
  76. time.sleep(0.5)
  77. def directives(uri, auth=None):
  78. headers = {}
  79. if auth:
  80. headers["X-Statum-Slot"] = "key=%s; as_at=%s" % (auth["key"], auth["as_at"])
  81. status, body = http("GET", "/_statum/entrypoint?uri=" + urllib.parse.quote(uri.split("?")[0]),
  82. headers=headers)
  83. if status != 200:
  84. raise SystemExit("entrypoint %s -> HTTP %d: %s" % (uri, status, body[:300]))
  85. return json.loads(body)
  86. def slot_public(auth, uri, type_name):
  87. for directive in directives(uri, auth):
  88. if directive["type"] == "set":
  89. content = json.loads(directive["snapshot_frame"]["content"])
  90. if content["slot"]["type"] == type_name:
  91. return content["public"]
  92. raise SystemExit("no %s slot in entrypoint state for %s" % (type_name, uri))
  93. def act(auth, action, fields):
  94. headers = {"X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}
  95. if action.get("private"):
  96. headers["X-Statum-Private"] = action["private"]
  97. status, body = http(action.get("method", "POST"), action["uri"], fields, headers)
  98. if status != 200:
  99. raise SystemExit("action %s -> HTTP %d: %s" % (action["uri"], status, body[:300]))
  100. return json.loads(body)
  101. def login(username, password):
  102. frames = directives("/login")
  103. content = json.loads(frames[0]["snapshot_frame"]["content"])
  104. action = content["public"]["login"]
  105. status, body = http(action.get("method", "POST"), action["uri"],
  106. {"username": username, "password": password})
  107. if status != 200:
  108. raise SystemExit("login -> HTTP %d: %s" % (status, body[:300]))
  109. for directive in json.loads(body):
  110. if directive["type"] == "set":
  111. frame = json.loads(directive["snapshot_frame"]["content"])
  112. if frame["slot"]["type"] == "auth":
  113. return {"key": frame["slot"]["key"], "as_at": frame["as_at"]}
  114. raise SystemExit("login response carried no auth slot: " + body[:300])
  115. def wait_for(predicate, timeout=60, what="condition", interval=0.5):
  116. deadline = time.monotonic() + timeout
  117. last = None
  118. while time.monotonic() < deadline:
  119. last = predicate()
  120. if last is not False and last is not None:
  121. return last
  122. time.sleep(interval)
  123. print(" (timeout waiting for %s; last: %s)" % (what, last))
  124. return None
  125. def task_state(auth, task_id):
  126. return slot_public(auth, "/tasks/%d" % task_id, "task")
  127. def wait_task_done(auth, task_id, timeout=90):
  128. return wait_for(lambda: task_state(auth, task_id).get("status") == "done" or False,
  129. timeout=timeout, what="task %d -> done" % task_id)
  130. def task_id_of(title):
  131. conn = db()
  132. try:
  133. return conn.execute("select id from tasks where title = ?", (title,)).fetchone()[0]
  134. finally:
  135. conn.close()
  136. def saddle_api(method, path, token, payload=None):
  137. """Raw call against the saddle ingest API; returns (status, json)."""
  138. request = urllib.request.Request(WEB + path,
  139. data=json.dumps(payload or {}).encode(), method=method)
  140. request.add_header("Content-Type", "application/json")
  141. if token is not None:
  142. request.add_header("Authorization", "Bearer " + token)
  143. try:
  144. with urllib.request.urlopen(request, timeout=15) as response:
  145. return response.status, json.loads(response.read().decode() or "{}")
  146. except urllib.error.HTTPError as error:
  147. body = error.read().decode()
  148. try:
  149. return error.code, json.loads(body)
  150. except ValueError:
  151. return error.code, {"raw": body}
  152. def db():
  153. return sqlite3.connect(DB_PATH)
  154. class FakeSaddle:
  155. """In-process saddle daemon implementing the wire contract."""
  156. PROMPT = "bbarrow@fedora:/workspace/task-1$ "
  157. def __init__(self):
  158. self.lock = threading.Lock()
  159. self.start_payloads = [] # captured POST /start bodies
  160. self.chunks = [] # [{seq, text}] — the raw log ring
  161. self.next_seq = 1
  162. self.state = "idle"
  163. self.summary = ""
  164. self.status_polls_after_start = 0
  165. def append_chunk(self, text):
  166. with self.lock:
  167. self.chunks.append({"seq": self.next_seq, "text": text})
  168. self.next_seq += 1
  169. def log_since(self, since):
  170. with self.lock:
  171. # `since` is the inclusive resume point (wire contract: a
  172. # response ending at seq 12 carries next=13, and polling
  173. # with since=13 must still deliver the chunk numbered 13).
  174. chunks = [c for c in self.chunks if c["seq"] >= since]
  175. return chunks, self.next_seq
  176. class Handler(BaseHTTPRequestHandler):
  177. daemon = None # set on the class before serving
  178. protocol_version = "HTTP/1.1"
  179. def log_message(self, fmt, *args):
  180. pass
  181. def _send(self, status, obj):
  182. body = json.dumps(obj).encode()
  183. self.send_response(status)
  184. self.send_header("Content-Type", "application/json")
  185. self.send_header("Content-Length", str(len(body)))
  186. self.end_headers()
  187. self.wfile.write(body)
  188. def do_POST(self):
  189. length = int(self.headers.get("Content-Length") or 0)
  190. raw = self.rfile.read(length).decode() if length else "{}"
  191. if self.path == "/start":
  192. try:
  193. payload = json.loads(raw)
  194. except ValueError:
  195. payload = {"raw": raw}
  196. self.daemon.start_payloads.append(payload)
  197. self.daemon.append_chunk(self.daemon.PROMPT)
  198. self.daemon.append_chunk("echo hello\r\n")
  199. self.daemon.append_chunk("hello\r\n")
  200. self.daemon.state = "working"
  201. self.daemon.status_polls_after_start = 0
  202. self._send(200, {})
  203. elif self.path == "/answer":
  204. self._send(200, {})
  205. else:
  206. self._send(404, {"error": "no such route"})
  207. def do_GET(self):
  208. if self.path == "/status":
  209. if self.daemon.state == "working":
  210. self.daemon.status_polls_after_start += 1
  211. if self.daemon.status_polls_after_start >= 2:
  212. self.daemon.state = "done"
  213. self.daemon.summary = "fake daemon finished"
  214. self._send(200, {"state": self.daemon.state,
  215. "summary": self.daemon.summary})
  216. elif self.path.startswith("/output"):
  217. self._send(200, [])
  218. elif self.path.startswith("/log"):
  219. query = urllib.parse.urlparse(self.path).query
  220. since = int(urllib.parse.parse_qs(query).get("since", ["0"])[0])
  221. # Simulate the live PTY: each poll produces one more chunk
  222. # (before slicing, so the poller actually sees it).
  223. self.daemon.append_chunk("stream-line-%d\r\n" % self.daemon.next_seq)
  224. chunks, nxt = self.daemon.log_since(since)
  225. self._send(200, {"chunks": chunks, "next": nxt})
  226. else:
  227. self._send(404, {"error": "no such route"})
  228. self.close_connection = True
  229. def serve(self):
  230. handler = type("BoundHandler", (FakeSaddle.Handler,), {"daemon": self})
  231. server = ThreadingHTTPServer(("127.0.0.1", DAEMON_PORT), handler)
  232. threading.Thread(target=server.serve_forever, daemon=True).start()
  233. return server
  234. def start_app():
  235. config = json.load(open(os.path.join(REPO, "web-config.json")))
  236. config["saddle_callback_base_url"] = WEB
  237. with open(os.path.join(WORK, "web-config.json"), "w") as handle:
  238. json.dump(config, handle)
  239. env = dict(os.environ)
  240. env.update({
  241. "SPRY_DB_PATH": DB_PATH,
  242. "SPRY_SEED_ADMIN_USERNAME": "admin",
  243. "SPRY_SEED_ADMIN_PASSWORD": "adminpass123",
  244. "SADDLE_LLM_BASE_URL": "http://127.0.0.1:%d" % DAEMON_PORT,
  245. "SADDLE_PROJECTS_ROOT": os.path.join(WORK, "workspace"),
  246. })
  247. log = open(os.path.join(WORK, "app.log"), "w")
  248. process = subprocess.Popen([APP, str(APP_PORT)], cwd=WORK, env=env,
  249. stdout=log, stderr=subprocess.STDOUT)
  250. if wait_for(lambda: app_ready() or False, timeout=30, what="app ready") is None:
  251. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  252. return process
  253. def app_ready():
  254. try:
  255. status, _ = http("GET", "/login", timeout=3)
  256. return status == 200
  257. except (urllib.error.URLError, OSError):
  258. return False
  259. def main():
  260. if not os.path.exists(APP):
  261. raise SystemExit("app binary not found at %s (build first)" % APP)
  262. if os.path.exists(WORK):
  263. shutil.rmtree(WORK)
  264. os.makedirs(os.path.join(WORK, "workspace"))
  265. fake = FakeSaddle()
  266. fake.serve()
  267. app = start_app()
  268. try:
  269. auth = login("admin", "adminpass123")
  270. check(True, "login yields an auth slot")
  271. print("== feature 3: plan review hides duplicate body ==")
  272. state = slot_public(auth, "/projects", "projects")
  273. act(auth, state["create"], {
  274. "name": "demo",
  275. "git_url": "https://example.com/demo.git",
  276. "default_branch": "main",
  277. })
  278. conn = db()
  279. conn.execute("insert into tasks (project_id, title, status, priority,"
  280. " is_design_task, plan, created_at)"
  281. " values (1, 'Plan review task', 'working', 5, 1, '# The plan\n\n1. Do it',"
  282. " strftime('%s','now'))")
  283. conn.commit()
  284. plan_task = conn.execute("select max(id) from tasks").fetchone()[0]
  285. saddles_state = slot_public(auth, "/saddles", "saddles")
  286. act(auth, saddles_state["register"], {"name": "fake-saddle",
  287. "host": "127.0.0.1:%d" % DAEMON_PORT})
  288. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  289. if s["name"] == "fake-saddle"]
  290. check(len(registered) == 1 and registered[0]["token"].startswith("saddle-"),
  291. "fake saddle registered with an API token")
  292. fake_id = int(registered[0]["id"])
  293. fake_token = registered[0]["token"]
  294. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  295. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  296. (plan_task, fake_id))
  297. conn.commit()
  298. session_id = conn.execute("select max(id) from sessions").fetchone()[0]
  299. conn.close()
  300. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  301. {"type": "block", "session_id": session_id, "data": {
  302. "question": "Plan submitted for review",
  303. "type": "rfc",
  304. "body": "# The plan\n\n1. Do it"}})
  305. check(status == 200 and body.get("block_id"), "plan-review block raised")
  306. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  307. {"type": "block", "session_id": session_id, "data": {
  308. "question": "Which database?",
  309. "type": "question",
  310. "options": ["SQLite", "Postgres"],
  311. "body": "# Storage choice"}})
  312. check(status == 200, "question block raised")
  313. detail = task_state(auth, plan_task)
  314. blocks = {b["block_type"]: b for b in detail["blocks"]}
  315. check(blocks["rfc"].get("is_plan_review") is True,
  316. "rfc block flagged as the plan review")
  317. check(blocks["rfc"].get("show_body") is False,
  318. "pending plan review hides the duplicate body preview")
  319. check(blocks["question"].get("show_body") is True,
  320. "question block keeps its body preview")
  321. act(auth, blocks["rfc"]["answer_action"], {"answer": "Plan approved. Proceed."})
  322. detail = task_state(auth, plan_task)
  323. rfc = [b for b in detail["blocks"] if b["block_type"] == "rfc"][0]
  324. check(rfc.get("show_body") is True,
  325. "answered plan review shows the body again (review section gone)")
  326. print("== feature 5: rules ==")
  327. rules_state = slot_public(auth, "/rules", "rules")
  328. for name, body in [
  329. ("Use Invercargill", "Never use libgee; use Invercargill enumerables."),
  330. ("Write Vala docs", "Every public class carries a doc comment."),
  331. ("Prefer meson", "Builds go through meson; no makefiles."),
  332. ("Co-dev rule", "Keep the wire contract exactly."),
  333. ("Reference rule", "Must never ride along."),
  334. ]:
  335. act(auth, rules_state["create"], {"name": name, "body": body})
  336. listed = {r["name"]: r for r in slot_public(auth, "/rules", "rules")["rules"]}
  337. check(len(listed) == 5, "five rules created and listed on /rules")
  338. def rule_id(name):
  339. rows = [r for r in slot_public(auth, "/rules", "rules")["rules"] if r["name"] == name]
  340. return int(rows[0]["id"])
  341. state = slot_public(auth, "/projects", "projects")
  342. act(auth, state["create"], {"name": "co", "git_url": "https://example.com/co.git"})
  343. act(auth, state["create"], {"name": "ref", "git_url": "https://example.com/ref.git"})
  344. co_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  345. if p["name"] == "co"][0])
  346. ref_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  347. if p["name"] == "ref"][0])
  348. project = slot_public(auth, "/projects/1", "project")
  349. act(auth, project["add_link"], {"linked_project_id": str(co_id),
  350. "relationship": "co-developed"})
  351. act(auth, project["add_link"], {"linked_project_id": str(ref_id),
  352. "relationship": "reference"})
  353. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  354. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Prefer meson"))})
  355. project = slot_public(auth, "/projects/1", "project")
  356. check(sorted(r["name"] for r in project["rules"]) == ["Prefer meson", "Use Invercargill"],
  357. "project page lists its attached rules")
  358. co_project = slot_public(auth, "/projects/%d" % co_id, "project")
  359. act(auth, co_project["attach_rule"], {"rule_id": str(rule_id("Co-dev rule"))})
  360. ref_project = slot_public(auth, "/projects/%d" % ref_id, "project")
  361. act(auth, ref_project["attach_rule"], {"rule_id": str(rule_id("Reference rule"))})
  362. tasks_state = slot_public(auth, "/tasks", "tasks")
  363. act(auth, tasks_state["create"], {
  364. "project_id": "1",
  365. "title": "Rules dispatch",
  366. "description": "Effective rule set rides the /start payload.",
  367. "priority": "2",
  368. })
  369. rule_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  370. if t["title"] == "Rules dispatch"][0])
  371. detail = task_state(auth, rule_task)
  372. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Write Vala docs"))})
  373. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  374. detail = task_state(auth, rule_task)
  375. check(sorted(r["name"] for r in detail["rules"]) == ["Use Invercargill", "Write Vala docs"],
  376. "task page lists its attached rules")
  377. check(wait_for(lambda: len(fake.start_payloads) > 0 or False,
  378. timeout=30, what="/start push") is not None,
  379. "dispatcher pushes the task to the fake saddle")
  380. payload = fake.start_payloads[-1]
  381. rule_names = [r["name"] for r in payload.get("rules", [])]
  382. check(rule_names == ["Write Vala docs", "Use Invercargill", "Prefer meson", "Co-dev rule"],
  383. "effective rules in /start: task, primary, co-developed order (%s)" % rule_names)
  384. check(all(r.get("body") for r in payload.get("rules", [])),
  385. "rules carry their bodies")
  386. check("Reference rule" not in rule_names,
  387. "reference project rules excluded")
  388. detail = task_state(auth, rule_task)
  389. act(auth, detail["rules"][0]["detach"], {})
  390. check([r["name"] for r in task_state(auth, rule_task)["rules"]] == ["Use Invercargill"],
  391. "detached task rule disappears")
  392. rules_rows = slot_public(auth, "/rules", "rules")["rules"]
  393. docs_row = [r for r in rules_rows if r["name"] == "Write Vala docs"][0]
  394. act(auth, docs_row["update"], {"name": "Write Vala docs", "body": "Doc comments or bust."})
  395. check(any(r["body"] == "Doc comments or bust."
  396. for r in slot_public(auth, "/rules", "rules")["rules"]),
  397. "rule edit saves the body")
  398. check(wait_task_done(auth, rule_task, timeout=60) is not None,
  399. "dispatched task completes against the fake daemon")
  400. print("== feature 6: project notes + callback ==")
  401. conn = db()
  402. callback_rows = conn.execute(
  403. "select token from api_tokens where saddle_id = 0").fetchall()
  404. conn.close()
  405. check(len(callback_rows) == 1 and callback_rows[0][0].startswith("saddle-callback-"),
  406. "dedicated saddle-callback token minted at startup")
  407. callback_token = callback_rows[0][0]
  408. status, _ = saddle_api("POST", "/api/saddle/note", None,
  409. {"project": "demo", "body": "x"})
  410. check(status == 401, "note endpoint rejects a missing token")
  411. status, _ = saddle_api("POST", "/api/saddle/note", "saddle-callback-not-real",
  412. {"project": "demo", "body": "x"})
  413. check(status == 401, "note endpoint rejects a wrong token")
  414. status, body = saddle_api("POST", "/api/saddle/note", callback_token,
  415. {"task_id": rule_task, "project": "demo",
  416. "body": "style.css tokens live in :root"})
  417. check(status == 200 and body.get("ok") is True, "note accepted with the callback token")
  418. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  419. {"project": "no-such-project", "body": "x"})
  420. check(status == 400, "unknown project rejected")
  421. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  422. {"project": "demo", "body": " "})
  423. check(status == 400, "empty note body rejected")
  424. project = slot_public(auth, "/projects/1", "project")
  425. check(any("style.css tokens" in n["body"] and int(n["source_task_id"]) == rule_task
  426. for n in project["notes"]),
  427. "project page lists the note with its source task")
  428. act(auth, [n for n in project["notes"] if "style.css tokens" in n["body"]][0]["delete"], {})
  429. check(all("style.css tokens" not in n["body"]
  430. for n in slot_public(auth, "/projects/1", "project")["notes"]),
  431. "note deleted from the project page")
  432. # /start payload: notes of primary + co-developed (not reference),
  433. # oldest first; callback carries the configured base URL + token.
  434. saddle_api("POST", "/api/saddle/note", callback_token,
  435. {"project": "demo", "body": "note-one"})
  436. saddle_api("POST", "/api/saddle/note", callback_token,
  437. {"project": "demo", "body": "note-two"})
  438. saddle_api("POST", "/api/saddle/note", callback_token,
  439. {"project": "co", "body": "co-note"})
  440. conn = db()
  441. conn.execute("insert into project_notes (project_id, body, created_at)"
  442. " values (?, 'ref-note-must-not-ship', strftime('%s','now'))", (ref_id,))
  443. conn.commit()
  444. conn.close()
  445. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  446. "project_id": "1",
  447. "title": "Notes dispatch",
  448. "description": "Project notes ride the /start payload.",
  449. "priority": "2",
  450. })
  451. check(wait_for(lambda: len(fake.start_payloads) >= 2 or False,
  452. timeout=30, what="second /start push") is not None,
  453. "dispatcher pushes the notes task")
  454. payload = fake.start_payloads[-1]
  455. notes = payload.get("project_notes", [])
  456. check([n["body"] for n in notes] == ["note-one", "note-two", "co-note"],
  457. "project_notes: primary + co-developed, oldest first (%s)" % [n["body"] for n in notes])
  458. check(all(n.get("project") for n in notes)
  459. and notes[2]["project"] == "co",
  460. "project_notes carry the project name")
  461. check("ref-note-must-not-ship" not in [n["body"] for n in notes],
  462. "reference project notes excluded")
  463. callback = payload.get("callback", {})
  464. check(callback.get("base_url") == WEB and callback.get("token") == callback_token,
  465. "callback carries the configured base URL and the minted token")
  466. # entry cap: 30 of 33 candidates
  467. conn = db()
  468. for i in range(33):
  469. conn.execute("insert into project_notes (project_id, body, created_at)"
  470. " values (?, ?, strftime('%s','now'))", (1, "bulk-%02d" % i))
  471. conn.commit()
  472. conn.close()
  473. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  474. "project_id": "1",
  475. "title": "Entry cap dispatch",
  476. "priority": "2",
  477. })
  478. check(wait_for(lambda: len(fake.start_payloads) >= 3 or False,
  479. timeout=30, what="third /start push") is not None,
  480. "dispatcher pushes the entry-cap task")
  481. notes = fake.start_payloads[-1].get("project_notes", [])
  482. check(len(notes) == 30 and notes[0]["body"] == "note-one" and notes[1]["body"] == "note-two",
  483. "project_notes capped at 30 entries, oldest kept (%d)" % len(notes))
  484. # char cap: the giant note is truncated so the total stays <= 20000
  485. conn = db()
  486. conn.execute("delete from project_notes where body like 'bulk-%' or body = 'co-note'")
  487. conn.execute("insert into project_notes (project_id, body, created_at)"
  488. " values (?, ?, strftime('%s','now'))", (1, "giant!" + "x" * 25000,))
  489. conn.commit()
  490. conn.close()
  491. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  492. "project_id": "1",
  493. "title": "Char cap dispatch",
  494. "priority": "2",
  495. })
  496. check(wait_for(lambda: len(fake.start_payloads) >= 4 or False,
  497. timeout=30, what="fourth /start push") is not None,
  498. "dispatcher pushes the char-cap task")
  499. notes = fake.start_payloads[-1].get("project_notes", [])
  500. total = sum(len(n["body"]) for n in notes)
  501. check(len(notes) == 3 and total == 20000 and notes[2]["body"].startswith("giant!"),
  502. "project_notes char cap: head kept, giant truncated (entries=%d, chars=%d)"
  503. % (len(notes), total))
  504. print("== raw log polling + terminal raw view ==")
  505. # Wait for the last dispatch to finish so its final polls ran.
  506. check(wait_task_done(auth, task_id_of("Char cap dispatch"), timeout=60) is not None,
  507. "char-cap task completes")
  508. conn = db()
  509. raw_session = conn.execute(
  510. "select s.id from sessions s join tasks t on t.id = s.task_id"
  511. " where t.title = 'Char cap dispatch' order by s.id desc limit 1").fetchone()[0]
  512. rows = conn.execute("select seq, chunk from session_raw_log where session_id = ?"
  513. " order by seq", (raw_session,)).fetchall()
  514. conn.close()
  515. check(len(rows) >= 3, "session_raw_log captured the daemon's chunks (%d)" % len(rows))
  516. seqs = [r[0] for r in rows]
  517. check(seqs == sorted(seqs) and len(set(seqs)) == len(seqs),
  518. "raw chunks stored once, seq strictly increasing")
  519. text = "".join(r[1] for r in rows)
  520. check(fake.PROMPT in text and "echo hello" in text and "hello" in text,
  521. "raw log keeps the prompt and echoed output byte-exact")
  522. check("stream-line-" in text, "incremental /log polls append later chunks")
  523. terminal = slot_public(auth, "/tasks/%d/terminal" % task_id_of("Char cap dispatch"),
  524. "terminal")
  525. check(terminal.get("has_raw_log") is True and int(terminal["session_id"]) == raw_session,
  526. "terminal view selects raw rendering for the raw session")
  527. # Old sessions (typed entries, no raw rows) keep the fallback view.
  528. conn = db()
  529. conn.execute("insert into session_commands (session_id, command_text, output_text,"
  530. " type, started_at) values (?, 'ls', 'old-output', 'command',"
  531. " strftime('%s','now'))", (session_id,))
  532. conn.commit()
  533. conn.close()
  534. legacy = slot_public(auth, "/tasks/%d/terminal" % plan_task, "terminal")
  535. check(legacy.get("has_raw_log") is False,
  536. "legacy session falls back to the entry-type terminal view")
  537. request = urllib.request.Request(WEB + "/terminal-stream/%d" % raw_session)
  538. with urllib.request.urlopen(request, timeout=15) as stream:
  539. raw_events = []
  540. deadline = time.monotonic() + 8
  541. while time.monotonic() < deadline and len(raw_events) < 3:
  542. line = stream.readline().decode().strip()
  543. if not line.startswith("data: ") or line == "data: ping":
  544. continue
  545. event = json.loads(line[6:])
  546. if event.get("type") == "raw":
  547. raw_events.append(event)
  548. check(len(raw_events) >= 3 and raw_events[0]["text"] == fake.PROMPT
  549. and raw_events[0]["seq"] < raw_events[1]["seq"],
  550. "terminal stream serves raw chunks in seq order (prompt first)")
  551. finally:
  552. app.terminate()
  553. try:
  554. app.wait(timeout=5)
  555. except subprocess.TimeoutExpired:
  556. app.kill()
  557. print("%d passed, %d failed" % (passes, failures))
  558. return 1 if failures else 0
  559. if __name__ == "__main__":
  560. sys.exit(main())