test_tui_app.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559
  1. """Smoke test: the Textual app mounts, subscribes, and ingests broadcasts."""
  2. import asyncio
  3. import os
  4. import shutil
  5. import sys
  6. import tempfile
  7. import pytest
  8. from stt_daemon.assistant.control import ControlServer
  9. from stt_daemon.assistant.service import AssistantService
  10. from stt_daemon.config import Config
  11. class FakeSubscriber:
  12. def events(self):
  13. return iter(())
  14. def close(self):
  15. pass
  16. @pytest.fixture
  17. def server():
  18. directory = tempfile.mkdtemp(prefix="stta-")
  19. path = os.path.join(directory, "c.sock")
  20. cfg = Config()
  21. cfg.assistant.control_socket = path
  22. service = AssistantService(cfg, FakeSubscriber())
  23. control = ControlServer(cfg, service, path=path)
  24. service.set_sinks(emit=control.broadcast, relay=control.relay)
  25. control.start()
  26. yield path, service
  27. control.close()
  28. service.stop()
  29. shutil.rmtree(directory, ignore_errors=True)
  30. def test_ctrl_r_sends_execute_and_e_focuses_command(server):
  31. pytest.importorskip("textual")
  32. from textual.widgets import Input
  33. from stt_daemon.tui.app import AssistantTUI
  34. path, _service = server
  35. app = AssistantTUI(path)
  36. sent: list[tuple] = []
  37. observed: dict = {}
  38. async def scenario():
  39. async with app.run_test() as pilot:
  40. await pilot.pause()
  41. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  42. await pilot.press("ctrl+r")
  43. await pilot.pause()
  44. await pilot.press("a")
  45. await pilot.pause()
  46. await pilot.press("escape")
  47. await pilot.pause()
  48. await pilot.press("e")
  49. await pilot.pause()
  50. cmd = app.query_one("#command", Input)
  51. observed["cmd_focused"] = cmd.has_focus
  52. asyncio.run(scenario())
  53. assert ("command_execute", {}) in sent
  54. assert ("command_start", {}) in sent
  55. assert ("command_cancel", {}) in sent
  56. assert observed["cmd_focused"] is True
  57. def test_type_command_enter_from_idle_sends_start_edit_execute(server):
  58. pytest.importorskip("textual")
  59. from textual.widgets import Input
  60. from stt_daemon.tui.app import AssistantTUI
  61. path, _service = server
  62. app = AssistantTUI(path)
  63. sent: list[tuple] = []
  64. async def scenario():
  65. async with app.run_test() as pilot:
  66. await pilot.pause()
  67. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  68. assert app.state.mode == "idle"
  69. app.query_one("#command", Input).focus()
  70. await pilot.pause()
  71. for ch in "take notes":
  72. await pilot.press(ch)
  73. await pilot.pause()
  74. await pilot.press("enter")
  75. await pilot.pause()
  76. asyncio.run(scenario())
  77. assert [t for t, _ in sent] == ["command_start", "command_edit", "command_execute"], sent
  78. assert sent[1][1] == {"text": "take notes"}, sent
  79. def test_type_command_enter_when_armed_skips_start(server):
  80. pytest.importorskip("textual")
  81. from textual.widgets import Input
  82. from stt_daemon.tui.app import AssistantTUI
  83. path, _service = server
  84. app = AssistantTUI(path)
  85. sent: list[tuple] = []
  86. async def scenario():
  87. async with app.run_test() as pilot:
  88. await pilot.pause()
  89. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  90. app._timer.stop() # no background drain: server status must not clobber state
  91. app._drain()
  92. app.state.ingest({"type": "mode", "mode": "command_armed"})
  93. assert app.state.mode == "command_armed"
  94. app.query_one("#command", Input).focus()
  95. await pilot.pause()
  96. for ch in "open calendar":
  97. await pilot.press(ch)
  98. await pilot.pause()
  99. await pilot.press("enter")
  100. await pilot.pause()
  101. asyncio.run(scenario())
  102. assert [t for t, _ in sent] == ["command_edit", "command_execute"], sent
  103. assert sent[0][1] == {"text": "open calendar"}, sent
  104. def test_arm_from_chat_leaves_chat_first(server):
  105. pytest.importorskip("textual")
  106. from stt_daemon.tui.app import AssistantTUI
  107. path, _service = server
  108. app = AssistantTUI(path)
  109. sent: list[tuple] = []
  110. async def scenario():
  111. async with app.run_test() as pilot:
  112. await pilot.pause()
  113. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  114. app._timer.stop()
  115. app._drain()
  116. app.state.ingest({"type": "mode", "mode": "chat"})
  117. await pilot.press("a")
  118. await pilot.pause()
  119. asyncio.run(scenario())
  120. assert [t for t, _ in sent] == ["chat_toggle", "command_start"], sent
  121. def test_type_command_enter_from_chat_leaves_chat_first(server):
  122. pytest.importorskip("textual")
  123. from textual.widgets import Input
  124. from stt_daemon.tui.app import AssistantTUI
  125. path, _service = server
  126. app = AssistantTUI(path)
  127. sent: list[tuple] = []
  128. async def scenario():
  129. async with app.run_test() as pilot:
  130. await pilot.pause()
  131. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  132. app._timer.stop()
  133. app._drain()
  134. app.state.ingest({"type": "mode", "mode": "chat"})
  135. app.query_one("#command", Input).focus()
  136. await pilot.pause()
  137. for ch in "open calendar":
  138. await pilot.press(ch)
  139. await pilot.pause()
  140. await pilot.press("enter")
  141. await pilot.pause()
  142. asyncio.run(scenario())
  143. assert [t for t, _ in sent] == [
  144. "chat_toggle",
  145. "command_start",
  146. "command_edit",
  147. "command_execute",
  148. ], sent
  149. def test_command_from_chat_mode_reaches_executing(server):
  150. """A command sent while chatting leaves chat and actually executes."""
  151. pytest.importorskip("textual")
  152. from textual.widgets import Input
  153. from stt_daemon.tui.app import AssistantTUI
  154. path, service = server
  155. app = AssistantTUI(path)
  156. async def scenario():
  157. async with app.run_test() as pilot:
  158. await pilot.pause()
  159. assert service.toggle_chat() is True
  160. for _ in range(100):
  161. await pilot.pause()
  162. if app.state.mode == "chat":
  163. break
  164. assert app.state.mode == "chat"
  165. app.query_one("#command", Input).focus()
  166. await pilot.pause()
  167. for ch in "do it":
  168. await pilot.press(ch)
  169. await pilot.pause()
  170. await pilot.press("enter")
  171. for _ in range(100):
  172. await pilot.pause()
  173. if service.modes.mode.value == "executing":
  174. break
  175. asyncio.run(scenario())
  176. assert service.modes.mode.value == "executing"
  177. def test_typed_execute_clears_command_input(server):
  178. """Typing a command and pressing Enter clears the input as soon as it executes."""
  179. pytest.importorskip("textual")
  180. from textual.widgets import Input
  181. from stt_daemon.tui.app import AssistantTUI
  182. path, service = server
  183. app = AssistantTUI(path)
  184. observed: dict = {}
  185. async def scenario():
  186. async with app.run_test() as pilot:
  187. await pilot.pause()
  188. app.query_one("#command", Input).focus()
  189. await pilot.pause()
  190. for ch in "do it":
  191. await pilot.press(ch)
  192. await pilot.pause()
  193. await pilot.press("enter")
  194. for _ in range(100):
  195. await pilot.pause()
  196. if service.modes.mode.value == "executing":
  197. break
  198. await pilot.pause()
  199. observed["value"] = app.query_one("#command", Input).value
  200. observed["state_text"] = app.state.command_text
  201. asyncio.run(scenario())
  202. assert service.modes.mode.value == "executing"
  203. assert observed["value"] == ""
  204. assert observed["state_text"] == ""
  205. def test_chat_input_enter_activates_chat_sends_and_keeps_focus(server):
  206. """Typing in #chat-input + Enter enters chat, sends, clears, and keeps focus."""
  207. pytest.importorskip("textual")
  208. from textual.widgets import Input
  209. from stt_daemon.tui.app import AssistantTUI
  210. path, _service = server
  211. app = AssistantTUI(path)
  212. sent: list[tuple] = []
  213. observed: dict = {}
  214. async def scenario():
  215. async with app.run_test(size=(80, 40)) as pilot:
  216. await pilot.pause()
  217. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  218. app._timer.stop()
  219. app._drain()
  220. chat_input = app.query_one("#chat-input", Input)
  221. chat_input.focus()
  222. await pilot.pause()
  223. for ch in "hello":
  224. await pilot.press(ch)
  225. await pilot.pause()
  226. await pilot.press("enter")
  227. await pilot.pause()
  228. observed["value"] = chat_input.value
  229. observed["focused"] = chat_input.has_focus
  230. observed["lower_view"] = app._lower_view
  231. asyncio.run(scenario())
  232. assert [t for t, _ in sent] == ["chat_toggle", "chat_send"], sent
  233. assert sent[1][1] == {"text": "hello"}
  234. assert observed["value"] == ""
  235. assert observed["focused"] is True
  236. assert observed["lower_view"] == "chat"
  237. def test_chat_input_from_chat_sends_without_toggle(server):
  238. pytest.importorskip("textual")
  239. from textual.widgets import Input
  240. from stt_daemon.tui.app import AssistantTUI
  241. path, _service = server
  242. app = AssistantTUI(path)
  243. sent: list[tuple] = []
  244. async def scenario():
  245. async with app.run_test(size=(80, 40)) as pilot:
  246. await pilot.pause()
  247. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  248. app._timer.stop()
  249. app._drain()
  250. app.state.ingest({"type": "mode", "mode": "chat"})
  251. chat_input = app.query_one("#chat-input", Input)
  252. chat_input.focus()
  253. await pilot.pause()
  254. for ch in "again":
  255. await pilot.press(ch)
  256. await pilot.pause()
  257. await pilot.press("enter")
  258. await pilot.pause()
  259. asyncio.run(scenario())
  260. assert [t for t, _ in sent] == ["chat_send"], sent
  261. def test_chat_input_enter_activates_chat_and_sends(server):
  262. """End-to-end: a typed chat message enters chat mode and lands in history."""
  263. pytest.importorskip("textual")
  264. from textual.widgets import Input
  265. from stt_daemon.tui.app import AssistantTUI
  266. path, service = server
  267. app = AssistantTUI(path)
  268. observed: dict = {}
  269. async def scenario():
  270. async with app.run_test(size=(80, 40)) as pilot:
  271. await pilot.pause()
  272. chat_input = app.query_one("#chat-input", Input)
  273. chat_input.focus()
  274. await pilot.pause()
  275. for ch in "hello":
  276. await pilot.press(ch)
  277. await pilot.pause()
  278. await pilot.press("enter")
  279. for _ in range(100):
  280. await pilot.pause()
  281. if service.modes.mode.value == "chat" and service.chat_history:
  282. break
  283. observed["mode"] = service.modes.mode.value
  284. observed["history"] = list(service.chat_history)
  285. asyncio.run(scenario())
  286. assert observed["mode"] == "chat"
  287. assert observed["history"] == ["hello"]
  288. def test_command_and_chat_inputs_share_a_row(server):
  289. """#chat-input sits to the right of #command on the same row, titled 'chat'."""
  290. pytest.importorskip("textual")
  291. from textual.widgets import Input
  292. from stt_daemon.tui.app import AssistantTUI
  293. path, _service = server
  294. app = AssistantTUI(path)
  295. observed: dict = {}
  296. async def scenario():
  297. async with app.run_test(size=(80, 40)) as pilot:
  298. await pilot.pause()
  299. command = app.query_one("#command", Input)
  300. chat = app.query_one("#chat-input", Input)
  301. observed["same_row"] = command.region.y == chat.region.y
  302. observed["chat_right"] = chat.region.x > command.region.x
  303. observed["title"] = chat.border_title
  304. observed["widths"] = (command.region.width, chat.region.width)
  305. asyncio.run(scenario())
  306. assert observed["same_row"] is True
  307. assert observed["chat_right"] is True
  308. assert observed["title"] == "chat"
  309. command_w, chat_w = observed["widths"]
  310. assert abs(command_w - chat_w) <= 2, observed["widths"]
  311. def test_empty_command_enter_sends_nothing(server):
  312. pytest.importorskip("textual")
  313. from textual.widgets import Input
  314. from stt_daemon.tui.app import AssistantTUI
  315. path, _service = server
  316. app = AssistantTUI(path)
  317. sent: list[tuple] = []
  318. async def scenario():
  319. async with app.run_test() as pilot:
  320. await pilot.pause()
  321. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  322. app.query_one("#command", Input).focus()
  323. await pilot.pause()
  324. await pilot.press("enter")
  325. await pilot.pause()
  326. asyncio.run(scenario())
  327. assert sent == []
  328. def test_e_focuses_command_input(server):
  329. pytest.importorskip("textual")
  330. from textual.widgets import Input
  331. from stt_daemon.tui.app import AssistantTUI
  332. path, _service = server
  333. app = AssistantTUI(path)
  334. observed: dict = {}
  335. async def scenario():
  336. async with app.run_test() as pilot:
  337. await pilot.pause()
  338. app._timer.stop() # no background drain: server status must not clobber state
  339. app._drain()
  340. app.state.ingest({"type": "command_text", "text": "voice text", "edited": False})
  341. app._render()
  342. await pilot.pause()
  343. await pilot.press("e")
  344. await pilot.pause()
  345. cmd = app.query_one("#command", Input)
  346. observed["focused"] = cmd.has_focus
  347. observed["value"] = cmd.value
  348. asyncio.run(scenario())
  349. assert observed["focused"] is True
  350. assert observed["value"] == "voice text"
  351. def test_voice_text_updates_unfocused_but_not_focused(server):
  352. pytest.importorskip("textual")
  353. from textual.widgets import Input
  354. from stt_daemon.tui.app import AssistantTUI
  355. path, _service = server
  356. app = AssistantTUI(path)
  357. observed: dict = {}
  358. async def scenario():
  359. async with app.run_test() as pilot:
  360. await pilot.pause()
  361. app._timer.stop() # no background drain: server status must not clobber state
  362. app._drain()
  363. cmd = app.query_one("#command", Input)
  364. assert not cmd.has_focus
  365. app.state.ingest({"type": "command_text", "text": "voice built", "edited": False})
  366. app._render()
  367. await pilot.pause()
  368. observed["unfocused_value"] = app.query_one("#command", Input).value
  369. app.query_one("#command", Input).focus()
  370. await pilot.pause()
  371. for ch in "user typing":
  372. await pilot.press(ch)
  373. await pilot.pause()
  374. app.state.ingest({"type": "command_text", "text": "voice late", "edited": False})
  375. app._render()
  376. await pilot.pause()
  377. observed["focused_value"] = app.query_one("#command", Input).value
  378. asyncio.run(scenario())
  379. assert observed["unfocused_value"] == "voice built"
  380. assert observed["focused_value"] == "user typing"
  381. def test_command_input_border_title(server):
  382. pytest.importorskip("textual")
  383. from textual.widgets import Input
  384. from stt_daemon.tui.app import AssistantTUI
  385. path, _service = server
  386. app = AssistantTUI(path)
  387. async def scenario():
  388. async with app.run_test() as pilot:
  389. await pilot.pause()
  390. app._render()
  391. await pilot.pause()
  392. return app.query_one("#command", Input).border_title
  393. title = asyncio.run(scenario())
  394. assert "command buffer" in title
  395. def test_no_autofocus_on_mount(server):
  396. """Nothing is focused on mount: single-letter hotkeys must not be swallowed by #command."""
  397. pytest.importorskip("textual")
  398. from stt_daemon.tui.app import AssistantTUI
  399. path, _service = server
  400. app = AssistantTUI(path)
  401. async def scenario():
  402. async with app.run_test() as pilot:
  403. await pilot.pause()
  404. await pilot.pause()
  405. return app.focused
  406. assert asyncio.run(scenario()) is None
  407. def test_submit_blurs_command_and_hotkey_still_fires(server):
  408. """Type + Enter sends messages, clears focus; a hotkey (t) still fires afterwards."""
  409. pytest.importorskip("textual")
  410. from textual.widgets import Input
  411. from stt_daemon.tui.app import AssistantTUI
  412. path, _service = server
  413. app = AssistantTUI(path)
  414. sent: list[tuple] = []
  415. observed: dict = {}
  416. async def scenario():
  417. async with app.run_test() as pilot:
  418. await pilot.pause()
  419. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  420. app._timer.stop() # no background drain: server status must not clobber state
  421. app._drain()
  422. app.query_one("#command", Input).focus()
  423. await pilot.pause()
  424. for ch in "take notes":
  425. await pilot.press(ch)
  426. await pilot.pause()
  427. await pilot.press("enter")
  428. await pilot.pause()
  429. observed["focused_after_submit"] = app.focused
  430. observed["value_after_submit"] = app.query_one("#command", Input).value
  431. await pilot.press("t")
  432. await pilot.pause()
  433. observed["lower_view"] = app._lower_view
  434. asyncio.run(scenario())
  435. assert [t for t, _ in sent] == [
  436. "command_start",
  437. "command_edit",
  438. "command_execute",
  439. ], sent
  440. assert observed["focused_after_submit"] is None
  441. assert observed["value_after_submit"] == ""
  442. assert observed["lower_view"] == "output"
  443. def test_focus_triage_then_m_maximizes_deterministically(server):
  444. """Focus #triage, assert focus stuck, then m maximizes #main (no auto-focus race)."""
  445. pytest.importorskip("textual")
  446. from textual.widgets import RichLog
  447. from stt_daemon.tui.app import AssistantTUI
  448. path, _service = server
  449. app = AssistantTUI(path, triage_enabled=True)
  450. observed: dict = {}
  451. async def scenario():
  452. async with app.run_test(size=(80, 40)) as pilot:
  453. await pilot.pause()
  454. app.query_one("#triage", RichLog).focus()
  455. await pilot.pause()
  456. assert app.focused is not None and app.focused.id == "triage", app.focused
  457. await pilot.press("m")
  458. await pilot.pause()
  459. observed["maximized_is_main"] = app.screen.maximized is app.query_one("#main")
  460. asyncio.run(scenario())
  461. assert observed["maximized_is_main"] is True
  462. def test_c_key_confirms_before_clearing(server):
  463. pytest.importorskip("textual")
  464. from stt_daemon.tui.app import AssistantTUI
  465. path, _service = server
  466. app = AssistantTUI(path)
  467. sent: list[tuple] = []
  468. async def scenario():
  469. async with app.run_test() as pilot:
  470. await pilot.pause()
  471. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  472. await pilot.press("c")
  473. await pilot.pause()
  474. assert not any(type_ == "clear" for type_, _ in sent), "clear sent before confirmation"
  475. await pilot.press("y")
  476. await pilot.pause()
  477. asyncio.run(scenario())
  478. assert ("clear", {}) in sent
  479. def test_c_key_hides_visible_pane(server):
  480. """Confirming clear hides whatever lower pane was showing."""
  481. pytest.importorskip("textual")
  482. from textual.widgets import RichLog
  483. from stt_daemon.tui.app import AssistantTUI
  484. path, _service = server
  485. app = AssistantTUI(path)
  486. async def scenario():
  487. async with app.run_test(size=(80, 40)) as pilot:
  488. await pilot.pause()
  489. app.state.ingest(
  490. {"type": "tool_result", "tool": "get_datetime", "ok": True, "result": "now"}
  491. )
  492. app._lower_view = "output"
  493. app._render()
  494. await pilot.pause()
  495. assert app.query_one("#output", RichLog).display is True
  496. await pilot.press("c")
  497. await pilot.pause()
  498. await pilot.press("y")
  499. for _ in range(100):
  500. await pilot.pause()
  501. if app._lower_view == "hidden":
  502. break
  503. asyncio.run(scenario())
  504. assert app._lower_view == "hidden"
  505. pytest.importorskip("textual")
  506. from stt_daemon.tui.app import AssistantTUI
  507. path, _service = server
  508. app = AssistantTUI(path)
  509. sent: list[tuple] = []
  510. async def scenario():
  511. async with app.run_test() as pilot:
  512. await pilot.pause()
  513. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  514. await pilot.press("c")
  515. await pilot.pause()
  516. await pilot.press("n")
  517. await pilot.pause()
  518. asyncio.run(scenario())
  519. assert not any(type_ == "clear" for type_, _ in sent)
  520. def test_c_key_escape_does_not_clear(server):
  521. pytest.importorskip("textual")
  522. from stt_daemon.tui.app import AssistantTUI
  523. path, _service = server
  524. app = AssistantTUI(path)
  525. sent: list[tuple] = []
  526. async def scenario():
  527. async with app.run_test() as pilot:
  528. await pilot.pause()
  529. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  530. await pilot.press("c")
  531. await pilot.pause()
  532. await pilot.press("escape")
  533. await pilot.pause()
  534. asyncio.run(scenario())
  535. assert not any(type_ == "clear" for type_, _ in sent)
  536. def test_c_key_clears_rendered_output(server):
  537. """Pressing 'c' clears the conversation pane via the cleared event."""
  538. pytest.importorskip("textual")
  539. from textual.widgets import RichLog
  540. from stt_daemon.tui.app import AssistantTUI
  541. path, _service = server
  542. app = AssistantTUI(path)
  543. async def scenario():
  544. async with app.run_test() as pilot:
  545. await pilot.pause()
  546. app.state.ingest({"type": "chat_message", "role": "user", "text": "hello"})
  547. app.state.ingest(
  548. {
  549. "type": "tool_result",
  550. "tool": "get_datetime",
  551. "ok": True,
  552. "result": "2026-09-21",
  553. }
  554. )
  555. app._render()
  556. await pilot.pause()
  557. app.state.ingest({"type": "cleared"})
  558. app._render()
  559. await pilot.pause()
  560. log = app.query_one("#chat", RichLog)
  561. return list(log.lines)
  562. lines = asyncio.run(scenario())
  563. assert not any("hello" in str(line) for line in lines)
  564. assert not any("2026-09-21" in str(line) for line in lines)
  565. def test_tui_renders_command_output(server):
  566. """A tool result must actually reach a widget - otherwise 'nothing happens'."""
  567. pytest.importorskip("textual")
  568. from textual.widgets import RichLog
  569. from stt_daemon.tui.app import AssistantTUI
  570. path, _service = server
  571. app = AssistantTUI(path)
  572. async def scenario():
  573. async with app.run_test() as pilot:
  574. await pilot.pause()
  575. app.state.ingest(
  576. {
  577. "type": "tool_result",
  578. "tool": "get_datetime",
  579. "ok": True,
  580. "result": "2026-09-21T01:00:00",
  581. }
  582. )
  583. app._render()
  584. await pilot.pause()
  585. log = app.query_one("#output", RichLog)
  586. return list(log.lines)
  587. lines = asyncio.run(scenario())
  588. assert lines, "command output was not rendered anywhere"
  589. def test_command_output_and_chat_render_in_separate_panes(server):
  590. """Tool output lands in #output and chat turns in #chat, with no crossover."""
  591. pytest.importorskip("textual")
  592. from textual.widgets import RichLog
  593. from stt_daemon.tui.app import AssistantTUI
  594. path, _service = server
  595. app = AssistantTUI(path)
  596. async def scenario():
  597. async with app.run_test() as pilot:
  598. await pilot.pause()
  599. app._timer.stop() # no background drain: server status must not clobber state
  600. app._drain()
  601. app.state.ingest(
  602. {"type": "tool_result", "tool": "get_datetime", "ok": True, "result": "cmd"}
  603. )
  604. app.state.ingest({"type": "mode", "mode": "chat"})
  605. app.state.ingest({"type": "chat_message", "role": "user", "text": "hi"})
  606. app._render()
  607. await pilot.pause()
  608. output = [str(line) for line in app.query_one("#output", RichLog).lines]
  609. chat = [str(line) for line in app.query_one("#chat", RichLog).lines]
  610. return output, chat
  611. output, chat = asyncio.run(scenario())
  612. assert any("cmd" in line for line in output)
  613. assert not any("hi" in line for line in output)
  614. assert any("hi" in line for line in chat)
  615. assert not any("cmd" in line for line in chat)
  616. def test_tui_keeps_chat_pane_on_chat_exit(server):
  617. """Leaving chat keeps the rendered conversation; only clear drops it."""
  618. pytest.importorskip("textual")
  619. from textual.widgets import RichLog
  620. from stt_daemon.tui.app import AssistantTUI
  621. path, _service = server
  622. app = AssistantTUI(path)
  623. async def scenario():
  624. async with app.run_test() as pilot:
  625. await pilot.pause()
  626. app.state.ingest(
  627. {"type": "tool_result", "tool": "get_datetime", "ok": True, "result": "kept"}
  628. )
  629. app.state.ingest({"type": "mode", "mode": "chat"})
  630. app.state.ingest({"type": "chat_message", "role": "user", "text": "kept-turn"})
  631. app._render()
  632. await pilot.pause()
  633. app.state.ingest({"type": "mode", "mode": "idle"})
  634. app._render()
  635. await pilot.pause()
  636. chat = [str(line) for line in app.query_one("#chat", RichLog).lines]
  637. output = [str(line) for line in app.query_one("#output", RichLog).lines]
  638. app.state.ingest({"type": "cleared"})
  639. app._render()
  640. await pilot.pause()
  641. cleared = [str(line) for line in app.query_one("#chat", RichLog).lines]
  642. return chat, output, cleared
  643. chat_lines, output_lines, cleared = asyncio.run(scenario())
  644. assert any("kept-turn" in line for line in chat_lines)
  645. assert not any("kept-turn" in line for line in output_lines)
  646. assert any("kept" in line for line in output_lines)
  647. assert cleared == []
  648. def test_tui_mounts_subscribes_and_ingests_broadcasts(server):
  649. pytest.importorskip("textual")
  650. from stt_daemon.tui.app import AssistantTUI
  651. path, service = server
  652. app = AssistantTUI(path)
  653. async def scenario():
  654. async with app.run_test() as pilot:
  655. await pilot.pause()
  656. service.arm() # broadcast to the subscribed viewer
  657. for _ in range(60):
  658. await pilot.pause()
  659. if app.state.mode == "command_armed":
  660. break
  661. await asyncio.sleep(0.05)
  662. asyncio.run(scenario())
  663. assert app.state.mode == "command_armed"
  664. def test_render_after_unmount_is_safe(server):
  665. """A timer tick can land during teardown; rendering must not raise."""
  666. pytest.importorskip("textual")
  667. from stt_daemon.tui.app import AssistantTUI
  668. path, _service = server
  669. app = AssistantTUI(path)
  670. async def scenario():
  671. async with app.run_test() as pilot:
  672. await pilot.pause()
  673. asyncio.run(scenario())
  674. app._render() # must not raise NoMatches
  675. def test_tui_records_connect_failure(tmp_path):
  676. pytest.importorskip("textual")
  677. from stt_daemon.tui.app import AssistantTUI
  678. app = AssistantTUI(str(tmp_path / "missing.sock"))
  679. async def scenario():
  680. async with app.run_test() as pilot:
  681. await pilot.pause()
  682. asyncio.run(scenario())
  683. assert app.connect_error is not None
  684. assert "cannot connect" in app.connect_error
  685. def test_border_titles_show_queue_and_inference_depths(server):
  686. """Border titles for transcript and chat show live segment and inference queue counts."""
  687. pytest.importorskip("textual")
  688. from textual.widgets import RichLog
  689. from stt_daemon.tui.app import AssistantTUI
  690. path, _service = server
  691. app = AssistantTUI(path)
  692. async def scenario():
  693. async with app.run_test() as pilot:
  694. await pilot.pause()
  695. app.state.ingest(
  696. {
  697. "type": "heartbeat",
  698. "queue_depth": 5,
  699. "inference_depth": 3,
  700. "inference_in_flight": False,
  701. }
  702. )
  703. app._render()
  704. await pilot.pause()
  705. transcript_title = app.query_one("#transcript", RichLog).border_title
  706. chat_title = app.query_one("#chat", RichLog).border_title
  707. assert "[seg 5]" in transcript_title
  708. assert "[inf 3]" in chat_title
  709. assert "busy" not in chat_title
  710. # Test with inference in flight
  711. app.state.ingest(
  712. {
  713. "type": "heartbeat",
  714. "inference_depth": 7,
  715. "inference_in_flight": True,
  716. }
  717. )
  718. app._render()
  719. await pilot.pause()
  720. chat_title = app.query_one("#chat", RichLog).border_title
  721. assert "[inf 7" in chat_title
  722. assert "busy" in chat_title
  723. asyncio.run(scenario())
  724. def test_main_exit_code_reflects_connect_failure(monkeypatch, tmp_path, capsys):
  725. pytest.importorskip("textual")
  726. from stt_daemon.tui import app as tui_app
  727. monkeypatch.setattr(
  728. tui_app.AssistantTUI,
  729. "run",
  730. lambda self: setattr(self, "connect_error", "boom"),
  731. )
  732. monkeypatch.setattr(sys, "argv", ["stt-tui", "--socket", str(tmp_path / "x.sock")])
  733. assert tui_app.main() == 1
  734. assert "boom" in capsys.readouterr().err
  735. monkeypatch.setattr(tui_app.AssistantTUI, "run", lambda self: None)
  736. assert tui_app.main() == 0
  737. def test_triage_disabled_composes_no_triage_widget(server):
  738. """Default (triage_enabled=False): no #triage, no #main — tree as today."""
  739. pytest.importorskip("textual")
  740. from stt_daemon.tui.app import AssistantTUI
  741. path, _service = server
  742. app = AssistantTUI(path)
  743. async def scenario():
  744. async with app.run_test() as pilot:
  745. await pilot.pause()
  746. assert not app.query("#triage")
  747. assert not app.query("#main")
  748. # The rest of the tree is intact.
  749. app.query_one("#transcript")
  750. app.query_one("#status")
  751. app.query_one("#command")
  752. app.query_one("#chat")
  753. asyncio.run(scenario())
  754. def test_triage_enabled_composes_split(server):
  755. """triage_enabled=True: #main wraps #triage (left) + #chat (right); transcript stays outside."""
  756. pytest.importorskip("textual")
  757. from textual.containers import Horizontal
  758. from textual.widgets import RichLog
  759. from stt_daemon.tui.app import AssistantTUI
  760. path, _service = server
  761. app = AssistantTUI(path, triage_enabled=True)
  762. async def scenario():
  763. async with app.run_test() as pilot:
  764. await pilot.pause()
  765. main = app.query_one("#main", Horizontal)
  766. transcript = app.query_one("#transcript", RichLog)
  767. triage = app.query_one("#triage", RichLog)
  768. chat = app.query_one("#chat", RichLog)
  769. assert triage.parent is main
  770. assert chat.parent is main
  771. assert transcript.parent is not main
  772. assert triage.border_title == "triage \\[inf 0]" # markup: '[' is escaped
  773. # triage sits LEFT of chat inside #main.
  774. assert main.children.index(triage) < main.children.index(chat)
  775. # Outside widgets stay outside #main.
  776. assert app.query_one("#status").parent is not main
  777. assert transcript.parent is not main
  778. asyncio.run(scenario())
  779. def test_triage_enabled_layout_proportions(server):
  780. """Rendered proportions: #triage ~1/3 and #chat ~2/3 of #main; #transcript ~25% of screen."""
  781. pytest.importorskip("textual")
  782. from textual.containers import Horizontal
  783. from textual.widgets import RichLog
  784. from stt_daemon.tui.app import AssistantTUI
  785. path, _service = server
  786. app = AssistantTUI(path, triage_enabled=True)
  787. async def scenario(size=None):
  788. kwargs = {"size": size} if size else {}
  789. async with app.run_test(**kwargs) as pilot:
  790. await pilot.pause()
  791. app._timer.stop() # no background drain: server status must not clobber state
  792. app._drain()
  793. # Chat needs content to be shown (hidden-by-default rule): put it in
  794. # chat mode so the 1/3-2/3 split applies.
  795. app._lower_view = "chat"
  796. app.state.ingest({"type": "mode", "mode": "chat"})
  797. app._render()
  798. await pilot.pause()
  799. main = app.query_one("#main", Horizontal)
  800. transcript = app.query_one("#transcript", RichLog)
  801. triage = app.query_one("#triage", RichLog)
  802. chat = app.query_one("#chat", RichLog)
  803. return (
  804. main.size.width,
  805. triage.size.width,
  806. chat.size.width,
  807. app.screen.size.height,
  808. transcript.region.height,
  809. )
  810. main_w, triage_w, chat_w, screen_h, transcript_h = asyncio.run(scenario())
  811. print(
  812. f"measured: main_w={main_w} triage_w={triage_w} chat_w={chat_w} "
  813. f"screen_h={screen_h} transcript_h={transcript_h}"
  814. )
  815. # Content boxes exclude the 1-cell border on each side; allow ±2 px for
  816. # borders/rounding on the fractional split.
  817. assert abs(triage_w / main_w - 1 / 3) < 0.05, (main_w, triage_w, chat_w)
  818. assert abs(chat_w / main_w - 2 / 3) < 0.05, (main_w, triage_w, chat_w)
  819. # region.height includes the transcript's 2 border rows; at the small
  820. # default size rounding is coarse, so only demand a floor here. The
  821. # precise 25% check runs at a taller size below.
  822. assert transcript_h / screen_h >= 0.18, (screen_h, transcript_h)
  823. assert transcript_h >= 1, transcript_h
  824. app2 = AssistantTUI(path, triage_enabled=True)
  825. async def scenario_tall():
  826. async with app2.run_test(size=(80, 40)) as pilot:
  827. await pilot.pause()
  828. transcript2 = app2.query_one("#transcript", RichLog)
  829. return app2.screen.size.height, transcript2.region.height
  830. screen_h2, transcript_h2 = asyncio.run(scenario_tall())
  831. print(f"measured tall: screen_h={screen_h2} transcript_h={transcript_h2}")
  832. assert abs(transcript_h2 / screen_h2 - 0.25) < 0.06, (screen_h2, transcript_h2)
  833. def test_triage_enabled_renders_signals_on_epoch_change(server):
  834. """A triage event + status event must actually write rendered lines into #triage."""
  835. pytest.importorskip("textual")
  836. from textual.widgets import RichLog
  837. from stt_daemon.tui.app import AssistantTUI
  838. path, _service = server
  839. app = AssistantTUI(path, triage_enabled=True)
  840. async def scenario():
  841. async with app.run_test() as pilot:
  842. await pilot.pause()
  843. app._timer.stop() # no background drain: server status must not clobber state
  844. app._drain()
  845. app.state.ingest(
  846. {
  847. "type": "triage",
  848. "stage": "signals",
  849. "triage": {
  850. "order": ["category"],
  851. "items": {
  852. "category": {
  853. "kind": "choice",
  854. "choice": "question",
  855. "answer_confidence": 0.91,
  856. }
  857. },
  858. },
  859. }
  860. )
  861. app.state.ingest(
  862. {"type": "status", "triage_state": "ok", "triage_reason": ""}
  863. )
  864. app._render()
  865. await pilot.pause()
  866. return [str(line) for line in app.query_one("#triage", RichLog).lines]
  867. lines = asyncio.run(scenario())
  868. rendered = "\n".join(lines)
  869. assert "category: question (0.91)" in rendered
  870. def test_triage_enabled_loading_shows_reason_line_never_blank(server):
  871. """loading/unknown triage_state renders the reason line — never a blank panel."""
  872. pytest.importorskip("textual")
  873. from textual.widgets import RichLog
  874. from stt_daemon.tui.app import AssistantTUI
  875. path, _service = server
  876. app = AssistantTUI(path, triage_enabled=True)
  877. async def scenario():
  878. async with app.run_test() as pilot:
  879. await pilot.pause()
  880. app._timer.stop() # no background drain: server status must not clobber state
  881. app._drain()
  882. app.state.ingest(
  883. {
  884. "type": "status",
  885. "triage_state": "loading",
  886. "triage_reason": "model loading",
  887. }
  888. )
  889. app._render()
  890. await pilot.pause()
  891. loading_lines = [str(line) for line in app.query_one("#triage", RichLog).lines]
  892. # Unknown state falls back to a generic reason line, no crash.
  893. app.state.ingest(
  894. {"type": "status", "triage_state": "weird_state", "triage_reason": ""}
  895. )
  896. app._render()
  897. await pilot.pause()
  898. unknown_lines = [str(line) for line in app.query_one("#triage", RichLog).lines]
  899. return loading_lines, unknown_lines
  900. loading_lines, unknown_lines = asyncio.run(scenario())
  901. assert loading_lines, "triage panel was blank in loading state"
  902. assert any("triage: unavailable" in line for line in loading_lines)
  903. assert any("model loading" in line for line in loading_lines)
  904. assert unknown_lines, "triage panel was blank for unknown state"
  905. assert any("triage: unavailable" in line for line in unknown_lines)
  906. assert any("weird_state" in line for line in unknown_lines)
  907. def test_triage_epoch_change_clears_before_rewrite(server):
  908. """Epoch bump clears #triage first: no duplicated stale lines."""
  909. pytest.importorskip("textual")
  910. from textual.widgets import RichLog
  911. from stt_daemon.tui.app import AssistantTUI
  912. path, _service = server
  913. app = AssistantTUI(path, triage_enabled=True)
  914. async def scenario():
  915. async with app.run_test() as pilot:
  916. await pilot.pause()
  917. app._timer.stop() # no background drain: server status must not clobber state
  918. app._drain()
  919. app.state.ingest(
  920. {
  921. "type": "triage",
  922. "stage": "signals",
  923. "triage": {"order": ["q1"], "items": {"q1": {"kind": "choice", "choice": "a"}}},
  924. }
  925. )
  926. app.state.ingest({"type": "status", "triage_state": "ok"})
  927. app._render()
  928. await pilot.pause()
  929. # New epoch: cleared stage empties the payload, panel must not keep old lines.
  930. app.state.ingest({"type": "triage", "stage": "cleared"})
  931. app._render()
  932. await pilot.pause()
  933. return [str(line) for line in app.query_one("#triage", RichLog).lines]
  934. lines = asyncio.run(scenario())
  935. rendered = "\n".join(lines)
  936. assert "q1" not in rendered, "stale triage lines survived an epoch change"
  937. assert "triage: unavailable — no data" in rendered
  938. def test_triage_disabled_never_writes_triage(server):
  939. """Disabled: triage events are ingested but #triage is never touched (it doesn't exist)."""
  940. pytest.importorskip("textual")
  941. from stt_daemon.tui.app import AssistantTUI
  942. path, _service = server
  943. app = AssistantTUI(path)
  944. async def scenario():
  945. async with app.run_test() as pilot:
  946. await pilot.pause()
  947. app.state.ingest({"type": "triage", "stage": "signals", "triage": {}})
  948. app.state.ingest({"type": "status", "triage_state": "ok"})
  949. app._render() # must not raise NoMatches for #triage
  950. await pilot.pause()
  951. assert not app.query("#triage")
  952. asyncio.run(scenario())
  953. def test_default_ctor_has_no_triage_arg(server):
  954. """AssistantTUI(path) stays valid: triage_enabled defaults to False."""
  955. pytest.importorskip("textual")
  956. from stt_daemon.tui.app import AssistantTUI
  957. path, _service = server
  958. app = AssistantTUI(path)
  959. assert app.triage_enabled is False
  960. assert app._seen_triage_epoch == 0
  961. def test_maximize_triage_hides_chat_and_fills_screen(server):
  962. """Focus #triage, press m: #main maximized, chat hidden, triage fills screen."""
  963. pytest.importorskip("textual")
  964. from textual.widgets import RichLog
  965. from stt_daemon.tui.app import AssistantTUI
  966. path, _service = server
  967. app = AssistantTUI(path, triage_enabled=True)
  968. observed: dict = {}
  969. async def scenario():
  970. async with app.run_test(size=(80, 40)) as pilot:
  971. await pilot.pause()
  972. app.query_one("#triage", RichLog).focus()
  973. await pilot.pause()
  974. assert app.focused is not None and app.focused.id == "triage", app.focused
  975. await pilot.press("m")
  976. await pilot.pause()
  977. observed["maximized_is_main"] = app.screen.maximized is app.query_one("#main")
  978. observed["triage_display"] = app.query_one("#triage", RichLog).display
  979. observed["chat_display"] = app.query_one("#chat", RichLog).display
  980. observed["region"] = app.query_one("#triage", RichLog).region
  981. observed["screen_size"] = app.screen.size
  982. asyncio.run(scenario())
  983. print("triage maximized: region=%s screen=%s" % (observed["region"], observed["screen_size"]))
  984. assert observed["maximized_is_main"] is True
  985. assert observed["triage_display"] is True
  986. assert observed["chat_display"] is False
  987. region = observed["region"]
  988. size = observed["screen_size"]
  989. assert abs(region.width - size.width) <= 2, (region, size)
  990. assert abs(region.height - size.height) <= 2, (region, size)
  991. def test_maximize_toggle_restores_layout(server):
  992. """Press m again: minimize restores panes; chat follows the content rule (hidden)."""
  993. pytest.importorskip("textual")
  994. from textual.widgets import RichLog
  995. from stt_daemon.tui.app import AssistantTUI
  996. path, _service = server
  997. app = AssistantTUI(path, triage_enabled=True)
  998. observed: dict = {}
  999. async def scenario():
  1000. async with app.run_test(size=(80, 40)) as pilot:
  1001. await pilot.pause()
  1002. app.query_one("#triage", RichLog).focus()
  1003. await pilot.pause()
  1004. await pilot.press("m")
  1005. await pilot.pause()
  1006. await pilot.press("m")
  1007. await pilot.pause()
  1008. observed["maximized"] = app.screen.maximized
  1009. observed["triage_display"] = app.query_one("#triage", RichLog).display
  1010. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1011. asyncio.run(scenario())
  1012. assert observed["maximized"] is None
  1013. assert observed["triage_display"] is True
  1014. # No chat/command output ingested: chat follows the content rule → hidden.
  1015. assert observed["chat_display"] is False
  1016. def test_maximize_transcript_fills_screen(server):
  1017. """Focus #transcript, press m: transcript maximized and fills the screen."""
  1018. pytest.importorskip("textual")
  1019. from textual.widgets import RichLog
  1020. from stt_daemon.tui.app import AssistantTUI
  1021. path, _service = server
  1022. app = AssistantTUI(path, triage_enabled=True)
  1023. observed: dict = {}
  1024. async def scenario():
  1025. async with app.run_test(size=(80, 40)) as pilot:
  1026. await pilot.pause()
  1027. app.query_one("#transcript", RichLog).focus()
  1028. await pilot.pause()
  1029. await pilot.press("m")
  1030. await pilot.pause()
  1031. observed["maximized_is_transcript"] = (
  1032. app.screen.maximized is app.query_one("#transcript")
  1033. )
  1034. observed["region"] = app.query_one("#transcript", RichLog).region
  1035. observed["screen_size"] = app.screen.size
  1036. await pilot.press("m")
  1037. await pilot.pause()
  1038. observed["restored"] = app.screen.maximized
  1039. asyncio.run(scenario())
  1040. print("transcript maximized: region=%s screen=%s"
  1041. % (observed["region"], observed["screen_size"]))
  1042. assert observed["maximized_is_transcript"] is True
  1043. region = observed["region"]
  1044. size = observed["screen_size"]
  1045. assert abs(region.width - size.width) <= 2, (region, size)
  1046. assert abs(region.height - size.height) <= 2, (region, size)
  1047. assert observed["restored"] is None
  1048. def test_escape_while_maximized_restores_panes(server):
  1049. """Escape minimizes (ESCAPE_TO_MINIMIZE) and _drain restores the hidden sibling."""
  1050. pytest.importorskip("textual")
  1051. from textual.widgets import RichLog
  1052. from stt_daemon.tui.app import AssistantTUI
  1053. path, _service = server
  1054. app = AssistantTUI(path, triage_enabled=True)
  1055. observed: dict = {}
  1056. async def scenario():
  1057. async with app.run_test(size=(80, 40)) as pilot:
  1058. await pilot.pause()
  1059. app.query_one("#triage", RichLog).focus()
  1060. await pilot.pause()
  1061. await pilot.press("m")
  1062. await pilot.pause()
  1063. assert app.screen.maximized is not None
  1064. await pilot.press("escape")
  1065. await pilot.pause()
  1066. # Let the 0.1s _drain timer run so the restore path executes.
  1067. for _ in range(10):
  1068. await pilot.pause()
  1069. await asyncio.sleep(0.05)
  1070. if app.screen.maximized is None:
  1071. break
  1072. observed["maximized"] = app.screen.maximized
  1073. observed["triage_display"] = app.query_one("#triage", RichLog).display
  1074. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1075. asyncio.run(scenario())
  1076. assert observed["maximized"] is None
  1077. assert observed["triage_display"] is True
  1078. # No chat/command output ingested: chat follows the content rule → hidden.
  1079. assert observed["chat_display"] is False
  1080. def test_maximize_chat_when_triage_disabled(server):
  1081. """triage_enabled=False: focus #chat, press m maximizes #main without crashing."""
  1082. pytest.importorskip("textual")
  1083. from textual.widgets import RichLog
  1084. from stt_daemon.tui.app import AssistantTUI
  1085. path, _service = server
  1086. app = AssistantTUI(path)
  1087. observed: dict = {}
  1088. async def scenario():
  1089. async with app.run_test(size=(80, 40)) as pilot:
  1090. await pilot.pause()
  1091. app._timer.stop() # keep the server status from re-hiding #chat
  1092. # Disabled: no #main/#triage. #chat starts hidden, so reveal it via
  1093. # the cycle, then focus it and press m to maximize #chat itself.
  1094. app._lower_view = "chat"
  1095. app.state.ingest({"type": "mode", "mode": "chat"})
  1096. app.state.ingest({"type": "chat_message", "role": "user", "text": "hi"})
  1097. app._render()
  1098. await pilot.pause()
  1099. app.query_one("#chat", RichLog).focus()
  1100. await pilot.pause()
  1101. await pilot.press("m")
  1102. await pilot.pause()
  1103. observed["maximized"] = app.screen.maximized
  1104. observed["chat"] = app.query_one("#chat", RichLog)
  1105. observed["region"] = app.query_one("#chat", RichLog).region
  1106. observed["screen_size"] = app.screen.size
  1107. await pilot.press("m")
  1108. await pilot.pause()
  1109. observed["restored"] = app.screen.maximized
  1110. asyncio.run(scenario())
  1111. print("chat maximized (disabled): region=%s screen=%s"
  1112. % (observed["region"], observed["screen_size"]))
  1113. assert observed["maximized"] is observed["chat"]
  1114. assert observed["restored"] is None
  1115. def test_maximize_chat_keeps_chat_input_at_bottom(server):
  1116. """Maximizing the conversation keeps only #chat-input, docked at the bottom."""
  1117. pytest.importorskip("textual")
  1118. from textual.widgets import Input, RichLog
  1119. from stt_daemon.tui.app import AssistantTUI
  1120. path, _service = server
  1121. app = AssistantTUI(path, triage_enabled=True)
  1122. observed: dict = {}
  1123. async def scenario():
  1124. async with app.run_test(size=(80, 40)) as pilot:
  1125. await pilot.pause()
  1126. app._timer.stop()
  1127. app._drain()
  1128. app._lower_view = "chat"
  1129. app.state.ingest({"type": "mode", "mode": "chat"})
  1130. app.state.ingest({"type": "chat_message", "role": "user", "text": "hi"})
  1131. app._render()
  1132. await pilot.pause()
  1133. app.query_one("#chat", RichLog).focus()
  1134. await pilot.pause()
  1135. await pilot.press("m")
  1136. await pilot.pause()
  1137. chat = app.query_one("#chat", RichLog)
  1138. chat_input = app.query_one("#chat-input", Input)
  1139. command = app.query_one("#command", Input)
  1140. observed["allow"] = app.ALLOW_IN_MAXIMIZED_VIEW
  1141. observed["chat_input_display"] = chat_input.display
  1142. observed["command_display"] = command.display
  1143. observed["chat_region"] = chat.region
  1144. observed["input_region"] = chat_input.region
  1145. observed["input_below_chat"] = chat_input.region.y > chat.region.y
  1146. observed["input_bottom"] = (
  1147. chat_input.region.y + chat_input.region.height
  1148. >= app.screen.size.height - 1
  1149. )
  1150. await pilot.press("m")
  1151. await pilot.pause()
  1152. observed["restored_allow"] = app.ALLOW_IN_MAXIMIZED_VIEW
  1153. observed["restored_command"] = command.display
  1154. observed["restored_chat_input"] = chat_input.display
  1155. asyncio.run(scenario())
  1156. assert observed["allow"] == "#inputs"
  1157. assert observed["chat_input_display"] is True
  1158. assert observed["command_display"] is False
  1159. assert observed["input_below_chat"] is True, observed
  1160. assert observed["input_bottom"] is True
  1161. assert observed["restored_allow"] == ".__never__"
  1162. assert observed["restored_command"] is True
  1163. assert observed["restored_chat_input"] is True
  1164. def test_maximize_output_keeps_command_input_at_bottom(server):
  1165. """Maximizing the command output keeps only #command, docked at the bottom."""
  1166. pytest.importorskip("textual")
  1167. from textual.widgets import Input, RichLog
  1168. from stt_daemon.tui.app import AssistantTUI
  1169. path, _service = server
  1170. app = AssistantTUI(path, triage_enabled=True)
  1171. observed: dict = {}
  1172. async def scenario():
  1173. async with app.run_test(size=(80, 40)) as pilot:
  1174. await pilot.pause()
  1175. app._timer.stop()
  1176. app._drain()
  1177. app._lower_view = "output"
  1178. app.state.ingest(
  1179. {"type": "tool_result", "tool": "get_datetime", "ok": True, "result": "now"}
  1180. )
  1181. app._render()
  1182. await pilot.pause()
  1183. app.query_one("#output", RichLog).focus()
  1184. await pilot.pause()
  1185. await pilot.press("m")
  1186. await pilot.pause()
  1187. output = app.query_one("#output", RichLog)
  1188. command = app.query_one("#command", Input)
  1189. chat_input = app.query_one("#chat-input", Input)
  1190. observed["allow"] = app.ALLOW_IN_MAXIMIZED_VIEW
  1191. observed["command_display"] = command.display
  1192. observed["chat_input_display"] = chat_input.display
  1193. observed["input_below_output"] = command.region.y > output.region.y
  1194. observed["input_bottom"] = (
  1195. command.region.y + command.region.height >= app.screen.size.height - 1
  1196. )
  1197. await pilot.press("m")
  1198. await pilot.pause()
  1199. observed["restored_allow"] = app.ALLOW_IN_MAXIMIZED_VIEW
  1200. observed["restored_command"] = command.display
  1201. observed["restored_chat_input"] = chat_input.display
  1202. asyncio.run(scenario())
  1203. assert observed["allow"] == "#inputs"
  1204. assert observed["command_display"] is True
  1205. assert observed["chat_input_display"] is False
  1206. assert observed["input_below_output"] is True, observed
  1207. assert observed["input_bottom"] is True
  1208. assert observed["restored_allow"] == ".__never__"
  1209. assert observed["restored_command"] is True
  1210. assert observed["restored_chat_input"] is True
  1211. def test_tab_reaches_docked_input_when_maximized(server):
  1212. """Tab moves focus between the maximized pane and its docked input."""
  1213. pytest.importorskip("textual")
  1214. from textual.widgets import RichLog
  1215. from stt_daemon.tui.app import AssistantTUI
  1216. path, _service = server
  1217. app = AssistantTUI(path, triage_enabled=True)
  1218. observed: dict = {}
  1219. async def scenario():
  1220. async with app.run_test(size=(80, 40)) as pilot:
  1221. await pilot.pause()
  1222. app._timer.stop()
  1223. app._drain()
  1224. app._lower_view = "chat"
  1225. app.state.ingest({"type": "mode", "mode": "chat"})
  1226. app.state.ingest({"type": "chat_message", "role": "user", "text": "hi"})
  1227. app._render()
  1228. await pilot.pause()
  1229. app.query_one("#chat", RichLog).focus()
  1230. await pilot.pause()
  1231. await pilot.press("m")
  1232. await pilot.pause()
  1233. await pilot.press("tab")
  1234. await pilot.pause()
  1235. observed["chat_to_input"] = app.focused.id if app.focused else None
  1236. await pilot.press("tab")
  1237. await pilot.pause()
  1238. observed["chat_back"] = app.focused.id if app.focused else None
  1239. await pilot.press("m") # restore
  1240. await pilot.pause()
  1241. app._lower_view = "output"
  1242. app.state.ingest(
  1243. {"type": "tool_result", "tool": "get_datetime", "ok": True, "result": "now"}
  1244. )
  1245. app._render()
  1246. await pilot.pause()
  1247. app.query_one("#output", RichLog).focus()
  1248. await pilot.pause()
  1249. await pilot.press("m")
  1250. await pilot.pause()
  1251. await pilot.press("tab")
  1252. await pilot.pause()
  1253. observed["output_to_input"] = app.focused.id if app.focused else None
  1254. asyncio.run(scenario())
  1255. assert observed["chat_to_input"] == "chat-input"
  1256. assert observed["chat_back"] == "chat"
  1257. assert observed["output_to_input"] == "command"
  1258. def test_footer_hidden_while_maximized(server):
  1259. """ALLOW_IN_MAXIMIZED_VIEW hides the Footer while a pane is maximized."""
  1260. pytest.importorskip("textual")
  1261. from textual.widgets import Footer, RichLog
  1262. from stt_daemon.tui.app import AssistantTUI
  1263. path, _service = server
  1264. app = AssistantTUI(path, triage_enabled=True)
  1265. observed: dict = {}
  1266. async def scenario():
  1267. async with app.run_test(size=(80, 40)) as pilot:
  1268. await pilot.pause()
  1269. app.query_one("#triage", RichLog).focus()
  1270. await pilot.pause()
  1271. await pilot.press("m")
  1272. await pilot.pause()
  1273. observed["maximized"] = app.screen.maximized
  1274. observed["footer_region"] = app.query_one(Footer).region
  1275. await pilot.press("m")
  1276. await pilot.pause()
  1277. asyncio.run(scenario())
  1278. assert observed["maximized"] is not None
  1279. footer_region = observed["footer_region"]
  1280. assert footer_region.height == 0 or footer_region.width == 0, observed
  1281. def test_question_mark_key_toggles_help_panel(server):
  1282. pytest.importorskip("textual")
  1283. from textual.widgets import HelpPanel
  1284. from stt_daemon.tui.app import AssistantTUI
  1285. path, _service = server
  1286. app = AssistantTUI(path)
  1287. observed: dict = {}
  1288. async def scenario():
  1289. async with app.run_test() as pilot:
  1290. await pilot.pause()
  1291. assert list(app.screen.query(HelpPanel)) == []
  1292. await pilot.press("question_mark")
  1293. await pilot.pause()
  1294. observed["shown"] = list(app.screen.query(HelpPanel)) != []
  1295. app.screen.query_one(HelpPanel) # must succeed while shown
  1296. await pilot.press("question_mark")
  1297. await pilot.pause()
  1298. observed["hidden"] = list(app.screen.query(HelpPanel)) == []
  1299. asyncio.run(scenario())
  1300. assert observed["shown"] is True, "? did not mount HelpPanel"
  1301. assert observed["hidden"] is True, "second ? did not remove HelpPanel"
  1302. def test_app_bindings_list():
  1303. """BINDINGS: 8 visible footer entries; hidden ones after; no h binding."""
  1304. pytest.importorskip("textual")
  1305. from stt_daemon.tui.app import AssistantTUI
  1306. pairs = [(b.key, b.description) for b in AssistantTUI.BINDINGS]
  1307. assert ("ctrl+r", "execute") in pairs
  1308. assert ("m", "maximize pane") in pairs
  1309. assert ("question_mark", "help") in pairs
  1310. assert ("ctrl+s", "save screenshot") in pairs
  1311. assert ("a", "arm command") in pairs
  1312. assert ("escape", "cancel") in pairs
  1313. assert ("e", "edit command") in pairs
  1314. assert ("t", "cycle pane") in pairs
  1315. assert ("s", "questions view") in pairs
  1316. assert ("c", "clear") in pairs
  1317. assert ("q", "quit") in pairs
  1318. assert ("ctrl+p", "instructions") in pairs
  1319. assert not any(key == "h" for key, _ in pairs)
  1320. assert not any(key == "ctrl+m" for key, _ in pairs)
  1321. assert not any(key == "ctrl+h" for key, _ in pairs)
  1322. assert not any(key == "enter" for key, _ in pairs)
  1323. assert not any(key == "ctrl+k" for key, _ in pairs)
  1324. by_key = {b.key: b for b in AssistantTUI.BINDINGS}
  1325. assert by_key["question_mark"].show is True
  1326. assert by_key["s"].show is True
  1327. assert by_key["m"].show is False
  1328. assert by_key["c"].show is False
  1329. assert by_key["ctrl+s"].show is False
  1330. assert by_key["ctrl+p"].show is False
  1331. # Visible eight first, in footer order.
  1332. visible = [(b.key, b.description) for b in AssistantTUI.BINDINGS if b.show]
  1333. assert visible == [
  1334. ("a", "arm command"),
  1335. ("ctrl+r", "execute"),
  1336. ("escape", "cancel"),
  1337. ("e", "edit command"),
  1338. ("t", "cycle pane"),
  1339. ("s", "questions view"),
  1340. ("question_mark", "help"),
  1341. ("q", "quit"),
  1342. ]
  1343. assert by_key["ctrl+p"].priority is True
  1344. def test_footer_shows_ordered_entries(server):
  1345. """Left list is the 8 visible bindings (? for help); instructions only right-aligned."""
  1346. pytest.importorskip("textual")
  1347. from textual.widgets import Footer
  1348. from textual.widgets._footer import FooterKey
  1349. from stt_daemon.tui.app import AssistantTUI
  1350. path, _service = server
  1351. app = AssistantTUI(path)
  1352. observed: dict = {}
  1353. async def scenario():
  1354. async with app.run_test() as pilot:
  1355. await pilot.pause()
  1356. shown = [
  1357. (b.binding.key, b.binding.description)
  1358. for b in app.screen.active_bindings.values()
  1359. if b.binding.show
  1360. ]
  1361. observed["shown"] = shown
  1362. footer = app.query_one(Footer)
  1363. keys = list(footer.query(FooterKey))
  1364. observed["keys"] = [
  1365. (k.key, k.key_display, k.description, k.action, set(k.classes))
  1366. for k in keys
  1367. ]
  1368. asyncio.run(scenario())
  1369. expected = [
  1370. ("a", "arm command"),
  1371. ("ctrl+r", "execute"),
  1372. ("escape", "cancel"),
  1373. ("e", "edit command"),
  1374. ("t", "cycle pane"),
  1375. ("s", "questions view"),
  1376. ("question_mark", "help"),
  1377. ("q", "quit"),
  1378. ]
  1379. assert observed["shown"] == expected, observed["shown"]
  1380. # Help advertises as "?" in the footer.
  1381. assert app.get_key_display(
  1382. next(b for b in AssistantTUI.BINDINGS if b.key == "question_mark")
  1383. ) == "?"
  1384. # The composed Footer: exactly one "instructions" entry and it is the
  1385. # right-aligned command-palette key; no left duplicate exists.
  1386. instructions = [k for k in observed["keys"] if k[2] == "instructions"]
  1387. assert len(instructions) == 1, observed["keys"]
  1388. key, key_display, _desc, action, classes = instructions[0]
  1389. assert action == "command_palette", instructions
  1390. assert "-command-palette" in classes, instructions
  1391. assert key == "ctrl+p", instructions
  1392. non_palette = [k for k in observed["keys"] if "-command-palette" not in k[4]]
  1393. assert not any(k[2] == "instructions" for k in non_palette), observed["keys"]
  1394. assert not any(k[3] == "command_palette" for k in non_palette), observed["keys"]
  1395. def test_ctrl_p_opens_command_palette(server):
  1396. """ctrl+p still opens the palette; its binding description is 'instructions'."""
  1397. pytest.importorskip("textual")
  1398. from textual.command import CommandPalette
  1399. from stt_daemon.tui.app import AssistantTUI
  1400. path, _service = server
  1401. app = AssistantTUI(path)
  1402. observed: dict = {}
  1403. async def scenario():
  1404. async with app.run_test() as pilot:
  1405. await pilot.pause()
  1406. await pilot.press("ctrl+p")
  1407. await pilot.pause()
  1408. await pilot.pause()
  1409. observed["is_palette"] = isinstance(app.screen, CommandPalette)
  1410. observed["stack"] = [type(s).__name__ for s in app.screen_stack]
  1411. asyncio.run(scenario())
  1412. palette_binding = next(b for b in AssistantTUI.BINDINGS if b.key == "ctrl+p")
  1413. assert palette_binding.description == "instructions"
  1414. assert observed["is_palette"], "ctrl+p did not open the command palette: %s" % (
  1415. observed["stack"],
  1416. )
  1417. def test_question_mark_toggles_help_panel(server):
  1418. """? toggles the help panel and is advertised in the left footer list."""
  1419. pytest.importorskip("textual")
  1420. from textual.widgets import HelpPanel
  1421. from stt_daemon.tui.app import AssistantTUI
  1422. path, _service = server
  1423. app = AssistantTUI(path)
  1424. observed: dict = {}
  1425. async def scenario():
  1426. async with app.run_test() as pilot:
  1427. await pilot.pause()
  1428. assert list(app.screen.query(HelpPanel)) == []
  1429. await pilot.press("?")
  1430. await pilot.pause()
  1431. observed["shown"] = list(app.screen.query(HelpPanel)) != []
  1432. await pilot.press("?")
  1433. await pilot.pause()
  1434. observed["hidden"] = list(app.screen.query(HelpPanel)) == []
  1435. asyncio.run(scenario())
  1436. assert observed["shown"] is True, "? did not mount HelpPanel"
  1437. assert observed["hidden"] is True, "second ? did not remove HelpPanel"
  1438. def test_plain_m_maximizes_triage_pane(server):
  1439. pytest.importorskip("textual")
  1440. from stt_daemon.tui.app import AssistantTUI
  1441. from textual.widgets import RichLog
  1442. path, _service = server
  1443. app = AssistantTUI(path, triage_enabled=True)
  1444. async def scenario():
  1445. async with app.run_test(size=(80, 40)) as pilot:
  1446. await pilot.pause()
  1447. app.query_one("#triage", RichLog).focus()
  1448. await pilot.pause()
  1449. await pilot.press("m")
  1450. await pilot.pause()
  1451. assert app.screen.maximized is app.query_one("#main")
  1452. await pilot.press("m")
  1453. await pilot.pause()
  1454. assert app.screen.maximized is None
  1455. assert app.query_one("#triage", RichLog).display is True
  1456. # No chat/command output ingested: chat follows the content rule → hidden.
  1457. assert app.query_one("#chat", RichLog).display is False
  1458. asyncio.run(scenario())
  1459. def test_screenshot_saves_svg(server, tmp_path, monkeypatch):
  1460. pytest.importorskip("textual")
  1461. import glob
  1462. from stt_daemon.tui.app import AssistantTUI
  1463. monkeypatch.chdir(tmp_path)
  1464. path, _service = server
  1465. app = AssistantTUI(path)
  1466. async def scenario():
  1467. async with app.run_test() as pilot:
  1468. await pilot.pause()
  1469. await pilot.press("ctrl+s")
  1470. await pilot.pause()
  1471. await pilot.pause()
  1472. asyncio.run(scenario())
  1473. out_dir = tmp_path / "screenshots"
  1474. assert out_dir.is_dir(), "screenshots/ not created in %s" % tmp_path
  1475. files = glob.glob(str(out_dir / "stt-tui-*.svg"))
  1476. assert files, "no stt-tui-*.svg found in %s" % out_dir
  1477. assert os.path.getsize(files[0]) > 0
  1478. assert glob.glob(str(tmp_path / "stt-tui-*.svg")) == [], \
  1479. "screenshot leaked into %s instead of screenshots/" % tmp_path
  1480. def test_screenshot_saves_into_session_dir(server, tmp_path, monkeypatch):
  1481. pytest.importorskip("textual")
  1482. import glob
  1483. from stt_daemon.tui.app import AssistantTUI
  1484. monkeypatch.chdir(tmp_path)
  1485. path, _service = server
  1486. app = AssistantTUI(path)
  1487. app.state.session_dir = "transcripts/x"
  1488. async def scenario():
  1489. async with app.run_test() as pilot:
  1490. await pilot.pause()
  1491. await pilot.press("ctrl+s")
  1492. await pilot.pause()
  1493. await pilot.pause()
  1494. asyncio.run(scenario())
  1495. out_dir = tmp_path / "transcripts" / "x" / "screenshots"
  1496. assert out_dir.is_dir(), "session screenshots/ not created in %s" % out_dir
  1497. files = glob.glob(str(out_dir / "stt-tui-*.svg"))
  1498. assert files, "no stt-tui-*.svg found in %s" % out_dir
  1499. assert os.path.getsize(files[0]) > 0
  1500. assert glob.glob(str(tmp_path / "screenshots" / "stt-tui-*.svg")) == [], \
  1501. "screenshot leaked into screenshots/ instead of the session dir"
  1502. def test_chat_hidden_by_default_triage_fills_main(server):
  1503. """Fresh state: #chat hidden, #triage fills the whole #main width."""
  1504. pytest.importorskip("textual")
  1505. from textual.containers import Horizontal
  1506. from textual.widgets import RichLog
  1507. from stt_daemon.tui.app import AssistantTUI
  1508. path, _service = server
  1509. app = AssistantTUI(path, triage_enabled=True)
  1510. observed: dict = {}
  1511. async def scenario():
  1512. async with app.run_test(size=(80, 40)) as pilot:
  1513. await pilot.pause()
  1514. app._timer.stop() # no background drain: server status must not clobber state
  1515. app._drain()
  1516. app._render()
  1517. await pilot.pause()
  1518. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1519. observed["triage_display"] = app.query_one("#triage", RichLog).display
  1520. observed["main_region"] = app.query_one("#main", Horizontal).region
  1521. observed["triage_region"] = app.query_one("#triage", RichLog).region
  1522. asyncio.run(scenario())
  1523. print("hidden: main=%s triage=%s" % (observed["main_region"], observed["triage_region"]))
  1524. assert observed["chat_display"] is False
  1525. assert observed["triage_display"] is True
  1526. assert (
  1527. abs(observed["triage_region"].width - observed["main_region"].width) <= 2
  1528. ), (observed["triage_region"], observed["main_region"])
  1529. def test_chat_mode_shows_chat_and_restores_split(server):
  1530. """mode=chat → #chat visible, triage back to ~1/3 width."""
  1531. pytest.importorskip("textual")
  1532. from textual.containers import Horizontal
  1533. from textual.widgets import RichLog
  1534. from stt_daemon.tui.app import AssistantTUI
  1535. path, _service = server
  1536. app = AssistantTUI(path, triage_enabled=True)
  1537. observed: dict = {}
  1538. async def scenario():
  1539. async with app.run_test(size=(80, 40)) as pilot:
  1540. await pilot.pause()
  1541. app._timer.stop() # no background drain: server status must not clobber state
  1542. app._drain()
  1543. app._lower_view = "chat"
  1544. app.state.ingest({"type": "mode", "mode": "chat"})
  1545. app._render()
  1546. await pilot.pause()
  1547. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1548. observed["main_region"] = app.query_one("#main", Horizontal).region
  1549. observed["triage_region"] = app.query_one("#triage", RichLog).region
  1550. observed["chat_region"] = app.query_one("#chat", RichLog).region
  1551. asyncio.run(scenario())
  1552. print(
  1553. "shown: main=%s triage=%s chat=%s"
  1554. % (observed["main_region"], observed["triage_region"], observed["chat_region"])
  1555. )
  1556. assert observed["chat_display"] is True
  1557. main_w = observed["main_region"].width
  1558. assert abs(observed["triage_region"].width / main_w - 1 / 3) < 0.08, observed
  1559. assert abs(observed["chat_region"].width / main_w - 2 / 3) < 0.08, observed
  1560. def test_tool_result_shows_output_pane(server):
  1561. """Command output (tool_result) goes to #output, leaving #chat hidden."""
  1562. pytest.importorskip("textual")
  1563. from textual.widgets import RichLog
  1564. from stt_daemon.tui.app import AssistantTUI
  1565. path, _service = server
  1566. app = AssistantTUI(path, triage_enabled=True)
  1567. observed: dict = {}
  1568. async def scenario():
  1569. async with app.run_test(size=(80, 40)) as pilot:
  1570. await pilot.pause()
  1571. app._timer.stop() # no background drain: server status must not clobber state
  1572. app._drain()
  1573. app._lower_view = "output"
  1574. app.state.ingest(
  1575. {
  1576. "type": "tool_result",
  1577. "tool": "get_datetime",
  1578. "ok": True,
  1579. "result": "2026-09-21",
  1580. }
  1581. )
  1582. app._render()
  1583. await pilot.pause()
  1584. observed["output_display"] = app.query_one("#output", RichLog).display
  1585. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1586. asyncio.run(scenario())
  1587. assert observed["output_display"] is True
  1588. assert observed["chat_display"] is False
  1589. def test_error_event_shows_output_pane(server):
  1590. """An error event goes to #output, leaving #chat hidden."""
  1591. pytest.importorskip("textual")
  1592. from textual.widgets import RichLog
  1593. from stt_daemon.tui.app import AssistantTUI
  1594. path, _service = server
  1595. app = AssistantTUI(path, triage_enabled=True)
  1596. observed: dict = {}
  1597. async def scenario():
  1598. async with app.run_test(size=(80, 40)) as pilot:
  1599. await pilot.pause()
  1600. app._timer.stop() # no background drain: server status must not clobber state
  1601. app._drain()
  1602. app._lower_view = "output"
  1603. app.state.ingest({"type": "error", "code": "boom", "message": "kaboom"})
  1604. app._render()
  1605. await pilot.pause()
  1606. observed["output_display"] = app.query_one("#output", RichLog).display
  1607. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1608. asyncio.run(scenario())
  1609. assert observed["output_display"] is True
  1610. assert observed["chat_display"] is False
  1611. def test_executing_mode_shows_output_pane(server):
  1612. """Assistant executing a command → #output visible, #chat hidden."""
  1613. pytest.importorskip("textual")
  1614. from textual.widgets import RichLog
  1615. from stt_daemon.tui.app import AssistantTUI
  1616. path, _service = server
  1617. app = AssistantTUI(path, triage_enabled=True)
  1618. observed: dict = {}
  1619. async def scenario():
  1620. async with app.run_test(size=(80, 40)) as pilot:
  1621. await pilot.pause()
  1622. app._timer.stop() # no background drain: server status must not clobber state
  1623. app._drain()
  1624. app._lower_view = "output"
  1625. app.state.ingest({"type": "mode", "mode": "executing"})
  1626. app._render()
  1627. await pilot.pause()
  1628. observed["output_display"] = app.query_one("#output", RichLog).display
  1629. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1630. asyncio.run(scenario())
  1631. assert observed["output_display"] is True
  1632. assert observed["chat_display"] is False
  1633. def test_cleared_hides_pane_empties_output_and_restores_full_width(server):
  1634. """cleared empties #output and hides it again, triage full width."""
  1635. pytest.importorskip("textual")
  1636. from textual.containers import Horizontal
  1637. from textual.widgets import RichLog
  1638. from stt_daemon.tui.app import AssistantTUI
  1639. path, _service = server
  1640. app = AssistantTUI(path, triage_enabled=True)
  1641. observed: dict = {}
  1642. async def scenario():
  1643. async with app.run_test(size=(80, 40)) as pilot:
  1644. await pilot.pause()
  1645. app._timer.stop() # no background drain: server status must not clobber state
  1646. app._drain()
  1647. app._lower_view = "output"
  1648. app.state.ingest(
  1649. {
  1650. "type": "tool_result",
  1651. "tool": "get_datetime",
  1652. "ok": True,
  1653. "result": "2026-09-21",
  1654. }
  1655. )
  1656. app._render()
  1657. await pilot.pause()
  1658. assert app.query_one("#output", RichLog).display is True
  1659. app.state.ingest({"type": "cleared"})
  1660. app._render()
  1661. await pilot.pause()
  1662. observed["empty_output"] = [
  1663. str(line) for line in app.query_one("#output", RichLog).lines
  1664. ]
  1665. observed["lower_view"] = app._lower_view
  1666. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1667. observed["output_display"] = app.query_one("#output", RichLog).display
  1668. observed["main_region"] = app.query_one("#main", Horizontal).region
  1669. observed["triage_region"] = app.query_one("#triage", RichLog).region
  1670. asyncio.run(scenario())
  1671. print(
  1672. "cleared: main=%s triage=%s"
  1673. % (observed["main_region"], observed["triage_region"])
  1674. )
  1675. assert observed["empty_output"] == []
  1676. assert observed["lower_view"] == "hidden"
  1677. assert observed["chat_display"] is False
  1678. assert observed["output_display"] is False
  1679. assert (
  1680. abs(observed["triage_region"].width - observed["main_region"].width) <= 2
  1681. ), (observed["triage_region"], observed["main_region"])
  1682. def test_cycle_lower_switches_panes(server):
  1683. """t cycles hidden -> #output -> #chat -> hidden when triage is disabled."""
  1684. pytest.importorskip("textual")
  1685. from textual.widgets import RichLog
  1686. from stt_daemon.tui.app import AssistantTUI
  1687. path, _service = server
  1688. app = AssistantTUI(path)
  1689. observed: dict = {}
  1690. def snap():
  1691. return (
  1692. app.query_one("#output", RichLog).display,
  1693. app.query_one("#chat", RichLog).display,
  1694. app.query_one("#transcript", RichLog).has_class("-grow"),
  1695. )
  1696. async def scenario():
  1697. async with app.run_test(size=(80, 40)) as pilot:
  1698. await pilot.pause()
  1699. app._timer.stop() # no background drain: server status must not clobber state
  1700. app._drain()
  1701. app._render()
  1702. await pilot.pause()
  1703. observed["hidden"] = snap()
  1704. app.action_cycle_lower()
  1705. app._render()
  1706. await pilot.pause()
  1707. observed["output"] = snap()
  1708. app.action_cycle_lower()
  1709. app._render()
  1710. await pilot.pause()
  1711. observed["chat"] = snap()
  1712. app.action_cycle_lower()
  1713. app._render()
  1714. await pilot.pause()
  1715. observed["hidden_again"] = snap()
  1716. asyncio.run(scenario())
  1717. assert observed["hidden"] == (False, False, True)
  1718. assert observed["output"] == (True, False, False)
  1719. assert observed["chat"] == (False, True, False)
  1720. assert observed["hidden_again"] == (False, False, True)
  1721. def test_cycle_lower_enters_and_exits_chat_mode(server):
  1722. """Selecting conversation sends chat_toggle on; leaving it toggles off but
  1723. keeps the rendered turns until an explicit clear."""
  1724. pytest.importorskip("textual")
  1725. from textual.widgets import RichLog
  1726. from stt_daemon.tui.app import AssistantTUI
  1727. path, _service = server
  1728. app = AssistantTUI(path)
  1729. sent: list[tuple] = []
  1730. observed: dict = {}
  1731. async def scenario():
  1732. async with app.run_test(size=(80, 40)) as pilot:
  1733. await pilot.pause()
  1734. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  1735. app._timer.stop()
  1736. app._drain()
  1737. app.action_cycle_lower() # hidden -> output
  1738. app.action_cycle_lower() # output -> chat
  1739. app._render()
  1740. await pilot.pause()
  1741. observed["after_enter"] = list(sent)
  1742. app.state.ingest({"type": "mode", "mode": "chat"})
  1743. app.state.ingest({"type": "chat_message", "role": "user", "text": "remember"})
  1744. app._render()
  1745. await pilot.pause()
  1746. app.action_cycle_lower() # chat -> hidden (mode is chat -> exits)
  1747. app._render()
  1748. await pilot.pause()
  1749. observed["after_exit"] = list(sent)
  1750. observed["chat_lines"] = [str(line) for line in app.query_one("#chat", RichLog).lines]
  1751. asyncio.run(scenario())
  1752. assert observed["after_enter"] == [("chat_toggle", {})]
  1753. assert observed["after_exit"] == [("chat_toggle", {}), ("chat_toggle", {})]
  1754. assert any("remember" in line for line in observed["chat_lines"])
  1755. def test_command_activity_reveals_output_pane(server):
  1756. """Arming, executing, and chatting: command modes force #output; chat does not."""
  1757. pytest.importorskip("textual")
  1758. from textual.widgets import RichLog
  1759. from stt_daemon.tui.app import AssistantTUI
  1760. path, _service = server
  1761. app = AssistantTUI(path, triage_enabled=True)
  1762. observed: dict = {}
  1763. async def scenario():
  1764. async with app.run_test(size=(80, 40)) as pilot:
  1765. await pilot.pause()
  1766. app._timer.stop()
  1767. app._drain()
  1768. await pilot.pause()
  1769. observed["hidden"] = app.query_one("#output", RichLog).display
  1770. app.state.ingest({"type": "mode", "mode": "command_armed"})
  1771. app._render()
  1772. await pilot.pause()
  1773. observed["armed"] = (
  1774. app._lower_view,
  1775. app.query_one("#output", RichLog).display,
  1776. app.query_one("#chat", RichLog).display,
  1777. )
  1778. app._lower_view = "hidden"
  1779. app.state.ingest({"type": "mode", "mode": "executing"})
  1780. app._render()
  1781. await pilot.pause()
  1782. observed["executing"] = (
  1783. app._lower_view,
  1784. app.query_one("#output", RichLog).display,
  1785. )
  1786. app._lower_view = "chat"
  1787. app.state.ingest({"type": "mode", "mode": "chat"})
  1788. app._render()
  1789. await pilot.pause()
  1790. observed["chat"] = (
  1791. app._lower_view,
  1792. app.query_one("#output", RichLog).display,
  1793. app.query_one("#chat", RichLog).display,
  1794. )
  1795. asyncio.run(scenario())
  1796. assert observed["hidden"] is False
  1797. assert observed["armed"] == ("output", True, False)
  1798. assert observed["executing"] == ("output", True)
  1799. assert observed["chat"] == ("chat", False, True)
  1800. def test_maximize_restore_with_output_keeps_output_visible(server):
  1801. """With ingested output, m then m restores with #output still visible."""
  1802. pytest.importorskip("textual")
  1803. from textual.widgets import RichLog
  1804. from stt_daemon.tui.app import AssistantTUI
  1805. path, _service = server
  1806. app = AssistantTUI(path, triage_enabled=True)
  1807. observed: dict = {}
  1808. async def scenario():
  1809. async with app.run_test(size=(80, 40)) as pilot:
  1810. await pilot.pause()
  1811. app._timer.stop() # no background drain: server status must not clobber state
  1812. app._drain()
  1813. app._lower_view = "output"
  1814. app.state.ingest(
  1815. {
  1816. "type": "tool_result",
  1817. "tool": "get_datetime",
  1818. "ok": True,
  1819. "result": "2026-09-21",
  1820. }
  1821. )
  1822. app._render()
  1823. await pilot.pause()
  1824. assert app.query_one("#output", RichLog).display is True
  1825. app.query_one("#triage", RichLog).focus()
  1826. await pilot.pause()
  1827. await pilot.press("m")
  1828. await pilot.pause()
  1829. assert app.screen.maximized is not None
  1830. await pilot.press("m")
  1831. await pilot.pause()
  1832. observed["maximized"] = app.screen.maximized
  1833. observed["triage_display"] = app.query_one("#triage", RichLog).display
  1834. observed["output_display"] = app.query_one("#output", RichLog).display
  1835. asyncio.run(scenario())
  1836. assert observed["maximized"] is None
  1837. assert observed["triage_display"] is True
  1838. assert observed["output_display"] is True
  1839. def test_transcript_pane_keeps_updating_past_cap(server):
  1840. """Regression: past MAX_TRANSCRIPTS the running log must still append."""
  1841. pytest.importorskip("textual")
  1842. from textual.widgets import RichLog
  1843. from stt_daemon.tui.app import AssistantTUI
  1844. from stt_daemon.tui.state import MAX_TRANSCRIPTS
  1845. path, _service = server
  1846. app = AssistantTUI(path)
  1847. observed: dict = {}
  1848. async def scenario():
  1849. async with app.run_test(size=(80, 40)) as pilot:
  1850. await pilot.pause()
  1851. app._timer.stop() # no background drain: server status must not clobber state
  1852. app._drain()
  1853. for i in range(MAX_TRANSCRIPTS + 5):
  1854. app.state.ingest({"type": "transcript", "text": f"t{i}", "lang": "en"})
  1855. app._render()
  1856. await pilot.pause()
  1857. app.state.ingest({"type": "transcript", "text": "after cap", "lang": "en"})
  1858. app._render()
  1859. await pilot.pause()
  1860. log = app.query_one("#transcript", RichLog)
  1861. observed["lines"] = [str(line) for line in log.lines]
  1862. asyncio.run(scenario())
  1863. assert any("after cap" in line for line in observed["lines"])
  1864. assert len(observed["lines"]) > MAX_TRANSCRIPTS
  1865. def _questions_payload():
  1866. return {
  1867. "topic": {
  1868. "type": "choice",
  1869. "instructions": "What is the main theme?",
  1870. "criteria": {"planning": "roadmap or prioritization"},
  1871. }
  1872. }
  1873. def _rendered_lines(log):
  1874. return [line.text for line in log.lines]
  1875. def _ingest_triage_signals(app):
  1876. app.state.ingest(
  1877. {
  1878. "type": "triage",
  1879. "stage": "signals",
  1880. "triage": {
  1881. "order": ["topic"],
  1882. "items": {
  1883. "topic": {
  1884. "kind": "choice",
  1885. "choice": "planning",
  1886. "answer_confidence": 0.91,
  1887. }
  1888. },
  1889. },
  1890. }
  1891. )
  1892. app.state.ingest(
  1893. {
  1894. "type": "status",
  1895. "triage_state": "ok",
  1896. "triage_reason": "",
  1897. "questions": _questions_payload(),
  1898. }
  1899. )
  1900. def test_s_key_swaps_triage_pane_to_questions_view(server):
  1901. """Press s: #triage border flips to questions and renders the structured blocks."""
  1902. pytest.importorskip("textual")
  1903. from textual.widgets import RichLog
  1904. from stt_daemon.tui.app import AssistantTUI
  1905. path, _service = server
  1906. app = AssistantTUI(path, triage_enabled=True)
  1907. observed: dict = {}
  1908. async def scenario():
  1909. async with app.run_test() as pilot:
  1910. await pilot.pause()
  1911. app._timer.stop() # no background drain: server status must not clobber state
  1912. app._drain()
  1913. _ingest_triage_signals(app)
  1914. app._render()
  1915. await pilot.pause()
  1916. observed["default_title"] = app.query_one("#triage", RichLog).border_title
  1917. observed["default_lines"] = _rendered_lines(app.query_one("#triage", RichLog))
  1918. await pilot.press("s")
  1919. await pilot.pause()
  1920. observed["questions_title"] = app.query_one("#triage", RichLog).border_title
  1921. observed["questions_lines"] = _rendered_lines(app.query_one("#triage", RichLog))
  1922. asyncio.run(scenario())
  1923. assert observed["default_title"] == "triage \\[inf 0]" # markup: '[' is escaped
  1924. assert any("topic: planning (0.91)" in line for line in observed["default_lines"])
  1925. assert observed["questions_title"] == "questions"
  1926. rendered = "\n".join(observed["questions_lines"])
  1927. assert "topic [choice]" in rendered
  1928. assert "What is the main theme?" in rendered
  1929. assert "planning — roadmap or prioritization" in rendered
  1930. assert "topic: planning" not in rendered
  1931. def test_s_key_again_restores_triage_view(server):
  1932. """Second s: border flips back to triage and the signals view is rewritten."""
  1933. pytest.importorskip("textual")
  1934. from textual.widgets import RichLog
  1935. from stt_daemon.tui.app import AssistantTUI
  1936. path, _service = server
  1937. app = AssistantTUI(path, triage_enabled=True)
  1938. observed: dict = {}
  1939. async def scenario():
  1940. async with app.run_test() as pilot:
  1941. await pilot.pause()
  1942. app._timer.stop() # no background drain: server status must not clobber state
  1943. app._drain()
  1944. _ingest_triage_signals(app)
  1945. app._render()
  1946. await pilot.pause()
  1947. await pilot.press("s")
  1948. await pilot.pause()
  1949. observed["mid_title"] = app.query_one("#triage", RichLog).border_title
  1950. await pilot.press("s")
  1951. await pilot.pause()
  1952. observed["triage_title"] = app.query_one("#triage", RichLog).border_title
  1953. observed["triage_lines"] = _rendered_lines(app.query_one("#triage", RichLog))
  1954. asyncio.run(scenario())
  1955. assert observed["mid_title"] == "questions"
  1956. assert observed["triage_title"] == "triage \\[inf 0]" # markup: '[' is escaped
  1957. rendered = "\n".join(observed["triage_lines"])
  1958. assert "topic: planning (0.91)" in rendered
  1959. assert "What is the main theme?" not in rendered
  1960. def test_triage_brief_title_mirrors_inference_depth_and_busy(server):
  1961. """Brief view: #triage title carries [inf N] and the busy marker, exactly."""
  1962. pytest.importorskip("textual")
  1963. from textual.widgets import RichLog
  1964. from stt_daemon.tui.app import AssistantTUI
  1965. path, _service = server
  1966. app = AssistantTUI(path, triage_enabled=True)
  1967. observed: dict = {}
  1968. async def scenario():
  1969. async with app.run_test() as pilot:
  1970. await pilot.pause()
  1971. app._timer.stop() # no background drain: server status must not clobber state
  1972. app._drain()
  1973. app.state.ingest(
  1974. {"type": "heartbeat", "inference_depth": 3, "inference_in_flight": False}
  1975. )
  1976. app._render()
  1977. await pilot.pause()
  1978. observed["idle"] = app.query_one("#triage", RichLog).border_title
  1979. app.state.ingest(
  1980. {"type": "heartbeat", "inference_depth": 7, "inference_in_flight": True}
  1981. )
  1982. app._render()
  1983. await pilot.pause()
  1984. observed["busy"] = app.query_one("#triage", RichLog).border_title
  1985. asyncio.run(scenario())
  1986. # border_title round-trips as console markup, so '[' reads back as '\['.
  1987. assert observed["idle"] == "triage \\[inf 3]"
  1988. assert observed["busy"] == "triage \\[inf 7 · busy]"
  1989. def test_questions_view_title_has_no_inference_suffix(server):
  1990. """Questions view: title is exactly 'questions'; toggling back restores the suffix."""
  1991. pytest.importorskip("textual")
  1992. from textual.widgets import RichLog
  1993. from stt_daemon.tui.app import AssistantTUI
  1994. path, _service = server
  1995. app = AssistantTUI(path, triage_enabled=True)
  1996. observed: dict = {}
  1997. async def scenario():
  1998. async with app.run_test() as pilot:
  1999. await pilot.pause()
  2000. app._timer.stop()
  2001. app._drain()
  2002. app.state.ingest(
  2003. {"type": "heartbeat", "inference_depth": 5, "inference_in_flight": True}
  2004. )
  2005. app._render()
  2006. await pilot.pause()
  2007. observed["brief"] = app.query_one("#triage", RichLog).border_title
  2008. await pilot.press("s")
  2009. await pilot.pause()
  2010. observed["questions"] = app.query_one("#triage", RichLog).border_title
  2011. await pilot.press("s")
  2012. await pilot.pause()
  2013. observed["restored"] = app.query_one("#triage", RichLog).border_title
  2014. asyncio.run(scenario())
  2015. assert observed["brief"] == "triage \\[inf 5 · busy]"
  2016. assert observed["questions"] == "questions"
  2017. assert "inf" not in observed["questions"]
  2018. assert "busy" not in observed["questions"]
  2019. # No stale plain title: the brief view comes back fully suffixed.
  2020. assert observed["restored"] == "triage \\[inf 5 · busy]"
  2021. def test_triage_disabled_heartbeat_leaves_no_triage_widget(server):
  2022. """triage_enabled=False: depths update #chat only and never create a #triage pane."""
  2023. pytest.importorskip("textual")
  2024. from textual.widgets import RichLog
  2025. from stt_daemon.tui.app import AssistantTUI
  2026. path, _service = server
  2027. app = AssistantTUI(path)
  2028. observed: dict = {}
  2029. async def scenario():
  2030. async with app.run_test() as pilot:
  2031. await pilot.pause()
  2032. app._timer.stop()
  2033. app._drain()
  2034. app.state.ingest(
  2035. {"type": "heartbeat", "inference_depth": 9, "inference_in_flight": True}
  2036. )
  2037. app._render()
  2038. await pilot.pause()
  2039. observed["has_triage"] = bool(app.query("#triage"))
  2040. observed["chat"] = app.query_one("#chat", RichLog).border_title
  2041. asyncio.run(scenario())
  2042. assert observed["has_triage"] is False
  2043. assert observed["chat"] == "conversation \\[inf 9 · busy]"
  2044. def test_s_key_is_noop_when_triage_disabled(server):
  2045. """triage_enabled=False: action_toggle_questions and s do nothing and never crash."""
  2046. pytest.importorskip("textual")
  2047. from stt_daemon.tui.app import AssistantTUI
  2048. path, _service = server
  2049. app = AssistantTUI(path)
  2050. async def scenario():
  2051. async with app.run_test() as pilot:
  2052. await pilot.pause()
  2053. app.action_toggle_questions()
  2054. await pilot.pause()
  2055. assert app._show_questions is False
  2056. assert not app.query("#triage")
  2057. await pilot.press("s")
  2058. await pilot.pause()
  2059. assert app._show_questions is False
  2060. assert not app.query("#triage")
  2061. asyncio.run(scenario())
  2062. def test_status_event_questions_populate_questions_view(server):
  2063. """A status event carrying questions fills state and the toggled pane."""
  2064. pytest.importorskip("textual")
  2065. from textual.widgets import RichLog
  2066. from stt_daemon.tui.app import AssistantTUI
  2067. path, _service = server
  2068. app = AssistantTUI(path, triage_enabled=True)
  2069. observed: dict = {}
  2070. async def scenario():
  2071. async with app.run_test() as pilot:
  2072. await pilot.pause()
  2073. app._timer.stop() # no background drain: server status must not clobber state
  2074. app._drain()
  2075. observed["before_epoch"] = app.state.questions_epoch
  2076. app.state.ingest({"type": "status", "questions": _questions_payload()})
  2077. app._render()
  2078. await pilot.pause()
  2079. observed["questions"] = app.state.questions
  2080. observed["epoch"] = app.state.questions_epoch
  2081. await pilot.press("s")
  2082. await pilot.pause()
  2083. observed["lines"] = _rendered_lines(app.query_one("#triage", RichLog))
  2084. asyncio.run(scenario())
  2085. assert observed["questions"] == _questions_payload()
  2086. assert observed["epoch"] == observed["before_epoch"] + 1
  2087. assert any("topic [choice]" in line for line in observed["lines"])