test_tui_app.py 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505
  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_footer_hidden_while_maximized(server):
  1212. """ALLOW_IN_MAXIMIZED_VIEW hides the Footer while a pane is maximized."""
  1213. pytest.importorskip("textual")
  1214. from textual.widgets import Footer, 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.query_one("#triage", RichLog).focus()
  1223. await pilot.pause()
  1224. await pilot.press("m")
  1225. await pilot.pause()
  1226. observed["maximized"] = app.screen.maximized
  1227. observed["footer_region"] = app.query_one(Footer).region
  1228. await pilot.press("m")
  1229. await pilot.pause()
  1230. asyncio.run(scenario())
  1231. assert observed["maximized"] is not None
  1232. footer_region = observed["footer_region"]
  1233. assert footer_region.height == 0 or footer_region.width == 0, observed
  1234. def test_question_mark_key_toggles_help_panel(server):
  1235. pytest.importorskip("textual")
  1236. from textual.widgets import HelpPanel
  1237. from stt_daemon.tui.app import AssistantTUI
  1238. path, _service = server
  1239. app = AssistantTUI(path)
  1240. observed: dict = {}
  1241. async def scenario():
  1242. async with app.run_test() as pilot:
  1243. await pilot.pause()
  1244. assert list(app.screen.query(HelpPanel)) == []
  1245. await pilot.press("question_mark")
  1246. await pilot.pause()
  1247. observed["shown"] = list(app.screen.query(HelpPanel)) != []
  1248. app.screen.query_one(HelpPanel) # must succeed while shown
  1249. await pilot.press("question_mark")
  1250. await pilot.pause()
  1251. observed["hidden"] = list(app.screen.query(HelpPanel)) == []
  1252. asyncio.run(scenario())
  1253. assert observed["shown"] is True, "? did not mount HelpPanel"
  1254. assert observed["hidden"] is True, "second ? did not remove HelpPanel"
  1255. def test_app_bindings_list():
  1256. """BINDINGS: 8 visible footer entries; hidden ones after; no h binding."""
  1257. pytest.importorskip("textual")
  1258. from stt_daemon.tui.app import AssistantTUI
  1259. pairs = [(b.key, b.description) for b in AssistantTUI.BINDINGS]
  1260. assert ("ctrl+r", "execute") in pairs
  1261. assert ("m", "maximize pane") in pairs
  1262. assert ("question_mark", "help") in pairs
  1263. assert ("ctrl+s", "save screenshot") in pairs
  1264. assert ("a", "arm command") in pairs
  1265. assert ("escape", "cancel") in pairs
  1266. assert ("e", "edit command") in pairs
  1267. assert ("t", "cycle pane") in pairs
  1268. assert ("s", "questions view") in pairs
  1269. assert ("c", "clear") in pairs
  1270. assert ("q", "quit") in pairs
  1271. assert ("ctrl+p", "instructions") in pairs
  1272. assert not any(key == "h" for key, _ in pairs)
  1273. assert not any(key == "ctrl+m" for key, _ in pairs)
  1274. assert not any(key == "ctrl+h" for key, _ in pairs)
  1275. assert not any(key == "enter" for key, _ in pairs)
  1276. assert not any(key == "ctrl+k" for key, _ in pairs)
  1277. by_key = {b.key: b for b in AssistantTUI.BINDINGS}
  1278. assert by_key["question_mark"].show is True
  1279. assert by_key["s"].show is True
  1280. assert by_key["m"].show is False
  1281. assert by_key["c"].show is False
  1282. assert by_key["ctrl+s"].show is False
  1283. assert by_key["ctrl+p"].show is False
  1284. # Visible eight first, in footer order.
  1285. visible = [(b.key, b.description) for b in AssistantTUI.BINDINGS if b.show]
  1286. assert visible == [
  1287. ("a", "arm command"),
  1288. ("ctrl+r", "execute"),
  1289. ("escape", "cancel"),
  1290. ("e", "edit command"),
  1291. ("t", "cycle pane"),
  1292. ("s", "questions view"),
  1293. ("question_mark", "help"),
  1294. ("q", "quit"),
  1295. ]
  1296. assert by_key["ctrl+p"].priority is True
  1297. def test_footer_shows_ordered_entries(server):
  1298. """Left list is the 8 visible bindings (? for help); instructions only right-aligned."""
  1299. pytest.importorskip("textual")
  1300. from textual.widgets import Footer
  1301. from textual.widgets._footer import FooterKey
  1302. from stt_daemon.tui.app import AssistantTUI
  1303. path, _service = server
  1304. app = AssistantTUI(path)
  1305. observed: dict = {}
  1306. async def scenario():
  1307. async with app.run_test() as pilot:
  1308. await pilot.pause()
  1309. shown = [
  1310. (b.binding.key, b.binding.description)
  1311. for b in app.screen.active_bindings.values()
  1312. if b.binding.show
  1313. ]
  1314. observed["shown"] = shown
  1315. footer = app.query_one(Footer)
  1316. keys = list(footer.query(FooterKey))
  1317. observed["keys"] = [
  1318. (k.key, k.key_display, k.description, k.action, set(k.classes))
  1319. for k in keys
  1320. ]
  1321. asyncio.run(scenario())
  1322. expected = [
  1323. ("a", "arm command"),
  1324. ("ctrl+r", "execute"),
  1325. ("escape", "cancel"),
  1326. ("e", "edit command"),
  1327. ("t", "cycle pane"),
  1328. ("s", "questions view"),
  1329. ("question_mark", "help"),
  1330. ("q", "quit"),
  1331. ]
  1332. assert observed["shown"] == expected, observed["shown"]
  1333. # Help advertises as "?" in the footer.
  1334. assert app.get_key_display(
  1335. next(b for b in AssistantTUI.BINDINGS if b.key == "question_mark")
  1336. ) == "?"
  1337. # The composed Footer: exactly one "instructions" entry and it is the
  1338. # right-aligned command-palette key; no left duplicate exists.
  1339. instructions = [k for k in observed["keys"] if k[2] == "instructions"]
  1340. assert len(instructions) == 1, observed["keys"]
  1341. key, key_display, _desc, action, classes = instructions[0]
  1342. assert action == "command_palette", instructions
  1343. assert "-command-palette" in classes, instructions
  1344. assert key == "ctrl+p", instructions
  1345. non_palette = [k for k in observed["keys"] if "-command-palette" not in k[4]]
  1346. assert not any(k[2] == "instructions" for k in non_palette), observed["keys"]
  1347. assert not any(k[3] == "command_palette" for k in non_palette), observed["keys"]
  1348. def test_ctrl_p_opens_command_palette(server):
  1349. """ctrl+p still opens the palette; its binding description is 'instructions'."""
  1350. pytest.importorskip("textual")
  1351. from textual.command import CommandPalette
  1352. from stt_daemon.tui.app import AssistantTUI
  1353. path, _service = server
  1354. app = AssistantTUI(path)
  1355. observed: dict = {}
  1356. async def scenario():
  1357. async with app.run_test() as pilot:
  1358. await pilot.pause()
  1359. await pilot.press("ctrl+p")
  1360. await pilot.pause()
  1361. await pilot.pause()
  1362. observed["is_palette"] = isinstance(app.screen, CommandPalette)
  1363. observed["stack"] = [type(s).__name__ for s in app.screen_stack]
  1364. asyncio.run(scenario())
  1365. palette_binding = next(b for b in AssistantTUI.BINDINGS if b.key == "ctrl+p")
  1366. assert palette_binding.description == "instructions"
  1367. assert observed["is_palette"], "ctrl+p did not open the command palette: %s" % (
  1368. observed["stack"],
  1369. )
  1370. def test_question_mark_toggles_help_panel(server):
  1371. """? toggles the help panel and is advertised in the left footer list."""
  1372. pytest.importorskip("textual")
  1373. from textual.widgets import HelpPanel
  1374. from stt_daemon.tui.app import AssistantTUI
  1375. path, _service = server
  1376. app = AssistantTUI(path)
  1377. observed: dict = {}
  1378. async def scenario():
  1379. async with app.run_test() as pilot:
  1380. await pilot.pause()
  1381. assert list(app.screen.query(HelpPanel)) == []
  1382. await pilot.press("?")
  1383. await pilot.pause()
  1384. observed["shown"] = list(app.screen.query(HelpPanel)) != []
  1385. await pilot.press("?")
  1386. await pilot.pause()
  1387. observed["hidden"] = list(app.screen.query(HelpPanel)) == []
  1388. asyncio.run(scenario())
  1389. assert observed["shown"] is True, "? did not mount HelpPanel"
  1390. assert observed["hidden"] is True, "second ? did not remove HelpPanel"
  1391. def test_plain_m_maximizes_triage_pane(server):
  1392. pytest.importorskip("textual")
  1393. from stt_daemon.tui.app import AssistantTUI
  1394. from textual.widgets import RichLog
  1395. path, _service = server
  1396. app = AssistantTUI(path, triage_enabled=True)
  1397. async def scenario():
  1398. async with app.run_test(size=(80, 40)) as pilot:
  1399. await pilot.pause()
  1400. app.query_one("#triage", RichLog).focus()
  1401. await pilot.pause()
  1402. await pilot.press("m")
  1403. await pilot.pause()
  1404. assert app.screen.maximized is app.query_one("#main")
  1405. await pilot.press("m")
  1406. await pilot.pause()
  1407. assert app.screen.maximized is None
  1408. assert app.query_one("#triage", RichLog).display is True
  1409. # No chat/command output ingested: chat follows the content rule → hidden.
  1410. assert app.query_one("#chat", RichLog).display is False
  1411. asyncio.run(scenario())
  1412. def test_screenshot_saves_svg(server, tmp_path, monkeypatch):
  1413. pytest.importorskip("textual")
  1414. import glob
  1415. from stt_daemon.tui.app import AssistantTUI
  1416. monkeypatch.chdir(tmp_path)
  1417. path, _service = server
  1418. app = AssistantTUI(path)
  1419. async def scenario():
  1420. async with app.run_test() as pilot:
  1421. await pilot.pause()
  1422. await pilot.press("ctrl+s")
  1423. await pilot.pause()
  1424. await pilot.pause()
  1425. asyncio.run(scenario())
  1426. out_dir = tmp_path / "screenshots"
  1427. assert out_dir.is_dir(), "screenshots/ not created in %s" % tmp_path
  1428. files = glob.glob(str(out_dir / "stt-tui-*.svg"))
  1429. assert files, "no stt-tui-*.svg found in %s" % out_dir
  1430. assert os.path.getsize(files[0]) > 0
  1431. assert glob.glob(str(tmp_path / "stt-tui-*.svg")) == [], \
  1432. "screenshot leaked into %s instead of screenshots/" % tmp_path
  1433. def test_screenshot_saves_into_session_dir(server, tmp_path, monkeypatch):
  1434. pytest.importorskip("textual")
  1435. import glob
  1436. from stt_daemon.tui.app import AssistantTUI
  1437. monkeypatch.chdir(tmp_path)
  1438. path, _service = server
  1439. app = AssistantTUI(path)
  1440. app.state.session_dir = "transcripts/x"
  1441. async def scenario():
  1442. async with app.run_test() as pilot:
  1443. await pilot.pause()
  1444. await pilot.press("ctrl+s")
  1445. await pilot.pause()
  1446. await pilot.pause()
  1447. asyncio.run(scenario())
  1448. out_dir = tmp_path / "transcripts" / "x" / "screenshots"
  1449. assert out_dir.is_dir(), "session screenshots/ not created in %s" % out_dir
  1450. files = glob.glob(str(out_dir / "stt-tui-*.svg"))
  1451. assert files, "no stt-tui-*.svg found in %s" % out_dir
  1452. assert os.path.getsize(files[0]) > 0
  1453. assert glob.glob(str(tmp_path / "screenshots" / "stt-tui-*.svg")) == [], \
  1454. "screenshot leaked into screenshots/ instead of the session dir"
  1455. def test_chat_hidden_by_default_triage_fills_main(server):
  1456. """Fresh state: #chat hidden, #triage fills the whole #main width."""
  1457. pytest.importorskip("textual")
  1458. from textual.containers import Horizontal
  1459. from textual.widgets import RichLog
  1460. from stt_daemon.tui.app import AssistantTUI
  1461. path, _service = server
  1462. app = AssistantTUI(path, triage_enabled=True)
  1463. observed: dict = {}
  1464. async def scenario():
  1465. async with app.run_test(size=(80, 40)) as pilot:
  1466. await pilot.pause()
  1467. app._timer.stop() # no background drain: server status must not clobber state
  1468. app._drain()
  1469. app._render()
  1470. await pilot.pause()
  1471. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1472. observed["triage_display"] = app.query_one("#triage", RichLog).display
  1473. observed["main_region"] = app.query_one("#main", Horizontal).region
  1474. observed["triage_region"] = app.query_one("#triage", RichLog).region
  1475. asyncio.run(scenario())
  1476. print("hidden: main=%s triage=%s" % (observed["main_region"], observed["triage_region"]))
  1477. assert observed["chat_display"] is False
  1478. assert observed["triage_display"] is True
  1479. assert (
  1480. abs(observed["triage_region"].width - observed["main_region"].width) <= 2
  1481. ), (observed["triage_region"], observed["main_region"])
  1482. def test_chat_mode_shows_chat_and_restores_split(server):
  1483. """mode=chat → #chat visible, triage back to ~1/3 width."""
  1484. pytest.importorskip("textual")
  1485. from textual.containers import Horizontal
  1486. from textual.widgets import RichLog
  1487. from stt_daemon.tui.app import AssistantTUI
  1488. path, _service = server
  1489. app = AssistantTUI(path, triage_enabled=True)
  1490. observed: dict = {}
  1491. async def scenario():
  1492. async with app.run_test(size=(80, 40)) as pilot:
  1493. await pilot.pause()
  1494. app._timer.stop() # no background drain: server status must not clobber state
  1495. app._drain()
  1496. app._lower_view = "chat"
  1497. app.state.ingest({"type": "mode", "mode": "chat"})
  1498. app._render()
  1499. await pilot.pause()
  1500. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1501. observed["main_region"] = app.query_one("#main", Horizontal).region
  1502. observed["triage_region"] = app.query_one("#triage", RichLog).region
  1503. observed["chat_region"] = app.query_one("#chat", RichLog).region
  1504. asyncio.run(scenario())
  1505. print(
  1506. "shown: main=%s triage=%s chat=%s"
  1507. % (observed["main_region"], observed["triage_region"], observed["chat_region"])
  1508. )
  1509. assert observed["chat_display"] is True
  1510. main_w = observed["main_region"].width
  1511. assert abs(observed["triage_region"].width / main_w - 1 / 3) < 0.08, observed
  1512. assert abs(observed["chat_region"].width / main_w - 2 / 3) < 0.08, observed
  1513. def test_tool_result_shows_output_pane(server):
  1514. """Command output (tool_result) goes to #output, leaving #chat hidden."""
  1515. pytest.importorskip("textual")
  1516. from textual.widgets import RichLog
  1517. from stt_daemon.tui.app import AssistantTUI
  1518. path, _service = server
  1519. app = AssistantTUI(path, triage_enabled=True)
  1520. observed: dict = {}
  1521. async def scenario():
  1522. async with app.run_test(size=(80, 40)) as pilot:
  1523. await pilot.pause()
  1524. app._timer.stop() # no background drain: server status must not clobber state
  1525. app._drain()
  1526. app._lower_view = "output"
  1527. app.state.ingest(
  1528. {
  1529. "type": "tool_result",
  1530. "tool": "get_datetime",
  1531. "ok": True,
  1532. "result": "2026-09-21",
  1533. }
  1534. )
  1535. app._render()
  1536. await pilot.pause()
  1537. observed["output_display"] = app.query_one("#output", RichLog).display
  1538. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1539. asyncio.run(scenario())
  1540. assert observed["output_display"] is True
  1541. assert observed["chat_display"] is False
  1542. def test_error_event_shows_output_pane(server):
  1543. """An error event goes to #output, leaving #chat hidden."""
  1544. pytest.importorskip("textual")
  1545. from textual.widgets import RichLog
  1546. from stt_daemon.tui.app import AssistantTUI
  1547. path, _service = server
  1548. app = AssistantTUI(path, triage_enabled=True)
  1549. observed: dict = {}
  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._lower_view = "output"
  1556. app.state.ingest({"type": "error", "code": "boom", "message": "kaboom"})
  1557. app._render()
  1558. await pilot.pause()
  1559. observed["output_display"] = app.query_one("#output", RichLog).display
  1560. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1561. asyncio.run(scenario())
  1562. assert observed["output_display"] is True
  1563. assert observed["chat_display"] is False
  1564. def test_executing_mode_shows_output_pane(server):
  1565. """Assistant executing a command → #output visible, #chat hidden."""
  1566. pytest.importorskip("textual")
  1567. from textual.widgets import RichLog
  1568. from stt_daemon.tui.app import AssistantTUI
  1569. path, _service = server
  1570. app = AssistantTUI(path, triage_enabled=True)
  1571. observed: dict = {}
  1572. async def scenario():
  1573. async with app.run_test(size=(80, 40)) as pilot:
  1574. await pilot.pause()
  1575. app._timer.stop() # no background drain: server status must not clobber state
  1576. app._drain()
  1577. app._lower_view = "output"
  1578. app.state.ingest({"type": "mode", "mode": "executing"})
  1579. app._render()
  1580. await pilot.pause()
  1581. observed["output_display"] = app.query_one("#output", RichLog).display
  1582. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1583. asyncio.run(scenario())
  1584. assert observed["output_display"] is True
  1585. assert observed["chat_display"] is False
  1586. def test_cleared_hides_pane_empties_output_and_restores_full_width(server):
  1587. """cleared empties #output and hides it again, triage full width."""
  1588. pytest.importorskip("textual")
  1589. from textual.containers import Horizontal
  1590. from textual.widgets import RichLog
  1591. from stt_daemon.tui.app import AssistantTUI
  1592. path, _service = server
  1593. app = AssistantTUI(path, triage_enabled=True)
  1594. observed: dict = {}
  1595. async def scenario():
  1596. async with app.run_test(size=(80, 40)) as pilot:
  1597. await pilot.pause()
  1598. app._timer.stop() # no background drain: server status must not clobber state
  1599. app._drain()
  1600. app._lower_view = "output"
  1601. app.state.ingest(
  1602. {
  1603. "type": "tool_result",
  1604. "tool": "get_datetime",
  1605. "ok": True,
  1606. "result": "2026-09-21",
  1607. }
  1608. )
  1609. app._render()
  1610. await pilot.pause()
  1611. assert app.query_one("#output", RichLog).display is True
  1612. app.state.ingest({"type": "cleared"})
  1613. app._render()
  1614. await pilot.pause()
  1615. observed["empty_output"] = [
  1616. str(line) for line in app.query_one("#output", RichLog).lines
  1617. ]
  1618. observed["lower_view"] = app._lower_view
  1619. observed["chat_display"] = app.query_one("#chat", RichLog).display
  1620. observed["output_display"] = app.query_one("#output", RichLog).display
  1621. observed["main_region"] = app.query_one("#main", Horizontal).region
  1622. observed["triage_region"] = app.query_one("#triage", RichLog).region
  1623. asyncio.run(scenario())
  1624. print(
  1625. "cleared: main=%s triage=%s"
  1626. % (observed["main_region"], observed["triage_region"])
  1627. )
  1628. assert observed["empty_output"] == []
  1629. assert observed["lower_view"] == "hidden"
  1630. assert observed["chat_display"] is False
  1631. assert observed["output_display"] is False
  1632. assert (
  1633. abs(observed["triage_region"].width - observed["main_region"].width) <= 2
  1634. ), (observed["triage_region"], observed["main_region"])
  1635. def test_cycle_lower_switches_panes(server):
  1636. """t cycles hidden -> #output -> #chat -> hidden when triage is disabled."""
  1637. pytest.importorskip("textual")
  1638. from textual.widgets import RichLog
  1639. from stt_daemon.tui.app import AssistantTUI
  1640. path, _service = server
  1641. app = AssistantTUI(path)
  1642. observed: dict = {}
  1643. def snap():
  1644. return (
  1645. app.query_one("#output", RichLog).display,
  1646. app.query_one("#chat", RichLog).display,
  1647. app.query_one("#transcript", RichLog).has_class("-grow"),
  1648. )
  1649. async def scenario():
  1650. async with app.run_test(size=(80, 40)) as pilot:
  1651. await pilot.pause()
  1652. app._timer.stop() # no background drain: server status must not clobber state
  1653. app._drain()
  1654. app._render()
  1655. await pilot.pause()
  1656. observed["hidden"] = snap()
  1657. app.action_cycle_lower()
  1658. app._render()
  1659. await pilot.pause()
  1660. observed["output"] = snap()
  1661. app.action_cycle_lower()
  1662. app._render()
  1663. await pilot.pause()
  1664. observed["chat"] = snap()
  1665. app.action_cycle_lower()
  1666. app._render()
  1667. await pilot.pause()
  1668. observed["hidden_again"] = snap()
  1669. asyncio.run(scenario())
  1670. assert observed["hidden"] == (False, False, True)
  1671. assert observed["output"] == (True, False, False)
  1672. assert observed["chat"] == (False, True, False)
  1673. assert observed["hidden_again"] == (False, False, True)
  1674. def test_cycle_lower_enters_and_exits_chat_mode(server):
  1675. """Selecting conversation sends chat_toggle on; leaving it toggles off but
  1676. keeps the rendered turns until an explicit clear."""
  1677. pytest.importorskip("textual")
  1678. from textual.widgets import RichLog
  1679. from stt_daemon.tui.app import AssistantTUI
  1680. path, _service = server
  1681. app = AssistantTUI(path)
  1682. sent: list[tuple] = []
  1683. observed: dict = {}
  1684. async def scenario():
  1685. async with app.run_test(size=(80, 40)) as pilot:
  1686. await pilot.pause()
  1687. app.client.send = lambda type_, **fields: sent.append((type_, fields))
  1688. app._timer.stop()
  1689. app._drain()
  1690. app.action_cycle_lower() # hidden -> output
  1691. app.action_cycle_lower() # output -> chat
  1692. app._render()
  1693. await pilot.pause()
  1694. observed["after_enter"] = list(sent)
  1695. app.state.ingest({"type": "mode", "mode": "chat"})
  1696. app.state.ingest({"type": "chat_message", "role": "user", "text": "remember"})
  1697. app._render()
  1698. await pilot.pause()
  1699. app.action_cycle_lower() # chat -> hidden (mode is chat -> exits)
  1700. app._render()
  1701. await pilot.pause()
  1702. observed["after_exit"] = list(sent)
  1703. observed["chat_lines"] = [str(line) for line in app.query_one("#chat", RichLog).lines]
  1704. asyncio.run(scenario())
  1705. assert observed["after_enter"] == [("chat_toggle", {})]
  1706. assert observed["after_exit"] == [("chat_toggle", {}), ("chat_toggle", {})]
  1707. assert any("remember" in line for line in observed["chat_lines"])
  1708. def test_command_activity_reveals_output_pane(server):
  1709. """Arming, executing, and chatting: command modes force #output; chat does not."""
  1710. pytest.importorskip("textual")
  1711. from textual.widgets import RichLog
  1712. from stt_daemon.tui.app import AssistantTUI
  1713. path, _service = server
  1714. app = AssistantTUI(path, triage_enabled=True)
  1715. observed: dict = {}
  1716. async def scenario():
  1717. async with app.run_test(size=(80, 40)) as pilot:
  1718. await pilot.pause()
  1719. app._timer.stop()
  1720. app._drain()
  1721. await pilot.pause()
  1722. observed["hidden"] = app.query_one("#output", RichLog).display
  1723. app.state.ingest({"type": "mode", "mode": "command_armed"})
  1724. app._render()
  1725. await pilot.pause()
  1726. observed["armed"] = (
  1727. app._lower_view,
  1728. app.query_one("#output", RichLog).display,
  1729. app.query_one("#chat", RichLog).display,
  1730. )
  1731. app._lower_view = "hidden"
  1732. app.state.ingest({"type": "mode", "mode": "executing"})
  1733. app._render()
  1734. await pilot.pause()
  1735. observed["executing"] = (
  1736. app._lower_view,
  1737. app.query_one("#output", RichLog).display,
  1738. )
  1739. app._lower_view = "chat"
  1740. app.state.ingest({"type": "mode", "mode": "chat"})
  1741. app._render()
  1742. await pilot.pause()
  1743. observed["chat"] = (
  1744. app._lower_view,
  1745. app.query_one("#output", RichLog).display,
  1746. app.query_one("#chat", RichLog).display,
  1747. )
  1748. asyncio.run(scenario())
  1749. assert observed["hidden"] is False
  1750. assert observed["armed"] == ("output", True, False)
  1751. assert observed["executing"] == ("output", True)
  1752. assert observed["chat"] == ("chat", False, True)
  1753. def test_maximize_restore_with_output_keeps_output_visible(server):
  1754. """With ingested output, m then m restores with #output still visible."""
  1755. pytest.importorskip("textual")
  1756. from textual.widgets import RichLog
  1757. from stt_daemon.tui.app import AssistantTUI
  1758. path, _service = server
  1759. app = AssistantTUI(path, triage_enabled=True)
  1760. observed: dict = {}
  1761. async def scenario():
  1762. async with app.run_test(size=(80, 40)) as pilot:
  1763. await pilot.pause()
  1764. app._timer.stop() # no background drain: server status must not clobber state
  1765. app._drain()
  1766. app._lower_view = "output"
  1767. app.state.ingest(
  1768. {
  1769. "type": "tool_result",
  1770. "tool": "get_datetime",
  1771. "ok": True,
  1772. "result": "2026-09-21",
  1773. }
  1774. )
  1775. app._render()
  1776. await pilot.pause()
  1777. assert app.query_one("#output", RichLog).display is True
  1778. app.query_one("#triage", RichLog).focus()
  1779. await pilot.pause()
  1780. await pilot.press("m")
  1781. await pilot.pause()
  1782. assert app.screen.maximized is not None
  1783. await pilot.press("m")
  1784. await pilot.pause()
  1785. observed["maximized"] = app.screen.maximized
  1786. observed["triage_display"] = app.query_one("#triage", RichLog).display
  1787. observed["output_display"] = app.query_one("#output", RichLog).display
  1788. asyncio.run(scenario())
  1789. assert observed["maximized"] is None
  1790. assert observed["triage_display"] is True
  1791. assert observed["output_display"] is True
  1792. def test_transcript_pane_keeps_updating_past_cap(server):
  1793. """Regression: past MAX_TRANSCRIPTS the running log must still append."""
  1794. pytest.importorskip("textual")
  1795. from textual.widgets import RichLog
  1796. from stt_daemon.tui.app import AssistantTUI
  1797. from stt_daemon.tui.state import MAX_TRANSCRIPTS
  1798. path, _service = server
  1799. app = AssistantTUI(path)
  1800. observed: dict = {}
  1801. async def scenario():
  1802. async with app.run_test(size=(80, 40)) as pilot:
  1803. await pilot.pause()
  1804. app._timer.stop() # no background drain: server status must not clobber state
  1805. app._drain()
  1806. for i in range(MAX_TRANSCRIPTS + 5):
  1807. app.state.ingest({"type": "transcript", "text": f"t{i}", "lang": "en"})
  1808. app._render()
  1809. await pilot.pause()
  1810. app.state.ingest({"type": "transcript", "text": "after cap", "lang": "en"})
  1811. app._render()
  1812. await pilot.pause()
  1813. log = app.query_one("#transcript", RichLog)
  1814. observed["lines"] = [str(line) for line in log.lines]
  1815. asyncio.run(scenario())
  1816. assert any("after cap" in line for line in observed["lines"])
  1817. assert len(observed["lines"]) > MAX_TRANSCRIPTS
  1818. def _questions_payload():
  1819. return {
  1820. "topic": {
  1821. "type": "choice",
  1822. "instructions": "What is the main theme?",
  1823. "criteria": {"planning": "roadmap or prioritization"},
  1824. }
  1825. }
  1826. def _rendered_lines(log):
  1827. return [line.text for line in log.lines]
  1828. def _ingest_triage_signals(app):
  1829. app.state.ingest(
  1830. {
  1831. "type": "triage",
  1832. "stage": "signals",
  1833. "triage": {
  1834. "order": ["topic"],
  1835. "items": {
  1836. "topic": {
  1837. "kind": "choice",
  1838. "choice": "planning",
  1839. "answer_confidence": 0.91,
  1840. }
  1841. },
  1842. },
  1843. }
  1844. )
  1845. app.state.ingest(
  1846. {
  1847. "type": "status",
  1848. "triage_state": "ok",
  1849. "triage_reason": "",
  1850. "questions": _questions_payload(),
  1851. }
  1852. )
  1853. def test_s_key_swaps_triage_pane_to_questions_view(server):
  1854. """Press s: #triage border flips to questions and renders the structured blocks."""
  1855. pytest.importorskip("textual")
  1856. from textual.widgets import RichLog
  1857. from stt_daemon.tui.app import AssistantTUI
  1858. path, _service = server
  1859. app = AssistantTUI(path, triage_enabled=True)
  1860. observed: dict = {}
  1861. async def scenario():
  1862. async with app.run_test() as pilot:
  1863. await pilot.pause()
  1864. app._timer.stop() # no background drain: server status must not clobber state
  1865. app._drain()
  1866. _ingest_triage_signals(app)
  1867. app._render()
  1868. await pilot.pause()
  1869. observed["default_title"] = app.query_one("#triage", RichLog).border_title
  1870. observed["default_lines"] = _rendered_lines(app.query_one("#triage", RichLog))
  1871. await pilot.press("s")
  1872. await pilot.pause()
  1873. observed["questions_title"] = app.query_one("#triage", RichLog).border_title
  1874. observed["questions_lines"] = _rendered_lines(app.query_one("#triage", RichLog))
  1875. asyncio.run(scenario())
  1876. assert observed["default_title"] == "triage \\[inf 0]" # markup: '[' is escaped
  1877. assert any("topic: planning (0.91)" in line for line in observed["default_lines"])
  1878. assert observed["questions_title"] == "questions"
  1879. rendered = "\n".join(observed["questions_lines"])
  1880. assert "topic [choice]" in rendered
  1881. assert "What is the main theme?" in rendered
  1882. assert "planning — roadmap or prioritization" in rendered
  1883. assert "topic: planning" not in rendered
  1884. def test_s_key_again_restores_triage_view(server):
  1885. """Second s: border flips back to triage and the signals view is rewritten."""
  1886. pytest.importorskip("textual")
  1887. from textual.widgets import RichLog
  1888. from stt_daemon.tui.app import AssistantTUI
  1889. path, _service = server
  1890. app = AssistantTUI(path, triage_enabled=True)
  1891. observed: dict = {}
  1892. async def scenario():
  1893. async with app.run_test() as pilot:
  1894. await pilot.pause()
  1895. app._timer.stop() # no background drain: server status must not clobber state
  1896. app._drain()
  1897. _ingest_triage_signals(app)
  1898. app._render()
  1899. await pilot.pause()
  1900. await pilot.press("s")
  1901. await pilot.pause()
  1902. observed["mid_title"] = app.query_one("#triage", RichLog).border_title
  1903. await pilot.press("s")
  1904. await pilot.pause()
  1905. observed["triage_title"] = app.query_one("#triage", RichLog).border_title
  1906. observed["triage_lines"] = _rendered_lines(app.query_one("#triage", RichLog))
  1907. asyncio.run(scenario())
  1908. assert observed["mid_title"] == "questions"
  1909. assert observed["triage_title"] == "triage \\[inf 0]" # markup: '[' is escaped
  1910. rendered = "\n".join(observed["triage_lines"])
  1911. assert "topic: planning (0.91)" in rendered
  1912. assert "What is the main theme?" not in rendered
  1913. def test_triage_brief_title_mirrors_inference_depth_and_busy(server):
  1914. """Brief view: #triage title carries [inf N] and the busy marker, exactly."""
  1915. pytest.importorskip("textual")
  1916. from textual.widgets import RichLog
  1917. from stt_daemon.tui.app import AssistantTUI
  1918. path, _service = server
  1919. app = AssistantTUI(path, triage_enabled=True)
  1920. observed: dict = {}
  1921. async def scenario():
  1922. async with app.run_test() as pilot:
  1923. await pilot.pause()
  1924. app._timer.stop() # no background drain: server status must not clobber state
  1925. app._drain()
  1926. app.state.ingest(
  1927. {"type": "heartbeat", "inference_depth": 3, "inference_in_flight": False}
  1928. )
  1929. app._render()
  1930. await pilot.pause()
  1931. observed["idle"] = app.query_one("#triage", RichLog).border_title
  1932. app.state.ingest(
  1933. {"type": "heartbeat", "inference_depth": 7, "inference_in_flight": True}
  1934. )
  1935. app._render()
  1936. await pilot.pause()
  1937. observed["busy"] = app.query_one("#triage", RichLog).border_title
  1938. asyncio.run(scenario())
  1939. # border_title round-trips as console markup, so '[' reads back as '\['.
  1940. assert observed["idle"] == "triage \\[inf 3]"
  1941. assert observed["busy"] == "triage \\[inf 7 · busy]"
  1942. def test_questions_view_title_has_no_inference_suffix(server):
  1943. """Questions view: title is exactly 'questions'; toggling back restores the suffix."""
  1944. pytest.importorskip("textual")
  1945. from textual.widgets import RichLog
  1946. from stt_daemon.tui.app import AssistantTUI
  1947. path, _service = server
  1948. app = AssistantTUI(path, triage_enabled=True)
  1949. observed: dict = {}
  1950. async def scenario():
  1951. async with app.run_test() as pilot:
  1952. await pilot.pause()
  1953. app._timer.stop()
  1954. app._drain()
  1955. app.state.ingest(
  1956. {"type": "heartbeat", "inference_depth": 5, "inference_in_flight": True}
  1957. )
  1958. app._render()
  1959. await pilot.pause()
  1960. observed["brief"] = app.query_one("#triage", RichLog).border_title
  1961. await pilot.press("s")
  1962. await pilot.pause()
  1963. observed["questions"] = app.query_one("#triage", RichLog).border_title
  1964. await pilot.press("s")
  1965. await pilot.pause()
  1966. observed["restored"] = app.query_one("#triage", RichLog).border_title
  1967. asyncio.run(scenario())
  1968. assert observed["brief"] == "triage \\[inf 5 · busy]"
  1969. assert observed["questions"] == "questions"
  1970. assert "inf" not in observed["questions"]
  1971. assert "busy" not in observed["questions"]
  1972. # No stale plain title: the brief view comes back fully suffixed.
  1973. assert observed["restored"] == "triage \\[inf 5 · busy]"
  1974. def test_triage_disabled_heartbeat_leaves_no_triage_widget(server):
  1975. """triage_enabled=False: depths update #chat only and never create a #triage pane."""
  1976. pytest.importorskip("textual")
  1977. from textual.widgets import RichLog
  1978. from stt_daemon.tui.app import AssistantTUI
  1979. path, _service = server
  1980. app = AssistantTUI(path)
  1981. observed: dict = {}
  1982. async def scenario():
  1983. async with app.run_test() as pilot:
  1984. await pilot.pause()
  1985. app._timer.stop()
  1986. app._drain()
  1987. app.state.ingest(
  1988. {"type": "heartbeat", "inference_depth": 9, "inference_in_flight": True}
  1989. )
  1990. app._render()
  1991. await pilot.pause()
  1992. observed["has_triage"] = bool(app.query("#triage"))
  1993. observed["chat"] = app.query_one("#chat", RichLog).border_title
  1994. asyncio.run(scenario())
  1995. assert observed["has_triage"] is False
  1996. assert observed["chat"] == "conversation \\[inf 9 · busy]"
  1997. def test_s_key_is_noop_when_triage_disabled(server):
  1998. """triage_enabled=False: action_toggle_questions and s do nothing and never crash."""
  1999. pytest.importorskip("textual")
  2000. from stt_daemon.tui.app import AssistantTUI
  2001. path, _service = server
  2002. app = AssistantTUI(path)
  2003. async def scenario():
  2004. async with app.run_test() as pilot:
  2005. await pilot.pause()
  2006. app.action_toggle_questions()
  2007. await pilot.pause()
  2008. assert app._show_questions is False
  2009. assert not app.query("#triage")
  2010. await pilot.press("s")
  2011. await pilot.pause()
  2012. assert app._show_questions is False
  2013. assert not app.query("#triage")
  2014. asyncio.run(scenario())
  2015. def test_status_event_questions_populate_questions_view(server):
  2016. """A status event carrying questions fills state and the toggled pane."""
  2017. pytest.importorskip("textual")
  2018. from textual.widgets import RichLog
  2019. from stt_daemon.tui.app import AssistantTUI
  2020. path, _service = server
  2021. app = AssistantTUI(path, triage_enabled=True)
  2022. observed: dict = {}
  2023. async def scenario():
  2024. async with app.run_test() as pilot:
  2025. await pilot.pause()
  2026. app._timer.stop() # no background drain: server status must not clobber state
  2027. app._drain()
  2028. observed["before_epoch"] = app.state.questions_epoch
  2029. app.state.ingest({"type": "status", "questions": _questions_payload()})
  2030. app._render()
  2031. await pilot.pause()
  2032. observed["questions"] = app.state.questions
  2033. observed["epoch"] = app.state.questions_epoch
  2034. await pilot.press("s")
  2035. await pilot.pause()
  2036. observed["lines"] = _rendered_lines(app.query_one("#triage", RichLog))
  2037. asyncio.run(scenario())
  2038. assert observed["questions"] == _questions_payload()
  2039. assert observed["epoch"] == observed["before_epoch"] + 1
  2040. assert any("topic [choice]" in line for line in observed["lines"])