test_task_log_js.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  1. #!/usr/bin/env python3
  2. """Static + logic tests for the task event-log page's client JS.
  3. The app binary cannot be built in every container (statum-mkpstm /
  4. libstatum are build-time dependencies), so this suite verifies
  5. src/pages/task_log.html two ways:
  6. 1. Statically - the <script> body must be ASCII-only (the page
  7. compiler HTML-escapes script bodies, so any non-ASCII literal is
  8. re-served as literal entity text like "&middot;" after the
  9. browser's one decode pass), must wire the SSE stream through
  10. `onmessage` (the server sends id:/data: frames with no `event:`
  11. name, so named listeners can never fire), must not listen for an
  12. 'append' event name, and its delimiter structure must balance
  13. after strings and comments are stripped.
  14. 2. Behaviourally - the ingest / render-order / scroll-stick /
  15. load-more logic is ported verbatim below as pure python functions
  16. and unit-tested: oldest-first chronology, id dedupe, the 48px
  17. bottom-stick rule, prepend-mode scroll anchoring, and the
  18. newest-first-page reversal with the `more` -> exhausted flag.
  19. Runnable standalone: python3 test/test_task_log_js.py
  20. """
  21. import json
  22. import os
  23. import re
  24. import unittest
  25. PAGE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  26. os.pardir, "src", "pages", "task_log.html")
  27. def script_body():
  28. with open(PAGE, encoding="utf-8") as handle:
  29. source = handle.read()
  30. head, rest = source.split("<script>", 1)
  31. body, _ = rest.split("</script>", 1)
  32. assert head, "no content before the script block"
  33. return body
  34. # ---------------------------------------------------------------------------
  35. # Static checks
  36. # ---------------------------------------------------------------------------
  37. class ScriptSourceTests(unittest.TestCase):
  38. """What the served bytes must look like after compilation."""
  39. def setUp(self):
  40. self.body = script_body()
  41. def test_script_is_ascii_only(self):
  42. """Non-ASCII in a script body comes back as literal entity
  43. text ("&middot;") because the compiler escapes script bodies
  44. and the browser decodes exactly once. ASCII (with \\uXXXX
  45. escapes for the characters we want) is immune."""
  46. offenders = [(index, hex(ord(char)))
  47. for index, char in enumerate(self.body) if ord(char) > 127]
  48. self.assertEqual(offenders, [])
  49. def test_unicode_escapes_used_for_separators(self):
  50. """The separator characters must still render - as escapes,
  51. not as raw bytes and not as HTML entities."""
  52. for escape in ("\\u00b7", "\\u2026", "\\u2014"):
  53. self.assertIn(escape, self.body)
  54. self.assertNotIn("&middot;", self.body)
  55. self.assertNotIn("&mdash;", self.body)
  56. def test_stream_wired_through_onmessage(self):
  57. self.assertRegex(self.body, r"stream\.onmessage\s*=")
  58. self.assertNotIn("addEventListener('append'", self.body)
  59. self.assertNotIn('addEventListener("append"', self.body)
  60. def test_heartbeat_ping_is_skipped(self):
  61. self.assertRegex(self.body, r"message\.data\s*===\s*'ping'")
  62. def test_load_more_pages_before_oldest(self):
  63. self.assertRegex(self.body, r"/events\?before='\s*\+\s*\(state\.oldest")
  64. def test_page_is_reversed_before_ingest(self):
  65. self.assertIn("slice().reverse().forEach(ingest)", self.body)
  66. def test_exhausted_set_when_no_more(self):
  67. self.assertIn("state.exhausted = true", self.body)
  68. def test_more_button_sits_above_the_feed(self):
  69. # Search the page markup only - the script's comments also
  70. # mention [data-log-feed], before the elements do.
  71. with open(PAGE, encoding="utf-8") as handle:
  72. markup = handle.read().split("</script>", 1)[1]
  73. more = markup.index("data-log-more")
  74. feed = markup.index("data-log-feed")
  75. self.assertLess(more, feed,
  76. "the load-older control must precede the feed markup")
  77. def test_delimiters_balance(self):
  78. """A cheap structural stand-in for a JS parser (none is
  79. installed here): after stripping comments and string literals
  80. every bracket must close."""
  81. body = self.body
  82. out = []
  83. i = 0
  84. mode = None # None | 'line' | 'block' | "'" | '"'
  85. while i < len(body):
  86. char = body[i]
  87. nxt = body[i + 1] if i + 1 < len(body) else ""
  88. if mode is None:
  89. if char == "/" and nxt == "/":
  90. mode = "line"
  91. i += 2
  92. continue
  93. if char == "/" and nxt == "*":
  94. mode = "block"
  95. i += 2
  96. continue
  97. if char in "'\"":
  98. mode = char
  99. i += 1
  100. continue
  101. out.append(char)
  102. elif mode == "line":
  103. if char == "\n":
  104. mode = None
  105. out.append("\n")
  106. elif mode == "block":
  107. if char == "*" and nxt == "/":
  108. mode = None
  109. i += 2
  110. continue
  111. else: # inside a string literal
  112. if char == "\\":
  113. i += 2
  114. continue
  115. if char == mode:
  116. mode = None
  117. i += 1
  118. self.assertEqual(mode, None, "unterminated comment or string literal")
  119. pairs = {")": "(", "]": "[", "}": "{"}
  120. stack = []
  121. for char in out:
  122. if char in "([{":
  123. stack.append(char)
  124. elif char in pairs:
  125. self.assertTrue(stack and stack[-1] == pairs[char],
  126. "unbalanced %r at depth %s" % (char, stack))
  127. stack.pop()
  128. self.assertEqual(stack, [], "unclosed delimiters %s" % stack)
  129. # ---------------------------------------------------------------------------
  130. # Port of the client logic (keep in step with task_log.html)
  131. # ---------------------------------------------------------------------------
  132. STICK_THRESHOLD = 48 # px that still counts as "reading the tail"
  133. PAGE_SIZE = 30
  134. class Feed(object):
  135. """Scroll-state stand-in for [data-log-feed]."""
  136. def __init__(self, scroll_height=0, client_height=600, scroll_top=0):
  137. self.scroll_height = scroll_height
  138. self.client_height = client_height
  139. self.scroll_top = scroll_top
  140. def at_bottom(feed):
  141. """PORT: a feed shorter than its viewport counts as at-bottom."""
  142. return feed.scroll_height - feed.scroll_top - feed.client_height \
  143. <= STICK_THRESHOLD
  144. class State(object):
  145. """PORT: the module-level `state` object."""
  146. def __init__(self):
  147. self.events = []
  148. self.oldest = 0
  149. self.exhausted = False
  150. self.loading = False
  151. self.seeded = False
  152. def ingest(state, evt):
  153. """PORT: keep state.events oldest-first (ascending id); skip ids
  154. already held (SSE replay after a reconnect resends a frame)."""
  155. i = 0
  156. while i < len(state.events) and state.events[i]["id"] < evt["id"]:
  157. i += 1
  158. if i < len(state.events) and state.events[i]["id"] == evt["id"]:
  159. return
  160. state.events.insert(i, evt)
  161. if evt["id"] < state.oldest or state.oldest == 0:
  162. state.oldest = evt["id"]
  163. def render(state, feed, mode=None, height_after=None):
  164. """PORT of render(mode): decide the post-render scroll position.
  165. height_after stands in for the DOM rebuild's new scrollHeight."""
  166. was_at_bottom = at_bottom(feed)
  167. height_before = feed.scroll_height
  168. scroll_top_before = feed.scroll_top
  169. if height_after is not None:
  170. feed.scroll_height = height_after
  171. if not state.seeded and len(state.events) > 0:
  172. state.seeded = True
  173. feed.scroll_top = feed.scroll_height # scrollToBottom()
  174. elif mode == "prepend":
  175. if was_at_bottom:
  176. feed.scroll_top = feed.scroll_height
  177. else:
  178. feed.scroll_top = scroll_top_before + (feed.scroll_height
  179. - height_before)
  180. elif was_at_bottom:
  181. feed.scroll_top = feed.scroll_height
  182. else:
  183. feed.scroll_top = scroll_top_before
  184. return feed.scroll_top
  185. def server_page(newest, oldest, more):
  186. """The endpoint's wire shape: newest-first within the page."""
  187. return {"events": [{"id": i} for i in range(newest, oldest - 1, -1)],
  188. "more": more}
  189. def load_more(state, feed, page, height_after):
  190. """PORT of loadMore's success path: reverse the newest-first page
  191. into chronological order, ingest it, set exhausted, render."""
  192. rows = page["events"]
  193. for evt in reversed(rows):
  194. ingest(state, evt)
  195. if not page["more"] or len(rows) == 0:
  196. state.exhausted = True
  197. return render(state, feed, mode="prepend", height_after=height_after)
  198. def on_stream_message(state, feed, data, height_after):
  199. """PORT of onStreamMessage: skip heartbeats, ingest one row."""
  200. if data == "ping":
  201. return feed.scroll_top
  202. ingest(state, {"id": int(data)})
  203. return render(state, feed, mode="append", height_after=height_after)
  204. # ---------------------------------------------------------------------------
  205. # Behaviour tests
  206. # ---------------------------------------------------------------------------
  207. def ids(state):
  208. return [evt["id"] for evt in state.events]
  209. class ChronologyTests(unittest.TestCase):
  210. def test_initial_window_renders_oldest_first(self):
  211. """The SSE replay / first JSON page arrives newest-first
  212. ([30..1]); the feed must render [1..30] - oldest at the top."""
  213. state = State()
  214. for evt in server_page(30, 1, True)["events"]:
  215. ingest(state, evt)
  216. self.assertEqual(ids(state), list(range(1, 31)))
  217. self.assertEqual(state.oldest, 1)
  218. def test_live_appends_land_in_order(self):
  219. state = State()
  220. for i in range(30, 0, -1):
  221. ingest(state, {"id": i})
  222. ingest(state, {"id": 31})
  223. ingest(state, {"id": 33})
  224. ingest(state, {"id": 32}) # out of order arrival
  225. self.assertEqual(ids(state)[-3:], [31, 32, 33])
  226. def test_duplicate_ids_are_dropped(self):
  227. state = State()
  228. ingest(state, {"id": 5})
  229. ingest(state, {"id": 5}) # EventSource reconnect replay
  230. self.assertEqual(ids(state), [5])
  231. class ScrollStickTests(unittest.TestCase):
  232. def test_first_render_with_rows_seeds_at_the_bottom(self):
  233. state = State()
  234. feed = Feed(scroll_height=0, client_height=600)
  235. for evt in server_page(30, 1, True)["events"]:
  236. ingest(state, evt)
  237. render(state, feed, height_after=3000)
  238. self.assertTrue(state.seeded)
  239. self.assertEqual(feed.scroll_top, 3000)
  240. def test_append_sticks_when_reading_the_tail(self):
  241. state = State()
  242. feed = Feed(scroll_height=3000, client_height=600)
  243. state.seeded = True
  244. feed.scroll_top = 2400 # exactly at the bottom
  245. self.assertTrue(at_bottom(feed))
  246. ingest(state, {"id": 31})
  247. render(state, feed, mode="append", height_after=3100)
  248. self.assertEqual(feed.scroll_top, 3100)
  249. def test_append_within_threshold_still_sticks(self):
  250. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2360)
  251. self.assertTrue(at_bottom(feed)) # 40px shy: close enough
  252. def test_just_past_threshold_is_not_the_tail(self):
  253. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2351)
  254. self.assertFalse(at_bottom(feed)) # 49px shy: reading history
  255. def test_scrolled_up_reader_is_never_yanked(self):
  256. state = State()
  257. feed = Feed(scroll_height=3000, client_height=600, scroll_top=500)
  258. state.seeded = True
  259. self.assertFalse(at_bottom(feed))
  260. ingest(state, {"id": 31})
  261. render(state, feed, mode="append", height_after=3100)
  262. self.assertEqual(feed.scroll_top, 500)
  263. def test_short_feed_counts_as_at_bottom(self):
  264. """A feed shorter than its viewport cannot be scrolled away
  265. from the newest row."""
  266. feed = Feed(scroll_height=100, client_height=600, scroll_top=0)
  267. self.assertTrue(at_bottom(feed))
  268. def test_heartbeat_does_not_touch_anything(self):
  269. state = State()
  270. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2400)
  271. state.seeded = True
  272. before = (list(ids(state)), feed.scroll_top)
  273. on_stream_message(state, feed, "ping", height_after=3100)
  274. self.assertEqual((list(ids(state)), feed.scroll_top), before)
  275. class LoadMoreTests(unittest.TestCase):
  276. def test_older_page_is_reversed_and_prepended(self):
  277. """before=<oldest>=1 returns [60..31] newest-first on the
  278. wire; the display must gain [31..60] above [1..30]."""
  279. state = State()
  280. feed = Feed(scroll_height=3000, client_height=600, scroll_top=500)
  281. for evt in server_page(30, 1, True)["events"]:
  282. ingest(state, evt)
  283. state.seeded = True
  284. render(state, feed, height_after=3000)
  285. feed.scroll_top = 500 # the reader scrolled up into history
  286. load_more(state, feed, server_page(60, 31, True), height_after=6000)
  287. self.assertEqual(ids(state), list(range(1, 61)))
  288. self.assertEqual(state.oldest, 1)
  289. self.assertFalse(state.exhausted)
  290. def test_prepend_keeps_the_viewport_anchored(self):
  291. """Content added above must not move the rows under the
  292. reader's cursor: scrollTop grows by the added height."""
  293. state = State()
  294. feed = Feed(scroll_height=3000, client_height=600, scroll_top=500)
  295. state.seeded = True
  296. self.assertFalse(at_bottom(feed))
  297. delta = 3000
  298. load_more(state, feed, server_page(60, 31, True),
  299. height_after=3000 + delta)
  300. self.assertEqual(feed.scroll_top, 500 + delta)
  301. def test_prepend_while_at_bottom_stays_at_bottom(self):
  302. state = State()
  303. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2400)
  304. state.seeded = True
  305. self.assertTrue(at_bottom(feed))
  306. load_more(state, feed, server_page(60, 31, True), height_after=6000)
  307. self.assertEqual(feed.scroll_top, 6000)
  308. def test_exhausted_when_more_is_false(self):
  309. state = State()
  310. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2400)
  311. state.seeded = True
  312. load_more(state, feed, server_page(60, 31, False), height_after=6000)
  313. self.assertTrue(state.exhausted)
  314. def test_empty_page_exhausts_too(self):
  315. """A defensive guard: a page with no rows means no older
  316. history, whatever the flag says."""
  317. state = State()
  318. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2400)
  319. state.seeded = True
  320. ingest(state, {"id": 1})
  321. load_more(state, feed, {"events": [], "more": True}, height_after=3000)
  322. self.assertTrue(state.exhausted)
  323. class EndToEndSequenceTests(unittest.TestCase):
  324. """The whole first-minute story: replay, live tail, history."""
  325. def test_replay_then_append_then_history(self):
  326. state = State()
  327. feed = Feed(scroll_height=0, client_height=600)
  328. # 1. SSE replay: most-recent-30 oldest-first on the wire.
  329. for evt in server_page(30, 1, True)["events"]:
  330. ingest(state, evt)
  331. render(state, feed, height_after=3000)
  332. self.assertEqual(ids(state), list(range(1, 31)))
  333. self.assertEqual(feed.scroll_top, 3000) # seeded at the tail
  334. # 2. Two live rows arrive; the reader is at the bottom.
  335. on_stream_message(state, feed, "31", height_after=3100)
  336. on_stream_message(state, feed, "32", height_after=3200)
  337. self.assertEqual(ids(state)[-2:], [31, 32])
  338. self.assertEqual(feed.scroll_top, 3200)
  339. # 3. A heartbeat is ignored, then the reader scrolls up.
  340. on_stream_message(state, feed, "ping", height_after=3200)
  341. feed.scroll_top = 100
  342. on_stream_message(state, feed, "33", height_after=3300)
  343. self.assertEqual(feed.scroll_top, 100) # never yanked
  344. # 4. Load older: before=1 -> [60..31] newest-first wire page.
  345. self.assertEqual(state.oldest, 1)
  346. load_more(state, feed, server_page(60, 31, False), height_after=6300)
  347. self.assertEqual(ids(state), list(range(1, 61)))
  348. self.assertTrue(state.exhausted)
  349. self.assertEqual(feed.scroll_top, 100 + 3000) # anchored
  350. # ---------------------------------------------------------------------------
  351. # Payload contract: the daemon JSON-encodes args/result into STRINGS
  352. # ---------------------------------------------------------------------------
  353. def parse_maybe_json(value):
  354. """PORT of parseMaybeJson: strings decode, objects pass through,
  355. a non-JSON string answers None so the caller can fall back to
  356. rendering the raw text."""
  357. if not isinstance(value, str):
  358. return value
  359. try:
  360. return json.loads(value)
  361. except ValueError:
  362. return None
  363. def is_plain_object(value):
  364. """PORT of isPlainObject."""
  365. return isinstance(value, dict)
  366. def fmt_bytes(n):
  367. """PORT of fmtBytes."""
  368. if n < 1024:
  369. return "%d B" % n
  370. if n < 1024 * 1024:
  371. return "%.1f KiB" % (n / 1024)
  372. return "%.1f MiB" % (n / (1024 * 1024))
  373. def str_text(value):
  374. """PORT of strText."""
  375. return value if isinstance(value, str) else ""
  376. def filter_of(kind):
  377. """PORT of filterOf: which filter bucket owns a kind. The yeehaw
  378. celebration lands in the comments bucket (goal 9 task 4b)."""
  379. if kind == "tool_call":
  380. return "commands"
  381. if kind in ("tool_result", "command_output"):
  382. return "results"
  383. if kind in ("comment", "answer", "verdict", "yeehaw"):
  384. return "comments"
  385. if kind == "usage":
  386. return "usage"
  387. return "transitions"
  388. def yeehaw_render(evt):
  389. """PORT of eventNode's yeehaw branch -> (span_class, message)."""
  390. payload = evt.get("payload") or {}
  391. return "yeehaw-message", str_text(payload.get("message"))
  392. def fmt_duration(ms):
  393. """PORT of fmtDuration."""
  394. if ms < 1000:
  395. return "%d ms" % ms
  396. return "%.1f s" % (ms / 1000)
  397. def str_bytes(value):
  398. """PORT of strBytes."""
  399. return len(value) if isinstance(value, str) else 0
  400. def result_envelope(evt):
  401. """PORT of resultEnvelope: the parsed result string when it
  402. decodes to an object, else the object-shaped payload itself."""
  403. payload = evt.get("payload") or {}
  404. parsed = parse_maybe_json(payload.get("result"))
  405. if is_plain_object(parsed):
  406. return parsed
  407. if is_plain_object(payload):
  408. return payload
  409. return {}
  410. RESULT_PLUMBING = ("ok", "exit_code", "stdout", "stderr", "bytes_out",
  411. "bytes_err", "truncated", "duration_ms", "turn", "tool")
  412. def result_extras(envelope):
  413. """PORT of resultExtras: the envelope minus command plumbing
  414. and minus the note members (rendered separately)."""
  415. return dict((key, value) for key, value in envelope.items()
  416. if key not in RESULT_PLUMBING
  417. and key not in ("error", "note", "timeout"))
  418. def result_summary(evt):
  419. """PORT of resultSummary -> the summary line's text."""
  420. envelope = result_envelope(evt)
  421. payload = evt.get("payload") or {}
  422. bits = []
  423. if envelope.get("exit_code") is not None:
  424. bits.append("exit %s" % envelope["exit_code"])
  425. elif envelope.get("ok") is False:
  426. bits.append("failed")
  427. if isinstance(envelope.get("bytes_out"), int) \
  428. and isinstance(envelope.get("bytes_err"), int):
  429. bytes_count = envelope["bytes_out"] + envelope["bytes_err"]
  430. else:
  431. bytes_count = str_bytes(envelope.get("stdout")) \
  432. + str_bytes(envelope.get("stderr"))
  433. if bytes_count > 0:
  434. bits.append(fmt_bytes(bytes_count))
  435. if envelope.get("truncated"):
  436. bits.append("truncated")
  437. if isinstance(envelope.get("duration_ms"), int):
  438. bits.append(fmt_duration(envelope["duration_ms"]))
  439. if payload.get("turn") is not None:
  440. bits.append("turn %s" % payload["turn"])
  441. # PORT: a non-JSON result string carries no envelope; its own
  442. # size is the only metric we have.
  443. if not bits and isinstance(payload.get("result"), str) \
  444. and not is_plain_object(parse_maybe_json(payload["result"])):
  445. bits.append(fmt_bytes(len(payload["result"])))
  446. return "result" + (" (" + ", ".join(bits) + ")" if bits else "")
  447. def result_output(evt):
  448. """PORT of resultBody's text decisions -> (stdout_text,
  449. stderr_text, note_text, extras_text, no_output_flag). The extras
  450. go through the tailored result body first (a read window, a
  451. replacement count, a task list, an ok ack), then raw JSON."""
  452. envelope = result_envelope(evt)
  453. payload = evt.get("payload") or {}
  454. parsed = parse_maybe_json(payload.get("result"))
  455. out = err = ""
  456. if is_plain_object(parsed):
  457. out = str_text(envelope.get("stdout"))
  458. err = str_text(envelope.get("stderr"))
  459. elif isinstance(parsed, str):
  460. out = parsed # a JSON string literal
  461. elif isinstance(payload.get("result"), str):
  462. out = payload["result"]
  463. else:
  464. out = str_text(envelope.get("stdout"))
  465. err = str_text(envelope.get("stderr"))
  466. note = ""
  467. extras = ""
  468. if not out and not err:
  469. note = str_text(envelope.get("error")) or str_text(envelope.get("note")) \
  470. or ("timed out" if envelope.get("timeout") else "")
  471. if not note:
  472. remainder = result_extras(envelope)
  473. if remainder:
  474. tailored = tailored_result_text(
  475. str_text(payload.get("tool")), remainder)
  476. if tailored is not None:
  477. extras = tailored
  478. else:
  479. compact = json.dumps(remainder)
  480. extras = compact if len(compact) <= 120 \
  481. else json.dumps(remainder, indent=2)
  482. return out, err, note, extras, (not out and not err and not note and not extras)
  483. def task_list_text(items):
  484. """PORT of taskList -> one '#id title status' line per item."""
  485. lines = []
  486. for item in items:
  487. if not is_plain_object(item):
  488. continue
  489. line = "#%s %s" % (item.get("id", "?"), str_text(item.get("title")))
  490. if str_text(item.get("status")):
  491. line += " " + str_text(item.get("status"))
  492. lines.append(line)
  493. return "\n".join(lines)
  494. def tailored_result_text(tool, extras):
  495. """PORT of tailoredResultBody -> the rendered text, or None for
  496. the generic JSON view."""
  497. if str_text(extras.get("content")) or isinstance(extras.get("total_lines"), int):
  498. meta = []
  499. if str_text(extras.get("path")):
  500. meta.append(str_text(extras.get("path")))
  501. if isinstance(extras.get("line_start"), int) \
  502. and isinstance(extras.get("total_lines"), int):
  503. end = extras.get("line_end")
  504. if not isinstance(end, int):
  505. end = extras["total_lines"]
  506. meta.append("lines %d-%d of %d"
  507. % (extras["line_start"], end, extras["total_lines"]))
  508. if isinstance(extras.get("bytes"), int):
  509. meta.append(fmt_bytes(extras["bytes"]))
  510. if extras.get("truncated"):
  511. meta.append("truncated")
  512. parts = [" \u00b7 ".join(meta)]
  513. if str_text(extras.get("content")):
  514. parts.append(str_text(extras["content"]))
  515. return "\n".join(parts)
  516. if tool == "replace_in_file" and isinstance(extras.get("replacements"), int):
  517. count = extras["replacements"]
  518. written = extras.get("bytes_written") \
  519. if isinstance(extras.get("bytes_written"), int) else 0
  520. return "%d replacement%s in %s \u00b7 %s" % (
  521. count, "" if count == 1 else "s",
  522. str_text(extras.get("path")), fmt_bytes(written))
  523. if tool == "write_file" and isinstance(extras.get("bytes"), int):
  524. return "wrote %s \u00b7 %s" % (str_text(extras.get("path")),
  525. fmt_bytes(extras["bytes"]))
  526. if tool == "overwrite_file" and isinstance(extras.get("bytes_written"), int):
  527. text = "rewrote %s \u00b7 %s" % (str_text(extras.get("path")),
  528. fmt_bytes(extras["bytes_written"]))
  529. if isinstance(extras.get("previous_bytes"), int):
  530. text += " (was %s)" % fmt_bytes(extras["previous_bytes"])
  531. return text
  532. if tool == "create_task" and isinstance(extras.get("task_id"), int):
  533. text = "created task #%d" % extras["task_id"]
  534. if str_text(extras.get("status")):
  535. text += " \u00b7 " + str_text(extras.get("status"))
  536. return text
  537. if tool == "get_task" and "id" in extras:
  538. return task_list_text([extras])
  539. for key in ("tasks", "goals"):
  540. if isinstance(extras.get(key), list):
  541. return task_list_text(extras[key])
  542. keys = list(extras)
  543. all_true = len(keys) > 0 and all(extras[key] is True for key in keys)
  544. all_scalars = 0 < len(keys) <= 4 and all(
  545. extras[key] is None or not isinstance(extras[key], (dict, list))
  546. for key in keys)
  547. if all_true:
  548. return "ok"
  549. if all_scalars:
  550. return " \u00b7 ".join("%s: %s" % (key, extras[key]) for key in keys)
  551. return None
  552. def args_without(args, skip):
  553. """PORT of argsWithout: every member except `skip`, pretty-
  554. printed; '' when nothing is left."""
  555. rest = dict((key, value) for key, value in args.items() if key != skip)
  556. return json.dumps(rest, indent=2) if rest else ""
  557. def tool_call_render(evt):
  558. """PORT of toolCallBody -> the rendered blocks as (kind, text)
  559. pairs: ('head', line) for a command-styled head, ('pre', text)
  560. for plain pre lines, ('para', text) for prose, ('fold', label)
  561. for collapsed payloads, ('diff', '- old') / ('diff', '+ new')
  562. for the replace_in_file diff. Bespoke bodies come from
  563. tailored_blocks; None falls back to the generic view."""
  564. payload = evt.get("payload") or {}
  565. tool = str_text(payload.get("tool")) or "tool"
  566. parsed = parse_maybe_json(payload.get("args"))
  567. args = parsed if is_plain_object(parsed) else None
  568. if args is not None:
  569. blocks = tailored_blocks(tool, args)
  570. if blocks is not None:
  571. return blocks
  572. blocks = [("head", tool)]
  573. if args is not None:
  574. rest = args_without(args, "command")
  575. if rest:
  576. blocks.append(("pre", rest))
  577. elif str_text(payload.get("args")):
  578. blocks.append(("pre", payload["args"]))
  579. elif payload.get("args") is not None and not isinstance(payload.get("args"), str):
  580. blocks.append(("pre", json.dumps(payload["args"], indent=2)))
  581. return blocks
  582. def fmt_int(n):
  583. """PORT of fmtInt: thousands separators without locale."""
  584. digits = str(abs(int(round(n))))
  585. out = ""
  586. for i, char in enumerate(digits):
  587. if i > 0 and (len(digits) - i) % 3 == 0:
  588. out += ","
  589. out += char
  590. return ("-" if n < 0 else "") + out
  591. def usage_line(payload):
  592. """PORT of eventNode's usage branch -> the one-line text. The
  593. daemon may report either token count alone."""
  594. bits = []
  595. if str_text(payload.get("model")):
  596. bits.append(payload["model"])
  597. in_tok = "%s in" % fmt_int(payload["prompt_tokens"]) \
  598. if isinstance(payload.get("prompt_tokens"), int) else ""
  599. out_tok = "%s out" % fmt_int(payload["completion_tokens"]) \
  600. if isinstance(payload.get("completion_tokens"), int) else ""
  601. if in_tok or out_tok:
  602. bits.append(in_tok + (" / " if in_tok and out_tok else "") + out_tok + " tok")
  603. if isinstance(payload.get("cached_tokens"), int):
  604. bits.append("%s cached" % fmt_int(payload["cached_tokens"]))
  605. if isinstance(payload.get("elapsed_ms"), int):
  606. bits.append(fmt_duration(payload["elapsed_ms"]))
  607. return " \u00b7 ".join(bits) if bits else "unreported"
  608. def state_change_line(payload):
  609. """PORT of eventNode's state_change branch."""
  610. from_status = str_text(payload.get("from"))
  611. to_status = str_text(payload.get("to"))
  612. if from_status and to_status:
  613. return from_status + " \u2192 " + to_status
  614. return str_text(payload.get("text")) or json.dumps(payload)
  615. DIFF_CONTEXT = 2
  616. DIFF_MAX_LINES = 400
  617. def _push_side(rows, lines, begin, end, marker):
  618. """PORT of pushSide."""
  619. count = end - begin
  620. half = DIFF_MAX_LINES // 2
  621. if count <= DIFF_MAX_LINES:
  622. for i in range(begin, end):
  623. rows.append([marker, lines[i]])
  624. return
  625. for j in range(begin, begin + half):
  626. rows.append([marker, lines[j]])
  627. rows.append([marker, "... %d more lines ..." % (count - half * 2)])
  628. for k in range(end - half, end):
  629. rows.append([marker, lines[k]])
  630. def diff_rows(old_text, new_text):
  631. """PORT of diffRows: common head/tail become clamped context,
  632. the differing middle renders as -old/+new."""
  633. old_lines = old_text.split("\n")
  634. new_lines = new_text.split("\n")
  635. start = 0
  636. while start < len(old_lines) and start < len(new_lines) \
  637. and old_lines[start] == new_lines[start]:
  638. start += 1
  639. end_old, end_new = len(old_lines), len(new_lines)
  640. while end_old > start and end_new > start \
  641. and old_lines[end_old - 1] == new_lines[end_new - 1]:
  642. end_old -= 1
  643. end_new -= 1
  644. rows = []
  645. has_middle = end_old > start or end_new > start
  646. if has_middle:
  647. for i in range(max(0, start - DIFF_CONTEXT), start):
  648. rows.append([" ", old_lines[i]])
  649. _push_side(rows, old_lines, start, end_old, "-")
  650. _push_side(rows, new_lines, start, end_new, "+")
  651. for i in range(end_old, min(len(old_lines), end_old + DIFF_CONTEXT)):
  652. rows.append([" ", old_lines[i]])
  653. return rows
  654. def tailored_blocks(tool, args):
  655. """PORT of tailoredCallBody -> the bespoke blocks, or None to
  656. fall back to the generic JSON view (fields missing - e.g. a
  657. truncated args string that clamped mid-JSON)."""
  658. path = str_text(args.get("path"))
  659. command = str_text(args.get("command"))
  660. question = str_text(args.get("question"))
  661. bits = []
  662. def head(text, more=None):
  663. block = ("head", text)
  664. if more:
  665. block = ("head", text + " \u00b7 " + " \u00b7 ".join(more))
  666. return block
  667. if tool == "run_command":
  668. if not command:
  669. return None
  670. if isinstance(args.get("timeout_ms"), int):
  671. bits.append("timeout %ds" % round(args["timeout_ms"] / 1000))
  672. return [head("$ " + command, bits)]
  673. if tool == "read_file":
  674. if not path:
  675. return None
  676. if isinstance(args.get("offset"), int) and args["offset"] > 1:
  677. bits.append("from line %d" % args["offset"])
  678. if isinstance(args.get("limit"), int):
  679. bits.append("%d lines" % args["limit"])
  680. return [head("read_file " + path, bits)]
  681. if tool in ("write_file", "overwrite_file"):
  682. content = str_text(args.get("content"))
  683. if not path or not content:
  684. return None
  685. return [head(tool + " " + path, [fmt_bytes(len(content))]),
  686. ("fold", "content \u00b7 " + fmt_bytes(len(content)))]
  687. if tool == "replace_in_file":
  688. old = str_text(args.get("old"))
  689. if not path or not old:
  690. return None
  691. if isinstance(args.get("expected_count"), int):
  692. bits.append("expect %d" % args["expected_count"])
  693. blocks = [head("replace_in_file " + path, bits)]
  694. rows = diff_rows(old, str_text(args.get("new")))
  695. if rows:
  696. blocks.extend(("diff", marker + " " + text) for marker, text in rows)
  697. return blocks
  698. if tool in ("enqueue_task", "delete_task", "get_task"):
  699. if not isinstance(args.get("task_id"), int):
  700. return None
  701. return [head(tool + " #" + str(args["task_id"]))]
  702. if tool in ("update_progress", "add_comment", "save_note"):
  703. text = str_text(args.get("text")) or str_text(args.get("body"))
  704. if not text:
  705. return None
  706. if tool == "save_note" and str_text(args.get("project")):
  707. bits.append(str_text(args.get("project")))
  708. return [head(tool, bits), ("para", text)]
  709. if tool == "ask_question":
  710. if not question:
  711. return None
  712. blocks = [head("ask_question"), ("para", "Q: " + question)]
  713. if isinstance(args.get("options"), list) and args["options"]:
  714. blocks.append(("options", [str(o) for o in args["options"]]))
  715. return blocks
  716. return None
  717. def command_output_render(evt):
  718. """PORT of eventNode's command_output branch ->
  719. (command_prefix, output_text)."""
  720. payload = evt.get("payload") or {}
  721. command = str_text(payload.get("command"))
  722. text = payload.get("text") or payload.get("chunk") or ""
  723. return ("$ " + command if command else ""), text
  724. # --- Fixtures: copied from the live ledger (web-db.sqlite, events
  725. # table) and the test fake's object-shaped pushes - the real wire
  726. # shapes, inner JSON spelled out as the daemon serialises it. ---
  727. # The daemon's inner JSON, built with json.dumps so the escaping
  728. # is exactly what the wire carries (a JSON string holding JSON).
  729. inner_call = json.dumps({"command": "cd /workspace && ls"})
  730. inner_progress = json.dumps(
  731. {"text": "Root-caused the SSE listener; next: the payload parse"})
  732. inner_enqueue = json.dumps({"task_id": 3})
  733. inner_result = json.dumps(
  734. {"ok": True, "exit_code": 0,
  735. "stdout": "find /workspace/task-1 -maxdepth 2",
  736. "stderr": "", "duration_ms": 11,
  737. "bytes_out": 6042, "bytes_err": 0, "truncated": True})
  738. inner_error = json.dumps(
  739. {"ok": False,
  740. "error": "suspend refused: 3 draft task(s) were never enqueued"})
  741. inner_empty = json.dumps({"ok": True, "exit_code": 0,
  742. "stdout": "", "stderr": ""})
  743. FIXTURE_RUN_COMMAND_CALL = json.loads(
  744. '{"turn": 52, "tool": "run_command", "args": ' + json.dumps(inner_call) + '}')
  745. FIXTURE_UPDATE_PROGRESS_CALL = json.loads(
  746. '{"turn": 6, "tool": "update_progress", "args": '
  747. + json.dumps(inner_progress) + '}')
  748. FIXTURE_ENQUEUE_CALL = json.loads(
  749. '{"turn": 5, "tool": "enqueue_task", "args": '
  750. + json.dumps(inner_enqueue) + '}')
  751. FIXTURE_RUN_COMMAND_RESULT = json.loads(
  752. '{"tool": "run_command", "result": ' + json.dumps(inner_result)
  753. + ', "turn": 52}')
  754. FIXTURE_ERROR_RESULT = json.loads(
  755. '{"tool": "suspend", "result": ' + json.dumps(inner_error) + '}')
  756. FIXTURE_EMPTY_RESULT = json.loads(
  757. '{"tool": "run_command", "result": ' + json.dumps(inner_empty) + '}')
  758. # Not valid JSON: the live daemon emitted result strings that are
  759. # truncated raw output (72 rows in the production ledger).
  760. FIXTURE_NOT_JSON_RESULT = {
  761. "tool": "run_command",
  762. "result": '{"ok":true,"exit_code":0,"stdout":"=== Spry ===\n'
  763. 'MANIFEST.usm README.md meson.build',
  764. }
  765. # command_output: the harness fake's shape; `command` is a member.
  766. FIXTURE_COMMAND_OUTPUT = {"command": "meson test -C builddir",
  767. "text": "nobody:/task-1$ done\r\n"}
  768. # The harness fake's legacy object-shaped payloads (plan 17's own
  769. # tests push these): args/result as real objects.
  770. FIXTURE_OBJECT_CALL = {"turn": 1, "tool": "run_command",
  771. "args": {"command": "echo hello"}}
  772. FIXTURE_OBJECT_RESULT = {"turn": 1, "tool": "run_command",
  773. "stdout": "hello\n", "exit_code": 0}
  774. # Tailored-rendering fixtures (plan 18): the file tools' arg shapes
  775. # straight off the daemon's tool schemas.
  776. FIXTURE_REPLACE_CALL = {"turn": 40, "tool": "replace_in_file", "args": {
  777. "path": "src/pages/app.css",
  778. "old": ".event-turn {\n border-left: 3px solid #ddf4ff;\n}",
  779. "new": ".event-turn {\n border-left: 3px solid #ddf4ff;\n color: var(--ink-muted);\n}",
  780. "expected_count": 1}}
  781. FIXTURE_WRITE_CALL = {"turn": 41, "tool": "write_file", "args": {
  782. "path": "notes.md", "content": "# Notes\n- first\n- second"}}
  783. # Args clamped mid-JSON by the daemon's display clamp: parsing
  784. # fails, so the bespoke renderer must step aside and the generic
  785. # view shows the raw text.
  786. FIXTURE_TRUNCATED_ARGS = {"turn": 42, "tool": "write_file", "args":
  787. '{"path":"big.bin","content":"AAA'}
  788. class PayloadParserTests(unittest.TestCase):
  789. def test_string_args_decode_to_an_object(self):
  790. parsed = parse_maybe_json(FIXTURE_RUN_COMMAND_CALL["args"])
  791. self.assertEqual(parsed, {"command": "cd /workspace && ls"})
  792. def test_non_json_string_answers_none(self):
  793. self.assertIsNone(parse_maybe_json(
  794. FIXTURE_NOT_JSON_RESULT["result"]))
  795. def test_objects_pass_through(self):
  796. self.assertEqual(parse_maybe_json({"command": "ls"}), {"command": "ls"})
  797. self.assertEqual(parse_maybe_json(None), None)
  798. class ToolCallRenderTests(unittest.TestCase):
  799. """The command the agent ran must surface in EVERY render path,
  800. and each known tool renders through its tailored body."""
  801. def evt(self, payload):
  802. return {"kind": "tool_call", "payload": payload}
  803. def test_run_command_call_heads_with_the_dollar(self):
  804. blocks = tool_call_render(self.evt(FIXTURE_RUN_COMMAND_CALL))
  805. self.assertEqual(blocks[0], ("head", "$ cd /workspace && ls"))
  806. def test_run_command_timeout_rides_the_head(self):
  807. blocks = tool_call_render(self.evt({"tool": "run_command", "args":
  808. {"command": "make", "timeout_ms": 900000}}))
  809. self.assertEqual(blocks[0],
  810. ("head", "$ make \u00b7 timeout 900s"))
  811. def test_update_progress_call_renders_prose_not_json(self):
  812. """The old renderer dumped {"text": ...} as JSON; the
  813. tailored body renders the text itself."""
  814. blocks = tool_call_render(self.evt(FIXTURE_UPDATE_PROGRESS_CALL))
  815. self.assertEqual(blocks[0], ("head", "update_progress"))
  816. self.assertEqual(blocks[1],
  817. ("para", "Root-caused the SSE listener; next: the payload parse"))
  818. self.assertNotIn('"text"', json.dumps(blocks))
  819. def test_enqueue_call_renders_the_id(self):
  820. blocks = tool_call_render(self.evt(FIXTURE_ENQUEUE_CALL))
  821. self.assertEqual(blocks, [("head", "enqueue_task #3")])
  822. def test_replace_in_file_renders_a_diff(self):
  823. blocks = tool_call_render(self.evt(FIXTURE_REPLACE_CALL))
  824. self.assertEqual(blocks[0],
  825. ("head", "replace_in_file src/pages/app.css \u00b7 expect 1"))
  826. diff_texts = [text for kind, text in blocks if kind == "diff"]
  827. joined = " ".join(diff_texts)
  828. self.assertIn(" .event-turn {", joined)
  829. # The untouched border line is context; only the added color
  830. # line is an addition - no phantom removals.
  831. self.assertIn(" border-left: 3px solid #ddf4ff;", joined)
  832. self.assertIn("+ color: var(--ink-muted);", joined)
  833. self.assertIn(" }", joined)
  834. self.assertFalse([t for t in diff_texts if t.startswith("- ")],
  835. "an unchanged line must never render as a removal")
  836. def test_write_file_folds_its_content(self):
  837. blocks = tool_call_render(self.evt(FIXTURE_WRITE_CALL))
  838. self.assertEqual(blocks[0], ("head", "write_file notes.md \u00b7 24 B"))
  839. self.assertEqual(blocks[1], ("fold", "content \u00b7 24 B"))
  840. def test_truncated_args_fall_back_to_the_raw_view(self):
  841. blocks = tool_call_render(self.evt(FIXTURE_TRUNCATED_ARGS))
  842. self.assertEqual(blocks[0], ("head", "write_file"))
  843. self.assertEqual(blocks[1][0], "pre")
  844. self.assertIn('"path":"big.bin"', blocks[1][1])
  845. def test_unknown_tool_falls_back_to_json_args(self):
  846. blocks = tool_call_render(self.evt(
  847. {"tool": "brand_new_tool", "args": {"deep": {"a": 1}}}))
  848. self.assertEqual(blocks[0], ("head", "brand_new_tool"))
  849. self.assertIn('"deep"', blocks[1][1])
  850. def test_object_shaped_call_still_works(self):
  851. blocks = tool_call_render(self.evt(FIXTURE_OBJECT_CALL))
  852. self.assertEqual(blocks, [("head", "$ echo hello")])
  853. def test_non_json_args_render_raw(self):
  854. blocks = tool_call_render(self.evt(
  855. {"tool": "run_command", "args": "not json at all"}))
  856. self.assertEqual(blocks,
  857. [("head", "run_command"), ("pre", "not json at all")])
  858. def test_no_args_at_all_renders_the_tool_name(self):
  859. blocks = tool_call_render(self.evt({"tool": "list_tasks"}))
  860. self.assertEqual(blocks, [("head", "list_tasks")])
  861. def test_bespoke_missing_fields_step_aside(self):
  862. """A replace_in_file without its old string (clamped args
  863. that still parse) falls back rather than lying."""
  864. blocks = tool_call_render(self.evt(
  865. {"tool": "replace_in_file", "args": {"path": "x.c"}}))
  866. self.assertEqual(blocks[0], ("head", "replace_in_file"))
  867. self.assertEqual(blocks[1][0], "pre")
  868. class DiffRowTests(unittest.TestCase):
  869. """The replace_in_file diff: context clamping and honest
  870. replacement semantics."""
  871. def test_single_line_swap(self):
  872. rows = diff_rows("alpha\nbeta\ngamma", "alpha\nBETA\ngamma")
  873. self.assertEqual(rows, [[" ", "alpha"], ["-", "beta"],
  874. ["+", "BETA"], [" ", "gamma"]])
  875. def test_context_is_clamped_to_two_lines_per_side(self):
  876. old = "\n".join(["ctx"] * 10 + ["old-line"] + ["ctx"] * 10)
  877. new = "\n".join(["ctx"] * 10 + ["new-line"] + ["ctx"] * 10)
  878. rows = diff_rows(old, new)
  879. context = [text for marker, text in rows if marker == " "]
  880. self.assertEqual(context, ["ctx"] * 4)
  881. def test_whole_file_rewrite_shows_no_context(self):
  882. rows = diff_rows("a\nb\nc", "x\ny\nz")
  883. self.assertEqual([m for m, _ in rows], ["-", "-", "-", "+", "+", "+"])
  884. def test_deletion_only_keeps_its_context(self):
  885. rows = diff_rows("keep\ndrop\nkeep", "keep\nkeep")
  886. self.assertEqual(rows, [[" ", "keep"], ["-", "drop"], [" ", "keep"]])
  887. def test_empty_new_text(self):
  888. rows = diff_rows("line", "")
  889. self.assertEqual(rows, [["-", "line"], ["+", ""]])
  890. def test_oversized_side_keeps_head_and_tail(self):
  891. old = "\n".join("line-%04d" % i for i in range(1000))
  892. rows = diff_rows(old, "changed")
  893. dels = [text for marker, text in rows if marker == "-"]
  894. self.assertEqual(len(dels), 401)
  895. self.assertIn("more lines", dels[200])
  896. self.assertEqual(dels[0], "line-0000")
  897. self.assertEqual(dels[-1], "line-0999")
  898. def test_identical_text_renders_nothing(self):
  899. self.assertEqual(diff_rows("same\nsame", "same\nsame"), [])
  900. class UsageLineTests(unittest.TestCase):
  901. def test_full_payload_is_one_line(self):
  902. line = usage_line({"model": "glm-4.7", "prompt_tokens": 45200000,
  903. "completion_tokens": 1100000, "cached_tokens": 4500,
  904. "elapsed_ms": 3200})
  905. self.assertEqual(line,
  906. "glm-4.7 \u00b7 45,200,000 in / 1,100,000 out tok "
  907. "\u00b7 4,500 cached \u00b7 3.2 s")
  908. def test_unreported_when_no_numbers(self):
  909. self.assertEqual(usage_line({}), "unreported")
  910. def test_partial_payload_skips_missing_members(self):
  911. line = usage_line({"completion_tokens": 5, "elapsed_ms": 40})
  912. self.assertEqual(line, "5 out tok \u00b7 40 ms")
  913. class StateChangeLineTests(unittest.TestCase):
  914. def test_from_to_arrow(self):
  915. self.assertEqual(
  916. state_change_line({"from": "working", "to": "blocked",
  917. "text": "Status \u2192 blocked"}),
  918. "working \u2192 blocked")
  919. def test_text_fallback(self):
  920. self.assertEqual(
  921. state_change_line({"text": "Goal created (branch x)"}),
  922. "Goal created (branch x)")
  923. def test_json_fallback(self):
  924. self.assertEqual(state_change_line({}), "{}")
  925. class ToolResultRenderTests(unittest.TestCase):
  926. def evt(self, payload):
  927. return {"kind": "tool_result", "payload": payload}
  928. def test_summary_comes_from_the_envelope(self):
  929. line = result_summary(self.evt(FIXTURE_RUN_COMMAND_RESULT))
  930. self.assertEqual(line,
  931. "result (exit 0, 5.9 KiB, truncated, 11 ms, turn 52)")
  932. def test_summary_marks_failed_envelopes(self):
  933. line = result_summary(self.evt(
  934. {"tool": "run_command", "result": '{"ok":false,"error":"x"}'}))
  935. self.assertEqual(line, "result (failed)")
  936. def test_body_shows_the_envelopes_stdout(self):
  937. out, err, note, extras, no_output = result_output(
  938. self.evt(FIXTURE_RUN_COMMAND_RESULT))
  939. self.assertEqual(out, "find /workspace/task-1 -maxdepth 2")
  940. self.assertEqual(err, "")
  941. self.assertFalse(no_output)
  942. def test_non_json_result_renders_as_output_text(self):
  943. out, err, note, extras, no_output = result_output(
  944. self.evt(FIXTURE_NOT_JSON_RESULT))
  945. self.assertIn("=== Spry ===", out)
  946. self.assertFalse(no_output,
  947. "raw output must never be called (no output)")
  948. def test_error_envelope_is_not_no_output(self):
  949. out, err, note, extras, no_output = result_output(
  950. self.evt(FIXTURE_ERROR_RESULT))
  951. self.assertEqual((out, err), ("", ""))
  952. self.assertIn("suspend refused", note)
  953. self.assertFalse(no_output,
  954. "an error member means the result said something")
  955. def test_genuinely_empty_result_says_no_output(self):
  956. out, err, note, extras, no_output = result_output(self.evt(FIXTURE_EMPTY_RESULT))
  957. self.assertEqual((out, err, note, extras), ("", "", "", ""))
  958. self.assertTrue(no_output)
  959. def test_object_shaped_result_still_works(self):
  960. line = result_summary(self.evt(FIXTURE_OBJECT_RESULT))
  961. self.assertEqual(line, "result (exit 0, 6 B, turn 1)")
  962. out, err, note, extras, no_output = result_output(self.evt(FIXTURE_OBJECT_RESULT))
  963. self.assertEqual(out, "hello\n")
  964. def test_tool_answer_envelope_is_rendered_not_swallowed(self):
  965. """The live ledger's update_progress/create_task/finish
  966. results carry {"recorded":true} / {"ok":true,"task_id":4}
  967. / {"accepted":true} with empty streams: that IS the tool's
  968. answer and must render, not "(no output)"."""
  969. for inner in ('{"recorded":true}',
  970. '{"ok":true,"task_id":4,"status":"draft"}',
  971. '{"accepted":true}',
  972. '{"suspended":true}',
  973. '{"ok":true,"status":"pending"}'):
  974. out, err, note, extras, no_output = result_output(self.evt(
  975. {"tool": "update_progress", "result": inner}))
  976. self.assertFalse(no_output, inner)
  977. self.assertEqual((out, err, note), ("", "", ""))
  978. self.assertTrue(extras, inner)
  979. def test_list_tasks_answer_renders_as_a_list(self):
  980. inner = json.dumps({"ok": True, "tasks": [
  981. {"id": 6, "title": "UX notes", "status": "queued"},
  982. {"id": 5, "title": "Event log parse", "status": "working"}]})
  983. out, err, note, extras, no_output = result_output(self.evt(
  984. {"tool": "list_tasks", "result": inner}))
  985. self.assertFalse(no_output)
  986. self.assertIn("UX notes", extras)
  987. self.assertIn("Event log parse", extras)
  988. self.assertIn("#6", extras)
  989. self.assertNotIn('"tasks"', extras,
  990. "a task list renders as rows, not a JSON dump")
  991. def test_replace_in_file_result_counts_the_replacements(self):
  992. inner = json.dumps({"ok": True, "path": "src/app.css",
  993. "replacements": 2, "bytes_written": 2048})
  994. out, err, note, extras, no_output = result_output(self.evt(
  995. {"tool": "replace_in_file", "result": inner}))
  996. self.assertEqual(extras, "2 replacements in src/app.css \u00b7 2.0 KiB")
  997. def test_read_file_result_renders_the_window(self):
  998. inner = json.dumps({"ok": True, "path": "src/main.vala",
  999. "total_lines": 540, "line_start": 100,
  1000. "line_end": 160, "bytes": 4200,
  1001. "truncated": False, "content": "int main() {"})
  1002. out, err, note, extras, no_output = result_output(self.evt(
  1003. {"tool": "read_file", "result": inner}))
  1004. self.assertIn("src/main.vala \u00b7 lines 100-160 of 540 \u00b7 4.1 KiB", extras)
  1005. self.assertIn("int main() {", extras)
  1006. def test_write_file_result_states_the_write(self):
  1007. out, err, note, extras, no_output = result_output(self.evt(
  1008. {"tool": "write_file",
  1009. "result": '{"ok":true,"path":"notes.md","bytes":24}'}))
  1010. self.assertEqual(extras, "wrote notes.md \u00b7 24 B")
  1011. def test_create_task_result_names_the_task(self):
  1012. out, err, note, extras, no_output = result_output(self.evt(
  1013. {"tool": "create_task",
  1014. "result": '{"ok":true,"task_id":4,"status":"draft"}'}))
  1015. self.assertEqual(extras, "created task #4 \u00b7 draft")
  1016. def test_pure_acknowledgement_is_an_ok_line(self):
  1017. out, err, note, extras, no_output = result_output(self.evt(
  1018. {"tool": "update_progress", "result": '{"ok":true,"recorded":true}'}))
  1019. self.assertEqual(extras, "ok")
  1020. def test_run_command_with_empty_streams_is_still_no_output(self):
  1021. """Only command plumbing present: the run genuinely said
  1022. nothing - keep the honest "(no output)"."""
  1023. out, err, note, extras, no_output = result_output(self.evt(
  1024. {"tool": "run_command",
  1025. "result": '{"ok":true,"exit_code":0,"stdout":"",'
  1026. '"stderr":"","duration_ms":5,"bytes_out":0,'
  1027. '"bytes_err":0,"truncated":false}'}))
  1028. self.assertTrue(no_output)
  1029. self.assertEqual(extras, "")
  1030. class CommandOutputRenderTests(unittest.TestCase):
  1031. def test_command_is_prefixed_as_a_shell_line(self):
  1032. command, text = command_output_render(
  1033. {"kind": "command_output", "payload": FIXTURE_COMMAND_OUTPUT})
  1034. self.assertEqual(command, "$ meson test -C builddir")
  1035. self.assertEqual(text, "nobody:/task-1$ done\r\n")
  1036. def test_text_only_chunk_keeps_the_old_render(self):
  1037. command, text = command_output_render(
  1038. {"kind": "command_output", "payload": {"text": "hello\r\n"}})
  1039. self.assertEqual(command, "")
  1040. self.assertEqual(text, "hello\r\n")
  1041. class SearchHaystackTests(unittest.TestCase):
  1042. """A search for text inside the STRING-encoded args/result must
  1043. still find the event: the haystack appends the raw strings."""
  1044. def test_search_matches_through_the_string_encoding(self):
  1045. payload = FIXTURE_RUN_COMMAND_CALL
  1046. haystack = "tool_call daemon " + json.dumps(payload) + " " \
  1047. + str_text(payload.get("args")) + " " \
  1048. + str_text(payload.get("result"))
  1049. self.assertIn("cd /workspace && ls", haystack)
  1050. class YeehawFilterTests(unittest.TestCase):
  1051. """The celebration must ride the comments filter (goal 9 task 4b):
  1052. a human scanning the conversation sees the yeehaw, and the
  1053. comments toggle hides it like any other chatter."""
  1054. def test_yeehaw_maps_to_comments(self):
  1055. self.assertEqual(filter_of("yeehaw"), "comments")
  1056. def test_comment_kinds_unchanged(self):
  1057. for kind in ("comment", "answer", "verdict"):
  1058. self.assertEqual(filter_of(kind), "comments")
  1059. def test_other_kinds_unchanged(self):
  1060. self.assertEqual(filter_of("tool_call"), "commands")
  1061. self.assertEqual(filter_of("tool_result"), "results")
  1062. self.assertEqual(filter_of("command_output"), "results")
  1063. self.assertEqual(filter_of("usage"), "usage")
  1064. self.assertEqual(filter_of("lifecycle"), "transitions")
  1065. class YeehawRenderTests(unittest.TestCase):
  1066. """The yeehaw branch: the message in the bold .yeehaw-message span
  1067. (the festive palette), never a JSON payload dump."""
  1068. def test_message_renders_in_the_span(self):
  1069. span, message = yeehaw_render(
  1070. {"kind": "yeehaw", "payload": {"message": "Loved every line"}})
  1071. self.assertEqual(span, "yeehaw-message")
  1072. self.assertEqual(message, "Loved every line")
  1073. def test_missing_message_is_blank_not_garbage(self):
  1074. span, message = yeehaw_render({"kind": "yeehaw", "payload": {}})
  1075. self.assertEqual(message, "")
  1076. def test_non_string_message_is_blank(self):
  1077. span, message = yeehaw_render(
  1078. {"kind": "yeehaw", "payload": {"message": 42}})
  1079. self.assertEqual(message, "")
  1080. class RendererSourceTests(unittest.TestCase):
  1081. """The shipped script itself (no JS engine in this container, so
  1082. the render decisions are pinned by the ports above plus these
  1083. shape checks on the served source)."""
  1084. def setUp(self):
  1085. self.body = script_body()
  1086. def test_parse_maybe_json_is_defined_and_used(self):
  1087. self.assertIn("function parseMaybeJson(value) {", self.body)
  1088. self.assertGreaterEqual(self.body.count("parseMaybeJson("), 4)
  1089. def test_no_innerhtml_anywhere(self):
  1090. self.assertNotIn(".innerHTML", self.body)
  1091. def test_command_output_prefixes_the_dollar(self):
  1092. self.assertIn("'$ ' + p.command", self.body)
  1093. def test_tool_call_line_uses_parsed_args(self):
  1094. self.assertIn("args.command", self.body)
  1095. self.assertIn("toolCallBody", self.body)
  1096. def test_result_reads_parsed_envelope(self):
  1097. self.assertIn("resultEnvelope", self.body)
  1098. self.assertIn("bytes_out", self.body)
  1099. self.assertIn("duration_ms", self.body)
  1100. def test_yeehaw_lands_in_the_comments_bucket(self):
  1101. self.assertRegex(
  1102. self.body,
  1103. r"kind === 'comment' \|\| kind === 'answer' \|\| kind === 'verdict'[\s\S]*?"
  1104. r"kind === 'yeehaw'\) return 'comments'")
  1105. def test_yeehaw_renders_the_message_span(self):
  1106. self.assertIn("evt.kind === 'yeehaw'", self.body)
  1107. self.assertIn("'yeehaw-message'", self.body)
  1108. self.assertIn("strText(p.message)", self.body)
  1109. def test_tailored_renderers_present(self):
  1110. self.assertIn("function tailoredCallBody(tool, args) {", self.body)
  1111. self.assertIn("function diffRows(oldText, newText) {", self.body)
  1112. self.assertIn("'event-diff'", self.body)
  1113. self.assertIn("tailoredCallBody(tool, args)", self.body)
  1114. if __name__ == "__main__":
  1115. unittest.main(verbosity=2)