test_task_log_js.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  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 the
  5. page (src/pages/task_log.html) and its client JS resource
  6. (src/pages/task_log.js, loaded via pstm-res-src) two ways:
  7. 1. Statically - the script must be ASCII-only (the page compiler
  8. HTML-escapes inline script bodies, so any non-ASCII literal is
  9. re-served as literal entity text like "·" after the
  10. browser's one decode pass; the resource keeps the discipline),
  11. must wire the SSE stream through `onmessage` (the server sends
  12. id:/data: frames with no `event:` name, so named listeners can
  13. never fire), must not listen for an 'append' event name, and its
  14. delimiter structure must balance after strings and comments are
  15. stripped.
  16. 2. Behaviourally - the ingest / render-order / scroll-stick /
  17. load-more logic is ported verbatim below as pure python functions
  18. and unit-tested: oldest-first chronology, id dedupe, the 48px
  19. bottom-stick rule, prepend-mode scroll anchoring, and the
  20. newest-first-page reversal with the `more` -> exhausted flag.
  21. Runnable standalone: python3 test/test_task_log_js.py
  22. """
  23. import json
  24. import os
  25. import re
  26. import unittest
  27. PAGE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  28. os.pardir, "src", "pages", "task_log.html")
  29. SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  30. os.pardir, "src", "pages", "task_log.js")
  31. def script_body():
  32. # The client JS lives in its own resource file; the page markup
  33. # carries no inline script.
  34. with open(SCRIPT, encoding="utf-8") as handle:
  35. return handle.read()
  36. # ---------------------------------------------------------------------------
  37. # Static checks
  38. # ---------------------------------------------------------------------------
  39. class ScriptSourceTests(unittest.TestCase):
  40. """What the served bytes must look like after compilation."""
  41. def setUp(self):
  42. self.body = script_body()
  43. def test_script_is_ascii_only(self):
  44. """Non-ASCII in a script body comes back as literal entity
  45. text ("·") because the compiler escapes script bodies
  46. and the browser decodes exactly once. ASCII (with \\uXXXX
  47. escapes for the characters we want) is immune."""
  48. offenders = [(index, hex(ord(char)))
  49. for index, char in enumerate(self.body) if ord(char) > 127]
  50. self.assertEqual(offenders, [])
  51. def test_page_loads_the_resource_and_carries_no_inline_script(self):
  52. with open(PAGE, encoding="utf-8") as handle:
  53. markup = handle.read()
  54. self.assertNotIn("<script>", markup,
  55. "the client JS lives in task_log.js, not inline")
  56. self.assertIn('pstm-res-src="task_log.js"', markup)
  57. def test_unicode_escapes_used_for_separators(self):
  58. """The separator characters must still render - as escapes,
  59. not as raw bytes and not as HTML entities."""
  60. for escape in ("\\u00b7", "\\u2026", "\\u2014"):
  61. self.assertIn(escape, self.body)
  62. self.assertNotIn("&middot;", self.body)
  63. self.assertNotIn("&mdash;", self.body)
  64. def test_stream_wired_through_onmessage(self):
  65. self.assertRegex(self.body, r"stream\.onmessage\s*=")
  66. self.assertNotIn("addEventListener('append'", self.body)
  67. self.assertNotIn('addEventListener("append"', self.body)
  68. def test_heartbeat_ping_is_skipped(self):
  69. self.assertRegex(self.body, r"message\.data\s*===\s*'ping'")
  70. def test_load_more_pages_before_oldest(self):
  71. self.assertRegex(self.body, r"/events\?before='\s*\+\s*\(state\.oldest")
  72. def test_page_is_reversed_before_ingest(self):
  73. self.assertIn("slice().reverse().forEach(ingest)", self.body)
  74. def test_exhausted_set_when_no_more(self):
  75. self.assertIn("state.exhausted = true", self.body)
  76. def test_more_button_rides_inside_the_feed(self):
  77. # The load-older control is the feed's FIRST row - it
  78. # scrolls away with the history instead of sitting above
  79. # the pane. Search the page markup only (the script's
  80. # comments also mention [data-log-feed]).
  81. with open(PAGE, encoding="utf-8") as handle:
  82. markup = handle.read().split("</script>", 1)[1]
  83. feed = markup.index("data-log-feed")
  84. more = markup.index("data-log-more", feed)
  85. close = markup.index("</div>", feed)
  86. self.assertLess(feed, more)
  87. self.assertLess(more, close,
  88. "the load-older control must live inside the feed container")
  89. self.assertLess(more, markup.index("<p", feed),
  90. "the load-older control must be the feed's first row")
  91. def test_delimiters_balance(self):
  92. """A cheap structural stand-in for a JS parser (none is
  93. installed here): after stripping comments and string literals
  94. every bracket must close."""
  95. body = self.body
  96. out = []
  97. i = 0
  98. mode = None # None | 'line' | 'block' | "'" | '"'
  99. while i < len(body):
  100. char = body[i]
  101. nxt = body[i + 1] if i + 1 < len(body) else ""
  102. if mode is None:
  103. if char == "/" and nxt == "/":
  104. mode = "line"
  105. i += 2
  106. continue
  107. if char == "/" and nxt == "*":
  108. mode = "block"
  109. i += 2
  110. continue
  111. if char in "'\"":
  112. mode = char
  113. i += 1
  114. continue
  115. out.append(char)
  116. elif mode == "line":
  117. if char == "\n":
  118. mode = None
  119. out.append("\n")
  120. elif mode == "block":
  121. if char == "*" and nxt == "/":
  122. mode = None
  123. i += 2
  124. continue
  125. else: # inside a string literal
  126. if char == "\\":
  127. i += 2
  128. continue
  129. if char == mode:
  130. mode = None
  131. i += 1
  132. self.assertEqual(mode, None, "unterminated comment or string literal")
  133. pairs = {")": "(", "]": "[", "}": "{"}
  134. stack = []
  135. for char in out:
  136. if char in "([{":
  137. stack.append(char)
  138. elif char in pairs:
  139. self.assertTrue(stack and stack[-1] == pairs[char],
  140. "unbalanced %r at depth %s" % (char, stack))
  141. stack.pop()
  142. self.assertEqual(stack, [], "unclosed delimiters %s" % stack)
  143. # ---------------------------------------------------------------------------
  144. # Port of the client logic (keep in step with task_log.html)
  145. # ---------------------------------------------------------------------------
  146. STICK_THRESHOLD = 48 # px that still counts as "reading the tail"
  147. PAGE_SIZE = 30
  148. class Feed(object):
  149. """Scroll-state stand-in for [data-log-feed]."""
  150. def __init__(self, scroll_height=0, client_height=600, scroll_top=0):
  151. self.scroll_height = scroll_height
  152. self.client_height = client_height
  153. self.scroll_top = scroll_top
  154. def at_bottom(feed):
  155. """PORT: a feed shorter than its viewport counts as at-bottom."""
  156. return feed.scroll_height - feed.scroll_top - feed.client_height \
  157. <= STICK_THRESHOLD
  158. class State(object):
  159. """PORT: the module-level `state` object."""
  160. def __init__(self):
  161. self.events = []
  162. self.oldest = 0
  163. self.exhausted = False
  164. self.loading = False
  165. self.seeded = False
  166. def ingest(state, evt):
  167. """PORT: keep state.events oldest-first (ascending id); skip ids
  168. already held (SSE replay after a reconnect resends a frame)."""
  169. i = 0
  170. while i < len(state.events) and state.events[i]["id"] < evt["id"]:
  171. i += 1
  172. if i < len(state.events) and state.events[i]["id"] == evt["id"]:
  173. return
  174. state.events.insert(i, evt)
  175. if evt["id"] < state.oldest or state.oldest == 0:
  176. state.oldest = evt["id"]
  177. def render(state, feed, mode=None, height_after=None):
  178. """PORT of render(mode): decide the post-render scroll position.
  179. height_after stands in for the DOM rebuild's new scrollHeight."""
  180. was_at_bottom = at_bottom(feed)
  181. height_before = feed.scroll_height
  182. scroll_top_before = feed.scroll_top
  183. if height_after is not None:
  184. feed.scroll_height = height_after
  185. if not state.seeded and len(state.events) > 0:
  186. state.seeded = True
  187. feed.scroll_top = feed.scroll_height # scrollToBottom()
  188. elif mode == "prepend":
  189. if was_at_bottom:
  190. feed.scroll_top = feed.scroll_height
  191. else:
  192. feed.scroll_top = scroll_top_before + (feed.scroll_height
  193. - height_before)
  194. elif was_at_bottom:
  195. feed.scroll_top = feed.scroll_height
  196. else:
  197. feed.scroll_top = scroll_top_before
  198. return feed.scroll_top
  199. def server_page(newest, oldest, more):
  200. """The endpoint's wire shape: newest-first within the page."""
  201. return {"events": [{"id": i} for i in range(newest, oldest - 1, -1)],
  202. "more": more}
  203. def load_more(state, feed, page, height_after):
  204. """PORT of loadMore's success path: reverse the newest-first page
  205. into chronological order, ingest it, set exhausted, render."""
  206. rows = page["events"]
  207. for evt in reversed(rows):
  208. ingest(state, evt)
  209. if not page["more"] or len(rows) == 0:
  210. state.exhausted = True
  211. return render(state, feed, mode="prepend", height_after=height_after)
  212. def on_stream_message(state, feed, data, height_after):
  213. """PORT of onStreamMessage: skip heartbeats, ingest one row."""
  214. if data == "ping":
  215. return feed.scroll_top
  216. ingest(state, {"id": int(data)})
  217. return render(state, feed, mode="append", height_after=height_after)
  218. # ---------------------------------------------------------------------------
  219. # Behaviour tests
  220. # ---------------------------------------------------------------------------
  221. def ids(state):
  222. return [evt["id"] for evt in state.events]
  223. class ChronologyTests(unittest.TestCase):
  224. def test_initial_window_renders_oldest_first(self):
  225. """The SSE replay / first JSON page arrives newest-first
  226. ([30..1]); the feed must render [1..30] - oldest at the top."""
  227. state = State()
  228. for evt in server_page(30, 1, True)["events"]:
  229. ingest(state, evt)
  230. self.assertEqual(ids(state), list(range(1, 31)))
  231. self.assertEqual(state.oldest, 1)
  232. def test_live_appends_land_in_order(self):
  233. state = State()
  234. for i in range(30, 0, -1):
  235. ingest(state, {"id": i})
  236. ingest(state, {"id": 31})
  237. ingest(state, {"id": 33})
  238. ingest(state, {"id": 32}) # out of order arrival
  239. self.assertEqual(ids(state)[-3:], [31, 32, 33])
  240. def test_duplicate_ids_are_dropped(self):
  241. state = State()
  242. ingest(state, {"id": 5})
  243. ingest(state, {"id": 5}) # EventSource reconnect replay
  244. self.assertEqual(ids(state), [5])
  245. class ScrollStickTests(unittest.TestCase):
  246. def test_first_render_with_rows_seeds_at_the_bottom(self):
  247. state = State()
  248. feed = Feed(scroll_height=0, client_height=600)
  249. for evt in server_page(30, 1, True)["events"]:
  250. ingest(state, evt)
  251. render(state, feed, height_after=3000)
  252. self.assertTrue(state.seeded)
  253. self.assertEqual(feed.scroll_top, 3000)
  254. def test_append_sticks_when_reading_the_tail(self):
  255. state = State()
  256. feed = Feed(scroll_height=3000, client_height=600)
  257. state.seeded = True
  258. feed.scroll_top = 2400 # exactly at the bottom
  259. self.assertTrue(at_bottom(feed))
  260. ingest(state, {"id": 31})
  261. render(state, feed, mode="append", height_after=3100)
  262. self.assertEqual(feed.scroll_top, 3100)
  263. def test_append_within_threshold_still_sticks(self):
  264. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2360)
  265. self.assertTrue(at_bottom(feed)) # 40px shy: close enough
  266. def test_just_past_threshold_is_not_the_tail(self):
  267. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2351)
  268. self.assertFalse(at_bottom(feed)) # 49px shy: reading history
  269. def test_scrolled_up_reader_is_never_yanked(self):
  270. state = State()
  271. feed = Feed(scroll_height=3000, client_height=600, scroll_top=500)
  272. state.seeded = True
  273. self.assertFalse(at_bottom(feed))
  274. ingest(state, {"id": 31})
  275. render(state, feed, mode="append", height_after=3100)
  276. self.assertEqual(feed.scroll_top, 500)
  277. def test_short_feed_counts_as_at_bottom(self):
  278. """A feed shorter than its viewport cannot be scrolled away
  279. from the newest row."""
  280. feed = Feed(scroll_height=100, client_height=600, scroll_top=0)
  281. self.assertTrue(at_bottom(feed))
  282. def test_heartbeat_does_not_touch_anything(self):
  283. state = State()
  284. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2400)
  285. state.seeded = True
  286. before = (list(ids(state)), feed.scroll_top)
  287. on_stream_message(state, feed, "ping", height_after=3100)
  288. self.assertEqual((list(ids(state)), feed.scroll_top), before)
  289. class LoadMoreTests(unittest.TestCase):
  290. def test_older_page_is_reversed_and_prepended(self):
  291. """before=<oldest>=1 returns [60..31] newest-first on the
  292. wire; the display must gain [31..60] above [1..30]."""
  293. state = State()
  294. feed = Feed(scroll_height=3000, client_height=600, scroll_top=500)
  295. for evt in server_page(30, 1, True)["events"]:
  296. ingest(state, evt)
  297. state.seeded = True
  298. render(state, feed, height_after=3000)
  299. feed.scroll_top = 500 # the reader scrolled up into history
  300. load_more(state, feed, server_page(60, 31, True), height_after=6000)
  301. self.assertEqual(ids(state), list(range(1, 61)))
  302. self.assertEqual(state.oldest, 1)
  303. self.assertFalse(state.exhausted)
  304. def test_prepend_keeps_the_viewport_anchored(self):
  305. """Content added above must not move the rows under the
  306. reader's cursor: scrollTop grows by the added height."""
  307. state = State()
  308. feed = Feed(scroll_height=3000, client_height=600, scroll_top=500)
  309. state.seeded = True
  310. self.assertFalse(at_bottom(feed))
  311. delta = 3000
  312. load_more(state, feed, server_page(60, 31, True),
  313. height_after=3000 + delta)
  314. self.assertEqual(feed.scroll_top, 500 + delta)
  315. def test_prepend_while_at_bottom_stays_at_bottom(self):
  316. state = State()
  317. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2400)
  318. state.seeded = True
  319. self.assertTrue(at_bottom(feed))
  320. load_more(state, feed, server_page(60, 31, True), height_after=6000)
  321. self.assertEqual(feed.scroll_top, 6000)
  322. def test_exhausted_when_more_is_false(self):
  323. state = State()
  324. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2400)
  325. state.seeded = True
  326. load_more(state, feed, server_page(60, 31, False), height_after=6000)
  327. self.assertTrue(state.exhausted)
  328. def test_empty_page_exhausts_too(self):
  329. """A defensive guard: a page with no rows means no older
  330. history, whatever the flag says."""
  331. state = State()
  332. feed = Feed(scroll_height=3000, client_height=600, scroll_top=2400)
  333. state.seeded = True
  334. ingest(state, {"id": 1})
  335. load_more(state, feed, {"events": [], "more": True}, height_after=3000)
  336. self.assertTrue(state.exhausted)
  337. class EndToEndSequenceTests(unittest.TestCase):
  338. """The whole first-minute story: replay, live tail, history."""
  339. def test_replay_then_append_then_history(self):
  340. state = State()
  341. feed = Feed(scroll_height=0, client_height=600)
  342. # 1. SSE replay: most-recent-30 oldest-first on the wire.
  343. for evt in server_page(30, 1, True)["events"]:
  344. ingest(state, evt)
  345. render(state, feed, height_after=3000)
  346. self.assertEqual(ids(state), list(range(1, 31)))
  347. self.assertEqual(feed.scroll_top, 3000) # seeded at the tail
  348. # 2. Two live rows arrive; the reader is at the bottom.
  349. on_stream_message(state, feed, "31", height_after=3100)
  350. on_stream_message(state, feed, "32", height_after=3200)
  351. self.assertEqual(ids(state)[-2:], [31, 32])
  352. self.assertEqual(feed.scroll_top, 3200)
  353. # 3. A heartbeat is ignored, then the reader scrolls up.
  354. on_stream_message(state, feed, "ping", height_after=3200)
  355. feed.scroll_top = 100
  356. on_stream_message(state, feed, "33", height_after=3300)
  357. self.assertEqual(feed.scroll_top, 100) # never yanked
  358. # 4. Load older: before=1 -> [60..31] newest-first wire page.
  359. self.assertEqual(state.oldest, 1)
  360. load_more(state, feed, server_page(60, 31, False), height_after=6300)
  361. self.assertEqual(ids(state), list(range(1, 61)))
  362. self.assertTrue(state.exhausted)
  363. self.assertEqual(feed.scroll_top, 100 + 3000) # anchored
  364. # ---------------------------------------------------------------------------
  365. # Payload contract: the daemon JSON-encodes args/result into STRINGS
  366. # ---------------------------------------------------------------------------
  367. def parse_maybe_json(value):
  368. """PORT of parseMaybeJson: strings decode, objects pass through,
  369. a non-JSON string answers None so the caller can fall back to
  370. rendering the raw text."""
  371. if not isinstance(value, str):
  372. return value
  373. try:
  374. return json.loads(value)
  375. except ValueError:
  376. return None
  377. def is_plain_object(value):
  378. """PORT of isPlainObject."""
  379. return isinstance(value, dict)
  380. def fmt_bytes(n):
  381. """PORT of fmtBytes."""
  382. if n < 1024:
  383. return "%d B" % n
  384. if n < 1024 * 1024:
  385. return "%.1f KiB" % (n / 1024)
  386. return "%.1f MiB" % (n / (1024 * 1024))
  387. def str_text(value):
  388. """PORT of strText."""
  389. return value if isinstance(value, str) else ""
  390. def filter_of(kind):
  391. """PORT of filterOf: which filter bucket owns a kind. The yeehaw
  392. celebration lands in the comments bucket (goal 9 task 4b)."""
  393. if kind == "tool_call":
  394. return "commands"
  395. if kind in ("tool_result", "command_output"):
  396. return "results"
  397. if kind in ("comment", "answer", "verdict", "yeehaw"):
  398. return "comments"
  399. if kind == "usage":
  400. return "usage"
  401. return "transitions"
  402. def yeehaw_render(evt):
  403. """PORT of eventNode's yeehaw branch -> (span_class, message)."""
  404. payload = evt.get("payload") or {}
  405. return "yeehaw-message", str_text(payload.get("message"))
  406. def fmt_duration(ms):
  407. """PORT of fmtDuration."""
  408. if ms < 1000:
  409. return "%d ms" % ms
  410. return "%.1f s" % (ms / 1000)
  411. def str_bytes(value):
  412. """PORT of strBytes."""
  413. return len(value) if isinstance(value, str) else 0
  414. def result_envelope(evt):
  415. """PORT of resultEnvelope: the parsed result string when it
  416. decodes to an object, else the object-shaped payload itself."""
  417. payload = evt.get("payload") or {}
  418. parsed = parse_maybe_json(payload.get("result"))
  419. if is_plain_object(parsed):
  420. return parsed
  421. if is_plain_object(payload):
  422. return payload
  423. return {}
  424. RESULT_PLUMBING = ("ok", "exit_code", "stdout", "stderr", "bytes_out",
  425. "bytes_err", "truncated", "duration_ms", "turn", "tool")
  426. def result_extras(envelope):
  427. """PORT of resultExtras: the envelope minus command plumbing
  428. and minus the note members (rendered separately)."""
  429. return dict((key, value) for key, value in envelope.items()
  430. if key not in RESULT_PLUMBING
  431. and key not in ("error", "note", "timeout"))
  432. def result_bits(evt):
  433. """PORT of resultBits -> the metric bits shared by the expander
  434. summary and the inline line."""
  435. envelope = result_envelope(evt)
  436. payload = evt.get("payload") or {}
  437. bits = []
  438. if envelope.get("exit_code") is not None:
  439. bits.append("exit %s" % envelope["exit_code"])
  440. elif envelope.get("ok") is False:
  441. bits.append("failed")
  442. if isinstance(envelope.get("bytes_out"), int) \
  443. and isinstance(envelope.get("bytes_err"), int):
  444. bytes_count = envelope["bytes_out"] + envelope["bytes_err"]
  445. else:
  446. bytes_count = str_bytes(envelope.get("stdout")) \
  447. + str_bytes(envelope.get("stderr"))
  448. if bytes_count > 0:
  449. bits.append(fmt_bytes(bytes_count))
  450. if envelope.get("truncated"):
  451. bits.append("truncated")
  452. if isinstance(envelope.get("duration_ms"), int):
  453. bits.append(fmt_duration(envelope["duration_ms"]))
  454. if payload.get("turn") is not None:
  455. bits.append("turn %s" % payload["turn"])
  456. if not bits and isinstance(payload.get("result"), str) \
  457. and not is_plain_object(parse_maybe_json(payload["result"])):
  458. bits.append(fmt_bytes(len(payload["result"])))
  459. return bits
  460. INLINE_RESULT_LIMIT = 220
  461. def result_view(evt, attached=False):
  462. """PORT of resultView -> (inline, bits_text, body_text): a short
  463. body renders inline under its metric bits; a long one collapses
  464. behind the expander summary - UNLESS it rides attached to its
  465. call, where the output is always visible (CSS clamps oversized
  466. bodies)."""
  467. out, err, note, extras, no_output = result_output(evt)
  468. parts = [part for part in (out, err, note, extras) if part]
  469. if no_output:
  470. parts = ["(no output)"]
  471. body_text = "\n".join(parts).strip()
  472. inline = attached or len(body_text) <= INLINE_RESULT_LIMIT
  473. return inline, " \u00b7 ".join(result_bits(evt)), body_text
  474. def result_summary(evt):
  475. """PORT of resultSummary -> the summary line's text."""
  476. bits = result_bits(evt)
  477. return "result" + (" (" + ", ".join(bits) + ")" if bits else "")
  478. def result_output(evt):
  479. """PORT of resultBody's text decisions -> (stdout_text,
  480. stderr_text, note_text, extras_text, no_output_flag). The extras
  481. go through the tailored result body first (a read window, a
  482. replacement count, a task list, an ok ack), then raw JSON."""
  483. envelope = result_envelope(evt)
  484. payload = evt.get("payload") or {}
  485. parsed = parse_maybe_json(payload.get("result"))
  486. out = err = ""
  487. if is_plain_object(parsed):
  488. out = str_text(envelope.get("stdout"))
  489. err = str_text(envelope.get("stderr"))
  490. elif isinstance(parsed, str):
  491. out = parsed # a JSON string literal
  492. elif isinstance(payload.get("result"), str):
  493. out = payload["result"]
  494. else:
  495. out = str_text(envelope.get("stdout"))
  496. err = str_text(envelope.get("stderr"))
  497. note = ""
  498. extras = ""
  499. if not out and not err:
  500. note = str_text(envelope.get("error")) or str_text(envelope.get("note")) \
  501. or ("timed out" if envelope.get("timeout") else "")
  502. if not note:
  503. remainder = result_extras(envelope)
  504. if remainder:
  505. tailored = tailored_result_text(
  506. str_text(payload.get("tool")), remainder)
  507. if tailored is not None:
  508. extras = tailored
  509. else:
  510. compact = json.dumps(remainder)
  511. extras = compact if len(compact) <= 120 \
  512. else json.dumps(remainder, indent=2)
  513. return out, err, note, extras, (not out and not err and not note and not extras)
  514. def task_list_text(items):
  515. """PORT of taskList -> one '#id title status' line per item."""
  516. lines = []
  517. for item in items:
  518. if not is_plain_object(item):
  519. continue
  520. line = "#%s %s" % (item.get("id", "?"), str_text(item.get("title")))
  521. if str_text(item.get("status")):
  522. line += " " + str_text(item.get("status"))
  523. lines.append(line)
  524. return "\n".join(lines)
  525. def tailored_result_text(tool, extras):
  526. """PORT of tailoredResultBody -> the rendered text, or None for
  527. the generic JSON view."""
  528. if str_text(extras.get("content")) or isinstance(extras.get("total_lines"), int):
  529. meta = []
  530. if str_text(extras.get("path")):
  531. meta.append(str_text(extras.get("path")))
  532. if isinstance(extras.get("total_lines"), int):
  533. start = extras.get("line_start") \
  534. if isinstance(extras.get("line_start"), int) else 1
  535. end = extras.get("line_end") \
  536. if isinstance(extras.get("line_end"), int) else extras["total_lines"]
  537. meta.append("lines %d-%d of %d"
  538. % (start, end, extras["total_lines"]))
  539. if isinstance(extras.get("bytes"), int):
  540. meta.append(fmt_bytes(extras["bytes"]))
  541. else:
  542. if str_text(extras.get("representation")):
  543. meta.append(str_text(extras.get("representation")))
  544. if isinstance(extras.get("bytes_read"), int):
  545. window = fmt_bytes(extras["bytes_read"])
  546. if isinstance(extras.get("total_bytes"), int):
  547. window += " of " + fmt_bytes(extras["total_bytes"])
  548. meta.append(window)
  549. if isinstance(extras.get("offset"), int) and extras["offset"] > 0:
  550. meta.append("at " + fmt_bytes(extras["offset"]))
  551. if extras.get("truncated"):
  552. meta.append("truncated")
  553. parts = [" \u00b7 ".join(meta)]
  554. if str_text(extras.get("content")):
  555. # The content rides behind an expander: a read is
  556. # reference material, not the action's output.
  557. parts.append("[fold] content \u00b7 "
  558. + fmt_bytes(len(str_text(extras.get("content")))))
  559. return "\n".join(parts)
  560. if tool == "replace_in_file" and isinstance(extras.get("replacements"), int):
  561. count = extras["replacements"]
  562. written = extras.get("bytes_written") \
  563. if isinstance(extras.get("bytes_written"), int) else 0
  564. return "%d replacement%s in %s \u00b7 %s" % (
  565. count, "" if count == 1 else "s",
  566. str_text(extras.get("path")), fmt_bytes(written))
  567. if tool == "write_file" and isinstance(extras.get("bytes"), int):
  568. return "wrote %s \u00b7 %s" % (str_text(extras.get("path")),
  569. fmt_bytes(extras["bytes"]))
  570. if tool == "overwrite_file" and isinstance(extras.get("bytes_written"), int):
  571. text = "rewrote %s \u00b7 %s" % (str_text(extras.get("path")),
  572. fmt_bytes(extras["bytes_written"]))
  573. if isinstance(extras.get("previous_bytes"), int):
  574. text += " (was %s)" % fmt_bytes(extras["previous_bytes"])
  575. return text
  576. if tool == "create_task" and isinstance(extras.get("task_id"), int):
  577. text = "created task #%d" % extras["task_id"]
  578. if str_text(extras.get("status")):
  579. text += " \u00b7 " + str_text(extras.get("status"))
  580. return text
  581. if tool == "get_task" and "id" in extras:
  582. return task_list_text([extras])
  583. for key in ("tasks", "goals"):
  584. if isinstance(extras.get(key), list):
  585. return task_list_text(extras[key])
  586. keys = list(extras)
  587. all_true = len(keys) > 0 and all(extras[key] is True for key in keys)
  588. all_scalars = 0 < len(keys) <= 4 and all(
  589. extras[key] is None or not isinstance(extras[key], (dict, list))
  590. for key in keys)
  591. if all_true:
  592. return "ok"
  593. if all_scalars:
  594. return " \u00b7 ".join("%s: %s" % (key, extras[key]) for key in keys)
  595. return None
  596. def args_without(args, skip):
  597. """PORT of argsWithout: every member except `skip`, pretty-
  598. printed; '' when nothing is left."""
  599. rest = dict((key, value) for key, value in args.items() if key != skip)
  600. return json.dumps(rest, indent=2) if rest else ""
  601. def tool_call_render(evt):
  602. """PORT of toolCallBody -> the rendered blocks as (kind, text)
  603. pairs: ('head', line) for a command-styled head, ('pre', text)
  604. for plain pre lines, ('para', text) for prose, ('fold', label)
  605. for collapsed payloads, ('diff', '- old') / ('diff', '+ new')
  606. for the replace_in_file diff. Bespoke bodies come from
  607. tailored_blocks; None falls back to the generic view."""
  608. payload = evt.get("payload") or {}
  609. tool = str_text(payload.get("tool")) or "tool"
  610. parsed = parse_maybe_json(payload.get("args"))
  611. args = parsed if is_plain_object(parsed) else None
  612. if args is not None:
  613. blocks = tailored_blocks(tool, args)
  614. if blocks is not None:
  615. return blocks
  616. blocks = [("head", tool)]
  617. if args is not None:
  618. rest = args_without(args, "command")
  619. if rest:
  620. blocks.append(("pre", rest))
  621. elif str_text(payload.get("args")):
  622. blocks.append(("pre", payload["args"]))
  623. elif payload.get("args") is not None and not isinstance(payload.get("args"), str):
  624. blocks.append(("pre", json.dumps(payload["args"], indent=2)))
  625. return blocks
  626. def fmt_int(n):
  627. """PORT of fmtInt: thousands separators without locale."""
  628. digits = str(abs(int(round(n))))
  629. out = ""
  630. for i, char in enumerate(digits):
  631. if i > 0 and (len(digits) - i) % 3 == 0:
  632. out += ","
  633. out += char
  634. return ("-" if n < 0 else "") + out
  635. def usage_line(payload):
  636. """PORT of eventNode's usage branch -> the one-line text. The
  637. daemon may report either token count alone."""
  638. bits = []
  639. if str_text(payload.get("model")):
  640. bits.append(payload["model"])
  641. in_tok = "%s in" % fmt_int(payload["prompt_tokens"]) \
  642. if isinstance(payload.get("prompt_tokens"), int) else ""
  643. out_tok = "%s out" % fmt_int(payload["completion_tokens"]) \
  644. if isinstance(payload.get("completion_tokens"), int) else ""
  645. if in_tok or out_tok:
  646. bits.append(in_tok + (" / " if in_tok and out_tok else "") + out_tok + " tok")
  647. if isinstance(payload.get("cached_tokens"), int):
  648. bits.append("%s cached" % fmt_int(payload["cached_tokens"]))
  649. if isinstance(payload.get("elapsed_ms"), int):
  650. bits.append(fmt_duration(payload["elapsed_ms"]))
  651. return " \u00b7 ".join(bits) if bits else "unreported"
  652. def state_change_line(payload):
  653. """PORT of eventNode's state_change branch."""
  654. from_status = str_text(payload.get("from"))
  655. to_status = str_text(payload.get("to"))
  656. if from_status and to_status:
  657. return from_status + " \u2192 " + to_status
  658. return str_text(payload.get("text")) or json.dumps(payload)
  659. # --- Quiet-call folding + result attachment (the live-tail polish):
  660. # a successful side-effect tool whose content already renders as its
  661. # own event folds its call/ack pair away; every other call carries
  662. # its result as an attached block instead of a separate row. ---
  663. FOLDABLE_TOOLS = {"update_progress": "progress", "add_comment": "comment",
  664. "yeehaw": "yeehaw"}
  665. def quiet_result(evt):
  666. """PORT of quietResult: an ack-shaped success with nothing to
  667. say - ok, no error/note/timeout, no output, extras only true/
  668. false/empty-string/row pointers (_id integers whose content
  669. renders elsewhere)."""
  670. envelope = result_envelope(evt)
  671. if envelope.get("ok") is False:
  672. return False
  673. if isinstance(envelope.get("exit_code"), int) and envelope["exit_code"] != 0:
  674. return False
  675. if str_text(envelope.get("error")) or str_text(envelope.get("note")):
  676. return False
  677. if envelope.get("timeout"):
  678. return False
  679. if str_text(envelope.get("stdout")) or str_text(envelope.get("stderr")):
  680. return False
  681. for key, value in result_extras(envelope).items():
  682. if value is True or value is False:
  683. continue
  684. if isinstance(value, str) and value == "":
  685. continue
  686. if isinstance(value, int) and key.endswith("_id"):
  687. continue
  688. return False
  689. return True
  690. def same_session(a, b):
  691. """PORT of sameSession: equal, or either side unlabelled."""
  692. return a == b or a is None or b is None
  693. def match_result_index(rows, index):
  694. """PORT of matchResultIndex: the first tool_result after the
  695. call is its own (one call per turn). The live wire's result
  696. payloads carry no turn of their own - matching rides on order,
  697. tool name and session; a turn mismatch (both present) is the
  698. only rejection."""
  699. evt = rows[index]
  700. payload = evt.get("payload") or {}
  701. if not isinstance(payload.get("turn"), int):
  702. return -1
  703. for j in range(index + 1, len(rows)):
  704. other = rows[j]
  705. if other.get("kind") == "tool_result":
  706. other_payload = other.get("payload") or {}
  707. other_turn = other_payload.get("turn")
  708. if (other_turn is None or other_turn == payload.get("turn")) \
  709. and same_session(other.get("session_id"), evt.get("session_id")) \
  710. and str_text(other_payload.get("tool")) == str_text(payload.get("tool")):
  711. return j
  712. return -1
  713. if other.get("kind") == "tool_call":
  714. return -1
  715. return -1
  716. def folded_quiet_calls(rows):
  717. """PORT of foldedQuietCalls -> the folded row indices."""
  718. folded = set()
  719. for index, evt in enumerate(rows):
  720. if evt.get("kind") != "tool_call":
  721. continue
  722. payload = evt.get("payload") or {}
  723. if not isinstance(payload.get("turn"), int):
  724. continue
  725. companion = FOLDABLE_TOOLS.get(str_text(payload.get("tool")))
  726. if not companion:
  727. continue
  728. result_index = match_result_index(rows, index)
  729. if result_index < 0:
  730. continue
  731. has_companion = any(
  732. rows[k].get("kind") == companion
  733. and same_session(rows[k].get("session_id"), evt.get("session_id"))
  734. for k in range(index + 1, result_index))
  735. if has_companion and quiet_result(rows[result_index]):
  736. folded.add(index)
  737. folded.add(result_index)
  738. return folded
  739. def attach_pairs(rows, folded):
  740. """PORT of render's attachment walk -> (calls_by_id,
  741. rides_by_id): every non-folded call carries its matching
  742. result; the result then never renders as its own row."""
  743. calls_by_id = {}
  744. rides_by_id = {}
  745. for index, evt in enumerate(rows):
  746. if index in folded or evt.get("kind") != "tool_call":
  747. continue
  748. result_index = match_result_index(rows, index)
  749. if result_index >= 0 and result_index not in folded:
  750. calls_by_id[evt["id"]] = rows[result_index]["id"]
  751. rides_by_id[rows[result_index]["id"]] = True
  752. return calls_by_id, rides_by_id
  753. # --- The state badge: only a working (or assigned) task streams
  754. # live; every other status names itself on the pill, still. ---
  755. LIVE_STATUSES = {"working", "assigned"}
  756. BADGE_LABELS = {"suspended": "parked", "review_requested": "review requested"}
  757. def badge_line(status, stream_state="live"):
  758. """PORT of updateBadge -> (class, label)."""
  759. if status in LIVE_STATUSES:
  760. if stream_state == "retry":
  761. return "log-live retry", "reconnecting..."
  762. return "log-live", "live"
  763. label = BADGE_LABELS.get(status, status) or "idle"
  764. return "log-live still badge badge-" + status, label
  765. DIFF_CONTEXT = 2
  766. DIFF_MAX_LINES = 400
  767. def _push_side(rows, lines, begin, end, marker):
  768. """PORT of pushSide."""
  769. count = end - begin
  770. half = DIFF_MAX_LINES // 2
  771. if count <= DIFF_MAX_LINES:
  772. for i in range(begin, end):
  773. rows.append([marker, lines[i]])
  774. return
  775. for j in range(begin, begin + half):
  776. rows.append([marker, lines[j]])
  777. rows.append([marker, "... %d more lines ..." % (count - half * 2)])
  778. for k in range(end - half, end):
  779. rows.append([marker, lines[k]])
  780. def diff_rows(old_text, new_text):
  781. """PORT of diffRows: common head/tail become clamped context,
  782. the differing middle renders as -old/+new."""
  783. old_lines = old_text.split("\n")
  784. new_lines = new_text.split("\n")
  785. start = 0
  786. while start < len(old_lines) and start < len(new_lines) \
  787. and old_lines[start] == new_lines[start]:
  788. start += 1
  789. end_old, end_new = len(old_lines), len(new_lines)
  790. while end_old > start and end_new > start \
  791. and old_lines[end_old - 1] == new_lines[end_new - 1]:
  792. end_old -= 1
  793. end_new -= 1
  794. rows = []
  795. has_middle = end_old > start or end_new > start
  796. if has_middle:
  797. for i in range(max(0, start - DIFF_CONTEXT), start):
  798. rows.append([" ", old_lines[i]])
  799. _push_side(rows, old_lines, start, end_old, "-")
  800. _push_side(rows, new_lines, start, end_new, "+")
  801. for i in range(end_old, min(len(old_lines), end_old + DIFF_CONTEXT)):
  802. rows.append([" ", old_lines[i]])
  803. return rows
  804. FILE_LANGUAGES = {".vala": "Vala", ".vapi": "Vapi", ".c": "C", ".h": "C",
  805. ".py": "Python", ".js": "JavaScript", ".ts": "TypeScript",
  806. ".html": "HTML", ".css": "CSS", ".json": "JSON",
  807. ".md": "Markdown", ".sh": "Shell", ".bash": "Shell",
  808. ".xml": "XML", ".yml": "YAML", ".yaml": "YAML",
  809. ".sql": "SQL", ".toml": "TOML", ".ini": "INI",
  810. ".cfg": "Config", ".diff": "Diff", ".patch": "Diff",
  811. ".rst": "reST", ".txt": "Text"}
  812. def language_of(path):
  813. """PORT of languageOf: the extension chip, with meson.build and
  814. makefile as whole-name matches; '' when nothing matches."""
  815. lower = path.lower()
  816. name = lower[lower.rfind("/") + 1:]
  817. if name == "meson.build":
  818. return "Meson"
  819. if name == "makefile":
  820. return "Make"
  821. dot = name.rfind(".")
  822. if dot < 1 or dot == len(name) - 1:
  823. return ""
  824. return FILE_LANGUAGES.get(name[dot:], "")
  825. def content_bits(content):
  826. """PORT of contentBits: line count and byte size."""
  827. lines = content.count("\n") + 1
  828. return ["%d line%s" % (lines, "" if lines == 1 else "s"),
  829. fmt_bytes(len(content))]
  830. def tailored_blocks(tool, args):
  831. """PORT of tailoredCallBody -> the bespoke blocks, or None to
  832. fall back to the generic JSON view (fields missing - e.g. a
  833. truncated args string that clamped mid-JSON)."""
  834. path = str_text(args.get("path"))
  835. command = str_text(args.get("command"))
  836. question = str_text(args.get("question"))
  837. bits = []
  838. def head(text, more=None):
  839. block = ("head", text)
  840. if more:
  841. block = ("head", text + " \u00b7 " + " \u00b7 ".join(more))
  842. return block
  843. if tool == "run_command":
  844. if not command:
  845. return None
  846. if isinstance(args.get("timeout_ms"), int):
  847. bits.append("timeout %ds" % round(args["timeout_ms"] / 1000))
  848. return [head("$ " + command, bits)]
  849. if tool == "read_file":
  850. if not path:
  851. return None
  852. if isinstance(args.get("offset"), int) and args["offset"] > 1:
  853. bits.append("from line %d" % args["offset"])
  854. if isinstance(args.get("limit"), int):
  855. bits.append("%d lines" % args["limit"])
  856. return [head("read_file " + path, bits)]
  857. if tool in ("write_file", "overwrite_file", "temp_doc"):
  858. content = str_text(args.get("content"))
  859. if not content:
  860. return None
  861. if tool == "temp_doc":
  862. return [head("temp_doc", content_bits(content)), ("pre", content)]
  863. if not path:
  864. return None
  865. more = content_bits(content)
  866. language = language_of(path)
  867. if language:
  868. more.insert(0, language)
  869. return [head(tool + " " + path, more), ("pre", content)]
  870. if tool == "replace_in_file":
  871. old = str_text(args.get("old"))
  872. if not path or not old:
  873. return None
  874. if isinstance(args.get("expected_count"), int):
  875. bits.append("expect %d" % args["expected_count"])
  876. blocks = [head("replace_in_file " + path, bits)]
  877. rows = diff_rows(old, str_text(args.get("new")))
  878. if rows:
  879. blocks.extend(("diff", marker + " " + text) for marker, text in rows)
  880. return blocks
  881. if tool in ("enqueue_task", "delete_task", "get_task"):
  882. if not isinstance(args.get("task_id"), int):
  883. return None
  884. return [head(tool + " #" + str(args["task_id"]))]
  885. if tool in ("update_progress", "add_comment", "save_note"):
  886. text = str_text(args.get("text")) or str_text(args.get("body"))
  887. if not text:
  888. return None
  889. if tool == "save_note" and str_text(args.get("project")):
  890. bits.append(str_text(args.get("project")))
  891. return [head(tool, bits), ("para", text)]
  892. if tool == "ask_question":
  893. if not question:
  894. return None
  895. blocks = [head("ask_question"), ("para", "Q: " + question)]
  896. if isinstance(args.get("options"), list) and args["options"]:
  897. blocks.append(("options", [str(o) for o in args["options"]]))
  898. return blocks
  899. return None
  900. def command_output_render(evt):
  901. """PORT of eventNode's command_output branch ->
  902. (command_prefix, output_text)."""
  903. payload = evt.get("payload") or {}
  904. command = str_text(payload.get("command"))
  905. text = payload.get("text") or payload.get("chunk") or ""
  906. return ("$ " + command if command else ""), text
  907. # --- Fixtures: copied from the live ledger (web-db.sqlite, events
  908. # table) and the test fake's object-shaped pushes - the real wire
  909. # shapes, inner JSON spelled out as the daemon serialises it. ---
  910. # The daemon's inner JSON, built with json.dumps so the escaping
  911. # is exactly what the wire carries (a JSON string holding JSON).
  912. inner_call = json.dumps({"command": "cd /workspace && ls"})
  913. inner_progress = json.dumps(
  914. {"text": "Root-caused the SSE listener; next: the payload parse"})
  915. inner_enqueue = json.dumps({"task_id": 3})
  916. inner_result = json.dumps(
  917. {"ok": True, "exit_code": 0,
  918. "stdout": "find /workspace/task-1 -maxdepth 2",
  919. "stderr": "", "duration_ms": 11,
  920. "bytes_out": 6042, "bytes_err": 0, "truncated": True})
  921. inner_error = json.dumps(
  922. {"ok": False,
  923. "error": "suspend refused: 3 draft task(s) were never enqueued"})
  924. inner_empty = json.dumps({"ok": True, "exit_code": 0,
  925. "stdout": "", "stderr": ""})
  926. FIXTURE_RUN_COMMAND_CALL = json.loads(
  927. '{"turn": 52, "tool": "run_command", "args": ' + json.dumps(inner_call) + '}')
  928. FIXTURE_UPDATE_PROGRESS_CALL = json.loads(
  929. '{"turn": 6, "tool": "update_progress", "args": '
  930. + json.dumps(inner_progress) + '}')
  931. FIXTURE_ENQUEUE_CALL = json.loads(
  932. '{"turn": 5, "tool": "enqueue_task", "args": '
  933. + json.dumps(inner_enqueue) + '}')
  934. FIXTURE_RUN_COMMAND_RESULT = json.loads(
  935. '{"tool": "run_command", "result": ' + json.dumps(inner_result)
  936. + ', "turn": 52}')
  937. FIXTURE_ERROR_RESULT = json.loads(
  938. '{"tool": "suspend", "result": ' + json.dumps(inner_error) + '}')
  939. FIXTURE_EMPTY_RESULT = json.loads(
  940. '{"tool": "run_command", "result": ' + json.dumps(inner_empty) + '}')
  941. # Not valid JSON: the live daemon emitted result strings that are
  942. # truncated raw output (72 rows in the production ledger).
  943. FIXTURE_NOT_JSON_RESULT = {
  944. "tool": "run_command",
  945. "result": '{"ok":true,"exit_code":0,"stdout":"=== Spry ===\n'
  946. 'MANIFEST.usm README.md meson.build',
  947. }
  948. # command_output: the harness fake's shape; `command` is a member.
  949. FIXTURE_COMMAND_OUTPUT = {"command": "meson test -C builddir",
  950. "text": "nobody:/task-1$ done\r\n"}
  951. # The harness fake's legacy object-shaped payloads (plan 17's own
  952. # tests push these): args/result as real objects.
  953. FIXTURE_OBJECT_CALL = {"turn": 1, "tool": "run_command",
  954. "args": {"command": "echo hello"}}
  955. FIXTURE_OBJECT_RESULT = {"turn": 1, "tool": "run_command",
  956. "stdout": "hello\n", "exit_code": 0}
  957. # Tailored-rendering fixtures (plan 18): the file tools' arg shapes
  958. # straight off the daemon's tool schemas.
  959. FIXTURE_REPLACE_CALL = {"turn": 40, "tool": "replace_in_file", "args": {
  960. "path": "src/pages/app.css",
  961. "old": ".event-turn {\n border-left: 3px solid #ddf4ff;\n}",
  962. "new": ".event-turn {\n border-left: 3px solid #ddf4ff;\n color: var(--ink-muted);\n}",
  963. "expected_count": 1}}
  964. FIXTURE_WRITE_CALL = {"turn": 41, "tool": "write_file", "args": {
  965. "path": "notes.md", "content": "# Notes\n- first\n- second"}}
  966. # Args clamped mid-JSON by the daemon's display clamp: parsing
  967. # fails, so the bespoke renderer must step aside and the generic
  968. # view shows the raw text.
  969. FIXTURE_TRUNCATED_ARGS = {"turn": 42, "tool": "write_file", "args":
  970. '{"path":"big.bin","content":"AAA'}
  971. class PayloadParserTests(unittest.TestCase):
  972. def test_string_args_decode_to_an_object(self):
  973. parsed = parse_maybe_json(FIXTURE_RUN_COMMAND_CALL["args"])
  974. self.assertEqual(parsed, {"command": "cd /workspace && ls"})
  975. def test_non_json_string_answers_none(self):
  976. self.assertIsNone(parse_maybe_json(
  977. FIXTURE_NOT_JSON_RESULT["result"]))
  978. def test_objects_pass_through(self):
  979. self.assertEqual(parse_maybe_json({"command": "ls"}), {"command": "ls"})
  980. self.assertEqual(parse_maybe_json(None), None)
  981. class ToolCallRenderTests(unittest.TestCase):
  982. """The command the agent ran must surface in EVERY render path,
  983. and each known tool renders through its tailored body."""
  984. def evt(self, payload):
  985. return {"kind": "tool_call", "payload": payload}
  986. def test_run_command_call_heads_with_the_dollar(self):
  987. blocks = tool_call_render(self.evt(FIXTURE_RUN_COMMAND_CALL))
  988. self.assertEqual(blocks[0], ("head", "$ cd /workspace && ls"))
  989. def test_run_command_timeout_rides_the_head(self):
  990. blocks = tool_call_render(self.evt({"tool": "run_command", "args":
  991. {"command": "make", "timeout_ms": 900000}}))
  992. self.assertEqual(blocks[0],
  993. ("head", "$ make \u00b7 timeout 900s"))
  994. def test_update_progress_call_renders_prose_not_json(self):
  995. """The old renderer dumped {"text": ...} as JSON; the
  996. tailored body renders the text itself."""
  997. blocks = tool_call_render(self.evt(FIXTURE_UPDATE_PROGRESS_CALL))
  998. self.assertEqual(blocks[0], ("head", "update_progress"))
  999. self.assertEqual(blocks[1],
  1000. ("para", "Root-caused the SSE listener; next: the payload parse"))
  1001. self.assertNotIn('"text"', json.dumps(blocks))
  1002. def test_enqueue_call_renders_the_id(self):
  1003. blocks = tool_call_render(self.evt(FIXTURE_ENQUEUE_CALL))
  1004. self.assertEqual(blocks, [("head", "enqueue_task #3")])
  1005. def test_replace_in_file_renders_a_diff(self):
  1006. blocks = tool_call_render(self.evt(FIXTURE_REPLACE_CALL))
  1007. self.assertEqual(blocks[0],
  1008. ("head", "replace_in_file src/pages/app.css \u00b7 expect 1"))
  1009. diff_texts = [text for kind, text in blocks if kind == "diff"]
  1010. joined = " ".join(diff_texts)
  1011. self.assertIn(" .event-turn {", joined)
  1012. # The untouched border line is context; only the added color
  1013. # line is an addition - no phantom removals.
  1014. self.assertIn(" border-left: 3px solid #ddf4ff;", joined)
  1015. self.assertIn("+ color: var(--ink-muted);", joined)
  1016. self.assertIn(" }", joined)
  1017. self.assertFalse([t for t in diff_texts if t.startswith("- ")],
  1018. "an unchanged line must never render as a removal")
  1019. def test_write_file_renders_language_lines_and_content(self):
  1020. blocks = tool_call_render(self.evt(FIXTURE_WRITE_CALL))
  1021. self.assertEqual(blocks[0],
  1022. ("head", "write_file notes.md \u00b7 Markdown \u00b7 3 lines \u00b7 24 B"))
  1023. self.assertEqual(blocks[1], ("pre", "# Notes\n- first\n- second"))
  1024. def test_meson_build_gets_its_language(self):
  1025. self.assertEqual(language_of("sub/meson.build"), "Meson")
  1026. self.assertEqual(language_of("src/app.vala"), "Vala")
  1027. self.assertEqual(language_of("Makefile".lower()), "Make")
  1028. self.assertEqual(language_of("data/bin"), "")
  1029. def test_truncated_args_fall_back_to_the_raw_view(self):
  1030. blocks = tool_call_render(self.evt(FIXTURE_TRUNCATED_ARGS))
  1031. self.assertEqual(blocks[0], ("head", "write_file"))
  1032. self.assertEqual(blocks[1][0], "pre")
  1033. self.assertIn('"path":"big.bin"', blocks[1][1])
  1034. def test_unknown_tool_falls_back_to_json_args(self):
  1035. blocks = tool_call_render(self.evt(
  1036. {"tool": "brand_new_tool", "args": {"deep": {"a": 1}}}))
  1037. self.assertEqual(blocks[0], ("head", "brand_new_tool"))
  1038. self.assertIn('"deep"', blocks[1][1])
  1039. def test_object_shaped_call_still_works(self):
  1040. blocks = tool_call_render(self.evt(FIXTURE_OBJECT_CALL))
  1041. self.assertEqual(blocks, [("head", "$ echo hello")])
  1042. def test_non_json_args_render_raw(self):
  1043. blocks = tool_call_render(self.evt(
  1044. {"tool": "run_command", "args": "not json at all"}))
  1045. self.assertEqual(blocks,
  1046. [("head", "run_command"), ("pre", "not json at all")])
  1047. def test_no_args_at_all_renders_the_tool_name(self):
  1048. blocks = tool_call_render(self.evt({"tool": "list_tasks"}))
  1049. self.assertEqual(blocks, [("head", "list_tasks")])
  1050. def test_bespoke_missing_fields_step_aside(self):
  1051. """A replace_in_file without its old string (clamped args
  1052. that still parse) falls back rather than lying."""
  1053. blocks = tool_call_render(self.evt(
  1054. {"tool": "replace_in_file", "args": {"path": "x.c"}}))
  1055. self.assertEqual(blocks[0], ("head", "replace_in_file"))
  1056. self.assertEqual(blocks[1][0], "pre")
  1057. class DiffRowTests(unittest.TestCase):
  1058. """The replace_in_file diff: context clamping and honest
  1059. replacement semantics."""
  1060. def test_single_line_swap(self):
  1061. rows = diff_rows("alpha\nbeta\ngamma", "alpha\nBETA\ngamma")
  1062. self.assertEqual(rows, [[" ", "alpha"], ["-", "beta"],
  1063. ["+", "BETA"], [" ", "gamma"]])
  1064. def test_context_is_clamped_to_two_lines_per_side(self):
  1065. old = "\n".join(["ctx"] * 10 + ["old-line"] + ["ctx"] * 10)
  1066. new = "\n".join(["ctx"] * 10 + ["new-line"] + ["ctx"] * 10)
  1067. rows = diff_rows(old, new)
  1068. context = [text for marker, text in rows if marker == " "]
  1069. self.assertEqual(context, ["ctx"] * 4)
  1070. def test_whole_file_rewrite_shows_no_context(self):
  1071. rows = diff_rows("a\nb\nc", "x\ny\nz")
  1072. self.assertEqual([m for m, _ in rows], ["-", "-", "-", "+", "+", "+"])
  1073. def test_deletion_only_keeps_its_context(self):
  1074. rows = diff_rows("keep\ndrop\nkeep", "keep\nkeep")
  1075. self.assertEqual(rows, [[" ", "keep"], ["-", "drop"], [" ", "keep"]])
  1076. def test_empty_new_text(self):
  1077. rows = diff_rows("line", "")
  1078. self.assertEqual(rows, [["-", "line"], ["+", ""]])
  1079. def test_oversized_side_keeps_head_and_tail(self):
  1080. old = "\n".join("line-%04d" % i for i in range(1000))
  1081. rows = diff_rows(old, "changed")
  1082. dels = [text for marker, text in rows if marker == "-"]
  1083. self.assertEqual(len(dels), 401)
  1084. self.assertIn("more lines", dels[200])
  1085. self.assertEqual(dels[0], "line-0000")
  1086. self.assertEqual(dels[-1], "line-0999")
  1087. def test_identical_text_renders_nothing(self):
  1088. self.assertEqual(diff_rows("same\nsame", "same\nsame"), [])
  1089. class UsageLineTests(unittest.TestCase):
  1090. def test_full_payload_is_one_line(self):
  1091. line = usage_line({"model": "glm-4.7", "prompt_tokens": 45200000,
  1092. "completion_tokens": 1100000, "cached_tokens": 4500,
  1093. "elapsed_ms": 3200})
  1094. self.assertEqual(line,
  1095. "glm-4.7 \u00b7 45,200,000 in / 1,100,000 out tok "
  1096. "\u00b7 4,500 cached \u00b7 3.2 s")
  1097. def test_unreported_when_no_numbers(self):
  1098. self.assertEqual(usage_line({}), "unreported")
  1099. def test_partial_payload_skips_missing_members(self):
  1100. line = usage_line({"completion_tokens": 5, "elapsed_ms": 40})
  1101. self.assertEqual(line, "5 out tok \u00b7 40 ms")
  1102. class StateChangeLineTests(unittest.TestCase):
  1103. def test_from_to_arrow(self):
  1104. self.assertEqual(
  1105. state_change_line({"from": "working", "to": "blocked",
  1106. "text": "Status \u2192 blocked"}),
  1107. "working \u2192 blocked")
  1108. def test_text_fallback(self):
  1109. self.assertEqual(
  1110. state_change_line({"text": "Goal created (branch x)"}),
  1111. "Goal created (branch x)")
  1112. def test_json_fallback(self):
  1113. self.assertEqual(state_change_line({}), "{}")
  1114. QUIET_ACK = json.dumps({"ok": True, "recorded": True})
  1115. FAILED_ACK = json.dumps({"ok": False, "error": "web callback unreachable"})
  1116. def progress_trio(result_inner=QUIET_ACK, with_companion=True,
  1117. result_turn=None):
  1118. """The live-tail's repetitive trio: an update_progress call,
  1119. the progress event carrying the same text, then the ack
  1120. result. The live wire's result payloads carry NO turn of their
  1121. own (the payload is {tool, result}); pass result_turn to model
  1122. a turn-stamped result."""
  1123. rows = [{"id": 1, "kind": "tool_call", "session_id": 201, "payload": {
  1124. "turn": 1551, "tool": "update_progress",
  1125. "args": json.dumps({"text": "Segfault located"})}}]
  1126. if with_companion:
  1127. rows.append({"id": 2, "kind": "progress", "session_id": 201,
  1128. "payload": {"text": "Segfault located"}})
  1129. result_payload = {"tool": "update_progress", "result": result_inner}
  1130. if result_turn is not None:
  1131. result_payload["turn"] = result_turn
  1132. rows.append({"id": 3, "kind": "tool_result", "session_id": 201,
  1133. "payload": result_payload})
  1134. return rows
  1135. class QuietFoldingTests(unittest.TestCase):
  1136. """A successful update_progress renders as its progress event
  1137. ALONE; the duplicate call and the bare ack fold away. A failure
  1138. unfolds both."""
  1139. def test_quiet_trio_folds_call_and_result(self):
  1140. """The live wire's shape: the result carries no turn."""
  1141. folded = folded_quiet_calls(progress_trio())
  1142. self.assertEqual(folded, {0, 2})
  1143. def test_turn_stamped_result_also_folds(self):
  1144. folded = folded_quiet_calls(progress_trio(result_turn=1551))
  1145. self.assertEqual(folded, {0, 2})
  1146. def test_turn_mismatch_never_folds(self):
  1147. """A result stamped with another turn is not this call's
  1148. answer."""
  1149. self.assertEqual(
  1150. folded_quiet_calls(progress_trio(result_turn=9999)), set())
  1151. def test_add_comment_folds_behind_its_comment_event(self):
  1152. """The add_comment result carries a comment_id row pointer -
  1153. quiet - and the comment event between carries the body."""
  1154. rows = [
  1155. {"id": 1, "kind": "tool_call", "session_id": 201, "payload": {
  1156. "turn": 60, "tool": "add_comment",
  1157. "args": json.dumps({"body": "Merged and pushed."})}},
  1158. {"id": 2, "kind": "comment", "session_id": 201, "actor": "model",
  1159. "payload": {"body": "Merged and pushed."}},
  1160. {"id": 3, "kind": "tool_result", "session_id": 201, "payload": {
  1161. "tool": "add_comment",
  1162. "result": json.dumps({"ok": True, "comment_id": 234})}},
  1163. ]
  1164. self.assertEqual(folded_quiet_calls(rows), {0, 2})
  1165. def test_failed_ack_unfolds_the_pair(self):
  1166. self.assertEqual(folded_quiet_calls(progress_trio(FAILED_ACK)), set())
  1167. def test_missing_companion_unfolds(self):
  1168. """Without the progress event between them there would be
  1169. nothing to show instead - keep the pair."""
  1170. self.assertEqual(folded_quiet_calls(progress_trio(with_companion=False)),
  1171. set())
  1172. def test_missing_result_unfolds(self):
  1173. rows = progress_trio()[:2]
  1174. self.assertEqual(folded_quiet_calls(rows), set())
  1175. def test_non_foldable_tool_never_folds(self):
  1176. rows = [
  1177. {"id": 1, "kind": "tool_call", "session_id": 201, "payload": {
  1178. "turn": 5, "tool": "run_command",
  1179. "args": json.dumps({"command": "ls"})}},
  1180. {"id": 2, "kind": "tool_result", "session_id": 201, "payload": {
  1181. "tool": "run_command", "result": QUIET_ACK}},
  1182. ]
  1183. self.assertEqual(folded_quiet_calls(rows), set())
  1184. class ResultAttachmentTests(unittest.TestCase):
  1185. """A non-folded call carries its result as an attached block
  1186. INSIDE its row; the result never renders as a separate row."""
  1187. def test_call_and_result_pair_up(self):
  1188. rows = [
  1189. {"id": 10, "kind": "tool_call", "session_id": 7, "payload": {
  1190. "turn": 5, "tool": "run_command",
  1191. "args": json.dumps({"command": "make"})}},
  1192. {"id": 11, "kind": "tool_result", "session_id": 7, "payload": {
  1193. "tool": "run_command",
  1194. "result": json.dumps({"ok": True, "exit_code": 0,
  1195. "stdout": "built\n", "stderr": "",
  1196. "duration_ms": 900})}},
  1197. ]
  1198. calls_by_id, rides_by_id = attach_pairs(rows, set())
  1199. self.assertEqual(calls_by_id, {10: 11})
  1200. self.assertEqual(rides_by_id, {11: True})
  1201. def test_turn_less_live_result_pairs_up(self):
  1202. """The live wire's shape: the result carries no turn, so
  1203. matching rides on order, tool and session."""
  1204. rows = [
  1205. {"id": 20, "kind": "tool_call", "session_id": 201, "payload": {
  1206. "turn": 1731, "tool": "run_command",
  1207. "args": json.dumps({"command": "make test"})}},
  1208. {"id": 21, "kind": "tool_result", "session_id": 201, "payload": {
  1209. "tool": "run_command",
  1210. "result": json.dumps({"ok": True, "exit_code": 0,
  1211. "stdout": "ok\n", "stderr": "",
  1212. "duration_ms": 25000})}},
  1213. ]
  1214. calls_by_id, rides_by_id = attach_pairs(rows, set())
  1215. self.assertEqual(calls_by_id, {20: 21})
  1216. self.assertEqual(rides_by_id, {21: True})
  1217. def test_long_command_output_is_visible_when_attached(self):
  1218. """A command's output must be VISIBLE riding with its call -
  1219. never behind a click - even past the inline limit; CSS
  1220. clamps the overflow."""
  1221. big_output = "line %d\n" * 60 % tuple(range(60))
  1222. evt = {"kind": "tool_result", "payload": {
  1223. "tool": "run_command",
  1224. "result": json.dumps({"ok": True, "exit_code": 0,
  1225. "stdout": big_output, "stderr": "",
  1226. "duration_ms": 5000})}}
  1227. standalone, _, body = result_view(evt)
  1228. attached, _, attached_body = result_view(evt, attached=True)
  1229. self.assertFalse(standalone, "long standalone results collapse")
  1230. self.assertTrue(attached, "attached results are always inline")
  1231. self.assertEqual(attached_body, body)
  1232. def test_folded_pair_attaches_nothing(self):
  1233. calls_by_id, rides_by_id = attach_pairs(
  1234. progress_trio(), folded_quiet_calls(progress_trio()))
  1235. self.assertEqual((calls_by_id, rides_by_id), ({}, {}))
  1236. def test_result_without_visible_call_stands_alone(self):
  1237. rows = progress_trio()[2:] # only the result is visible
  1238. calls_by_id, rides_by_id = attach_pairs(rows, set())
  1239. self.assertEqual((calls_by_id, rides_by_id), ({}, {}))
  1240. class BadgeLineTests(unittest.TestCase):
  1241. """The badge reflects the TASK first: live only while a working
  1242. (or assigned) task streams; every other status names itself."""
  1243. def test_working_is_live(self):
  1244. self.assertEqual(badge_line("working"), ("log-live", "live"))
  1245. def test_assigned_is_live(self):
  1246. self.assertEqual(badge_line("assigned"), ("log-live", "live"))
  1247. def test_retry_only_rides_a_live_task(self):
  1248. self.assertEqual(badge_line("working", "retry"),
  1249. ("log-live retry", "reconnecting..."))
  1250. self.assertEqual(badge_line("failed", "retry")[1], "failed")
  1251. def test_suspended_shows_as_parked(self):
  1252. cls, label = badge_line("suspended")
  1253. self.assertEqual(label, "parked")
  1254. self.assertIn("still badge badge-suspended", cls)
  1255. def test_review_requested_uses_the_task_page_word(self):
  1256. self.assertEqual(badge_line("review_requested")[1],
  1257. "review requested")
  1258. def test_terminal_states_name_themselves(self):
  1259. self.assertEqual(badge_line("done")[1], "done")
  1260. self.assertEqual(badge_line("failed")[1], "failed")
  1261. def test_unknown_status_falls_back_to_idle(self):
  1262. self.assertEqual(badge_line("")[1], "idle")
  1263. class ToolResultRenderTests(unittest.TestCase):
  1264. def evt(self, payload):
  1265. return {"kind": "tool_result", "payload": payload}
  1266. def test_summary_comes_from_the_envelope(self):
  1267. line = result_summary(self.evt(FIXTURE_RUN_COMMAND_RESULT))
  1268. self.assertEqual(line,
  1269. "result (exit 0, 5.9 KiB, truncated, 11 ms, turn 52)")
  1270. def test_summary_marks_failed_envelopes(self):
  1271. line = result_summary(self.evt(
  1272. {"tool": "run_command", "result": '{"ok":false,"error":"x"}'}))
  1273. self.assertEqual(line, "result (failed)")
  1274. def test_body_shows_the_envelopes_stdout(self):
  1275. out, err, note, extras, no_output = result_output(
  1276. self.evt(FIXTURE_RUN_COMMAND_RESULT))
  1277. self.assertEqual(out, "find /workspace/task-1 -maxdepth 2")
  1278. self.assertEqual(err, "")
  1279. self.assertFalse(no_output)
  1280. def test_non_json_result_renders_as_output_text(self):
  1281. out, err, note, extras, no_output = result_output(
  1282. self.evt(FIXTURE_NOT_JSON_RESULT))
  1283. self.assertIn("=== Spry ===", out)
  1284. self.assertFalse(no_output,
  1285. "raw output must never be called (no output)")
  1286. def test_error_envelope_is_not_no_output(self):
  1287. out, err, note, extras, no_output = result_output(
  1288. self.evt(FIXTURE_ERROR_RESULT))
  1289. self.assertEqual((out, err), ("", ""))
  1290. self.assertIn("suspend refused", note)
  1291. self.assertFalse(no_output,
  1292. "an error member means the result said something")
  1293. def test_genuinely_empty_result_says_no_output(self):
  1294. out, err, note, extras, no_output = result_output(self.evt(FIXTURE_EMPTY_RESULT))
  1295. self.assertEqual((out, err, note, extras), ("", "", "", ""))
  1296. self.assertTrue(no_output)
  1297. def test_object_shaped_result_still_works(self):
  1298. line = result_summary(self.evt(FIXTURE_OBJECT_RESULT))
  1299. self.assertEqual(line, "result (exit 0, 6 B, turn 1)")
  1300. out, err, note, extras, no_output = result_output(self.evt(FIXTURE_OBJECT_RESULT))
  1301. self.assertEqual(out, "hello\n")
  1302. def test_tool_answer_envelope_is_rendered_not_swallowed(self):
  1303. """The live ledger's update_progress/create_task/finish
  1304. results carry {"recorded":true} / {"ok":true,"task_id":4}
  1305. / {"accepted":true} with empty streams: that IS the tool's
  1306. answer and must render, not "(no output)"."""
  1307. for inner in ('{"recorded":true}',
  1308. '{"ok":true,"task_id":4,"status":"draft"}',
  1309. '{"accepted":true}',
  1310. '{"suspended":true}',
  1311. '{"ok":true,"status":"pending"}'):
  1312. out, err, note, extras, no_output = result_output(self.evt(
  1313. {"tool": "update_progress", "result": inner}))
  1314. self.assertFalse(no_output, inner)
  1315. self.assertEqual((out, err, note), ("", "", ""))
  1316. self.assertTrue(extras, inner)
  1317. def test_list_tasks_answer_renders_as_a_list(self):
  1318. inner = json.dumps({"ok": True, "tasks": [
  1319. {"id": 6, "title": "UX notes", "status": "queued"},
  1320. {"id": 5, "title": "Event log parse", "status": "working"}]})
  1321. out, err, note, extras, no_output = result_output(self.evt(
  1322. {"tool": "list_tasks", "result": inner}))
  1323. self.assertFalse(no_output)
  1324. self.assertIn("UX notes", extras)
  1325. self.assertIn("Event log parse", extras)
  1326. self.assertIn("#6", extras)
  1327. self.assertNotIn('"tasks"', extras,
  1328. "a task list renders as rows, not a JSON dump")
  1329. def test_replace_in_file_result_counts_the_replacements(self):
  1330. inner = json.dumps({"ok": True, "path": "src/app.css",
  1331. "replacements": 2, "bytes_written": 2048})
  1332. out, err, note, extras, no_output = result_output(self.evt(
  1333. {"tool": "replace_in_file", "result": inner}))
  1334. self.assertEqual(extras, "2 replacements in src/app.css \u00b7 2.0 KiB")
  1335. def test_read_file_result_renders_the_window(self):
  1336. inner = json.dumps({"ok": True, "path": "src/main.vala",
  1337. "total_lines": 540, "line_start": 100,
  1338. "line_end": 160, "bytes": 4200,
  1339. "truncated": False, "content": "int main() {"})
  1340. out, err, note, extras, no_output = result_output(self.evt(
  1341. {"tool": "read_file", "result": inner}))
  1342. self.assertIn("src/main.vala \u00b7 lines 100-160 of 540 \u00b7 4.1 KiB", extras)
  1343. self.assertIn("[fold] content \u00b7 12 B", extras)
  1344. def test_read_binary_result_renders_the_window(self):
  1345. inner = json.dumps({"ok": True, "path": "model.bin",
  1346. "representation": "hex", "total_bytes": 1024,
  1347. "offset": 256, "bytes_read": 512,
  1348. "truncated": False,
  1349. "content": "00000100 7f 45 4c 46"})
  1350. out, err, note, extras, no_output = result_output(self.evt(
  1351. {"tool": "read_binary", "result": inner}))
  1352. self.assertIn("model.bin \u00b7 hex \u00b7 512 B of 1.0 KiB \u00b7 at 256 B", extras)
  1353. self.assertIn("[fold] content", extras)
  1354. def test_write_file_result_states_the_write(self):
  1355. out, err, note, extras, no_output = result_output(self.evt(
  1356. {"tool": "write_file",
  1357. "result": '{"ok":true,"path":"notes.md","bytes":24}'}))
  1358. self.assertEqual(extras, "wrote notes.md \u00b7 24 B")
  1359. def test_create_task_result_names_the_task(self):
  1360. out, err, note, extras, no_output = result_output(self.evt(
  1361. {"tool": "create_task",
  1362. "result": '{"ok":true,"task_id":4,"status":"draft"}'}))
  1363. self.assertEqual(extras, "created task #4 \u00b7 draft")
  1364. def test_pure_acknowledgement_is_an_ok_line(self):
  1365. out, err, note, extras, no_output = result_output(self.evt(
  1366. {"tool": "update_progress", "result": '{"ok":true,"recorded":true}'}))
  1367. self.assertEqual(extras, "ok")
  1368. def test_run_command_with_empty_streams_is_still_no_output(self):
  1369. """Only command plumbing present: the run genuinely said
  1370. nothing - keep the honest "(no output)"."""
  1371. out, err, note, extras, no_output = result_output(self.evt(
  1372. {"tool": "run_command",
  1373. "result": '{"ok":true,"exit_code":0,"stdout":"",'
  1374. '"stderr":"","duration_ms":5,"bytes_out":0,'
  1375. '"bytes_err":0,"truncated":false}'}))
  1376. self.assertTrue(no_output)
  1377. self.assertEqual(extras, "")
  1378. class CommandOutputRenderTests(unittest.TestCase):
  1379. def test_command_is_prefixed_as_a_shell_line(self):
  1380. command, text = command_output_render(
  1381. {"kind": "command_output", "payload": FIXTURE_COMMAND_OUTPUT})
  1382. self.assertEqual(command, "$ meson test -C builddir")
  1383. self.assertEqual(text, "nobody:/task-1$ done\r\n")
  1384. def test_text_only_chunk_keeps_the_old_render(self):
  1385. command, text = command_output_render(
  1386. {"kind": "command_output", "payload": {"text": "hello\r\n"}})
  1387. self.assertEqual(command, "")
  1388. self.assertEqual(text, "hello\r\n")
  1389. class SearchHaystackTests(unittest.TestCase):
  1390. """A search for text inside the STRING-encoded args/result must
  1391. still find the event: the haystack appends the raw strings."""
  1392. def test_search_matches_through_the_string_encoding(self):
  1393. payload = FIXTURE_RUN_COMMAND_CALL
  1394. haystack = "tool_call daemon " + json.dumps(payload) + " " \
  1395. + str_text(payload.get("args")) + " " \
  1396. + str_text(payload.get("result"))
  1397. self.assertIn("cd /workspace && ls", haystack)
  1398. class YeehawFilterTests(unittest.TestCase):
  1399. """The celebration must ride the comments filter (goal 9 task 4b):
  1400. a human scanning the conversation sees the yeehaw, and the
  1401. comments toggle hides it like any other chatter."""
  1402. def test_yeehaw_maps_to_comments(self):
  1403. self.assertEqual(filter_of("yeehaw"), "comments")
  1404. def test_comment_kinds_unchanged(self):
  1405. for kind in ("comment", "answer", "verdict"):
  1406. self.assertEqual(filter_of(kind), "comments")
  1407. def test_other_kinds_unchanged(self):
  1408. self.assertEqual(filter_of("tool_call"), "commands")
  1409. self.assertEqual(filter_of("tool_result"), "results")
  1410. self.assertEqual(filter_of("command_output"), "results")
  1411. self.assertEqual(filter_of("usage"), "usage")
  1412. self.assertEqual(filter_of("lifecycle"), "transitions")
  1413. class YeehawRenderTests(unittest.TestCase):
  1414. """The yeehaw branch: the message in the bold .yeehaw-message span
  1415. (the festive palette), never a JSON payload dump."""
  1416. def test_message_renders_in_the_span(self):
  1417. span, message = yeehaw_render(
  1418. {"kind": "yeehaw", "payload": {"message": "Loved every line"}})
  1419. self.assertEqual(span, "yeehaw-message")
  1420. self.assertEqual(message, "Loved every line")
  1421. def test_missing_message_is_blank_not_garbage(self):
  1422. span, message = yeehaw_render({"kind": "yeehaw", "payload": {}})
  1423. self.assertEqual(message, "")
  1424. def test_non_string_message_is_blank(self):
  1425. span, message = yeehaw_render(
  1426. {"kind": "yeehaw", "payload": {"message": 42}})
  1427. self.assertEqual(message, "")
  1428. class RendererSourceTests(unittest.TestCase):
  1429. """The shipped script itself (no JS engine in this container, so
  1430. the render decisions are pinned by the ports above plus these
  1431. shape checks on the served source)."""
  1432. def setUp(self):
  1433. self.body = script_body()
  1434. def test_parse_maybe_json_is_defined_and_used(self):
  1435. self.assertIn("function parseMaybeJson(value) {", self.body)
  1436. self.assertGreaterEqual(self.body.count("parseMaybeJson("), 4)
  1437. def test_no_innerhtml_anywhere(self):
  1438. self.assertNotIn(".innerHTML", self.body)
  1439. def test_command_output_prefixes_the_dollar(self):
  1440. self.assertIn("'$ ' + p.command", self.body)
  1441. def test_tool_call_line_uses_parsed_args(self):
  1442. self.assertIn("args.command", self.body)
  1443. self.assertIn("toolCallBody", self.body)
  1444. def test_result_reads_parsed_envelope(self):
  1445. self.assertIn("resultEnvelope", self.body)
  1446. self.assertIn("bytes_out", self.body)
  1447. self.assertIn("duration_ms", self.body)
  1448. def test_yeehaw_lands_in_the_comments_bucket(self):
  1449. self.assertRegex(
  1450. self.body,
  1451. r"kind === 'comment' \|\| kind === 'answer' \|\| kind === 'verdict'[\s\S]*?"
  1452. r"kind === 'yeehaw'\) return 'comments'")
  1453. def test_yeehaw_renders_the_message_span(self):
  1454. self.assertIn("evt.kind === 'yeehaw'", self.body)
  1455. self.assertIn("'yeehaw-message'", self.body)
  1456. self.assertIn("strText(p.message)", self.body)
  1457. def test_tailored_renderers_present(self):
  1458. self.assertIn("function tailoredCallBody(tool, args) {", self.body)
  1459. self.assertIn("function diffRows(oldText, newText) {", self.body)
  1460. self.assertIn("'event-diff'", self.body)
  1461. self.assertIn("tailoredCallBody(tool, args)", self.body)
  1462. if __name__ == "__main__":
  1463. unittest.main(verbosity=2)