test_tui_app.py 83 KB

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