test_triage.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. """Tests for the triage analyzer (todos 3, 9, 10, 11). Pure, hardware-free."""
  2. import json
  3. import logging
  4. from pathlib import Path
  5. from types import SimpleNamespace
  6. import pytest
  7. from stt_daemon import events
  8. from stt_daemon.assistant import triage
  9. from stt_daemon.assistant.service import AssistantService
  10. from stt_daemon.assistant.triage import TriageAnalyzer, load_questions
  11. from stt_daemon.config import Config
  12. from stt_daemon.tui.state import ViewState
  13. EXAMPLE_PATH = str(Path(__file__).resolve().parent.parent / "questions.example.json")
  14. EXPECTED_ORDER = [
  15. "category",
  16. "urgency",
  17. "frustration",
  18. "churn_risk",
  19. "needs_action",
  20. "needs_clarification",
  21. "contains_idea",
  22. "business_opportunity",
  23. "positive_sentiment",
  24. ]
  25. def _cfg(path=EXAMPLE_PATH, **overrides):
  26. base = {
  27. "questions_file": path,
  28. "state_char_budget": 1200,
  29. "confidence_field": "answer_confidence",
  30. "escalate_threshold": 0.6,
  31. "choice_min_confidence": 0.85,
  32. }
  33. base.update(overrides)
  34. return SimpleNamespace(**base)
  35. def _write_questions(tmp_path, questions):
  36. path = tmp_path / "questions.json"
  37. path.write_text(json.dumps(questions), encoding="utf-8")
  38. return str(path)
  39. def _analyzer(tmp_path, questions=None, **overrides):
  40. if questions is None:
  41. return TriageAnalyzer(_cfg(**overrides))
  42. return TriageAnalyzer(_cfg(_write_questions(tmp_path, questions), **overrides))
  43. # --- todo 3: load_questions -------------------------------------------------
  44. def test_load_example_order_preserved():
  45. questions = load_questions(EXAMPLE_PATH)
  46. assert questions is not None
  47. assert list(questions.keys()) == EXPECTED_ORDER
  48. assert questions["category"]["type"] == "choice"
  49. assert questions["urgency"]["type"] == "choice"
  50. for qid in EXPECTED_ORDER[2:]:
  51. assert questions[qid]["type"] == "noul"
  52. def test_load_missing_file_returns_none_with_warning(caplog):
  53. with caplog.at_level(logging.WARNING, logger="stt_daemon.assistant.triage"):
  54. assert load_questions("/nonexistent/questions.json") is None
  55. assert caplog.records, "expected a warning for the missing file"
  56. def test_load_bad_json_returns_none_with_warning(tmp_path, caplog):
  57. path = tmp_path / "questions.json"
  58. path.write_text("{not valid json", encoding="utf-8")
  59. with caplog.at_level(logging.WARNING, logger="stt_daemon.assistant.triage"):
  60. assert load_questions(str(path)) is None
  61. assert caplog.records
  62. @pytest.mark.parametrize(
  63. "bad_entry",
  64. [
  65. {"type": "mystery", "instructions": "do something"}, # unknown type
  66. {"type": "score", "instructions": "rate it", "criteria": {"0": "low"}}, # score dict
  67. { # noul criteria with a bad key
  68. "type": "noul",
  69. "instructions": "holds?",
  70. "criteria": {"true": "yes", "maybe": "hmm"},
  71. },
  72. "just a string", # non-object entry
  73. {"type": "choice", "instructions": "pick one", "criteria": []}, # empty choice
  74. {"type": "choice", "instructions": "pick one", "criteria": {}}, # empty choice dict
  75. {"type": "choice", "criteria": ["a", "b"]}, # missing instructions
  76. {"type": "score", "instructions": "rate it", "criteria": ["a", None]}, # None level
  77. {"type": "noul", "instructions": "holds?", "criteria": ["true"]}, # noul list
  78. ],
  79. )
  80. def test_load_malformed_returns_none_with_warning(tmp_path, caplog, bad_entry):
  81. path = _write_questions(
  82. tmp_path, {"good": {"type": "noul", "instructions": "ok?"}, "bad": bad_entry}
  83. )
  84. with caplog.at_level(logging.WARNING, logger="stt_daemon.assistant.triage"):
  85. assert load_questions(str(path)) is None
  86. assert caplog.records
  87. # --- todo 9: normalize ------------------------------------------------------
  88. def _score_questions():
  89. return {
  90. "severity": {
  91. "type": "score",
  92. "instructions": "How severe is the issue?",
  93. "criteria": ["none", "low", "high", "critical"],
  94. },
  95. "category": {
  96. "type": "choice",
  97. "instructions": "What is this about?",
  98. "criteria": {"support": "help needed", "sales": "buying"},
  99. },
  100. "churn_risk": {"type": "noul", "instructions": "User may leave."},
  101. }
  102. def test_normalize_choice_exact(tmp_path):
  103. analyzer = _analyzer(tmp_path, _score_questions())
  104. payload = {
  105. "model": "multilingual",
  106. "answers": {
  107. "category": {
  108. "type": "choice",
  109. "choice": "support",
  110. "confidence": 0.7,
  111. "answer_confidence": 0.4,
  112. }
  113. },
  114. "usage": {"input_tokens": 123, "output_tokens": 0},
  115. }
  116. result = analyzer.normalize(payload)
  117. assert result["order"] == ["category"]
  118. assert result["items"]["category"] == {
  119. "kind": "choice",
  120. "choice": "support",
  121. "confidence": 0.7,
  122. "answer_confidence": 0.4,
  123. "gate": 0.4,
  124. "flagged": True,
  125. }
  126. assert result["input_tokens"] == 123
  127. assert result["escalated"] is True
  128. def test_normalize_score_with_legend(tmp_path):
  129. analyzer = _analyzer(tmp_path, _score_questions())
  130. payload = {
  131. "answers": {
  132. "severity": {
  133. "type": "score",
  134. "score": 2.6,
  135. "legend": {"0": "none", "1": "low", "2": "high", "3": "critical"},
  136. "confidence": 0.5,
  137. "answer_confidence": 0.6,
  138. }
  139. },
  140. "usage": {"input_tokens": 7, "output_tokens": 0},
  141. }
  142. item = analyzer.normalize(payload)["items"]["severity"]
  143. assert item["kind"] == "score"
  144. assert item["expected"] == 2.6
  145. assert item["level"] == 3
  146. assert item["label"] == "critical"
  147. assert item["confidence"] == 0.5
  148. assert item["answer_confidence"] == 0.6
  149. assert item["gate"] == 0.6
  150. assert item["flagged"] is True
  151. def test_normalize_score_legend_fallback(tmp_path):
  152. analyzer = _analyzer(tmp_path, _score_questions())
  153. payload = {
  154. "answers": {
  155. "severity": {"type": "score", "score": 1.2, "confidence": 0.9, "answer_confidence": 0.9}
  156. }
  157. }
  158. item = analyzer.normalize(payload)["items"]["severity"]
  159. assert item["level"] == 1
  160. assert item["label"] == "low" # falls back to criteria[level]
  161. assert item["flagged"] is False # 1.2 < (4 - 1) * 0.5
  162. def test_normalize_noul_and_bare_payload(tmp_path):
  163. analyzer = _analyzer(tmp_path, _score_questions())
  164. bare = {
  165. "churn_risk": {"type": "noul", "noul": 0.9, "confidence": 0.9, "answer_confidence": 0.85}
  166. }
  167. result = analyzer.normalize(bare)
  168. assert result["order"] == ["churn_risk"]
  169. assert result["items"]["churn_risk"] == {
  170. "kind": "noul",
  171. "p": 0.9,
  172. "confidence": 0.9,
  173. "answer_confidence": 0.85,
  174. "gate": 0.85,
  175. "flagged": True,
  176. }
  177. assert result["input_tokens"] == 0
  178. def test_normalize_skips_unknown_qid_and_malformed(tmp_path):
  179. analyzer = _analyzer(tmp_path, _score_questions())
  180. payload = {
  181. "answers": {
  182. "ghost": {"type": "noul", "noul": 0.99, "confidence": 0.9, "answer_confidence": 0.9},
  183. "category": {"type": "choice", "choice": 42}, # malformed: no confidences
  184. "churn_risk": "nonsense", # malformed: not a dict
  185. },
  186. "usage": {"input_tokens": 3, "output_tokens": 0},
  187. }
  188. result = analyzer.normalize(payload)
  189. assert result["order"] == []
  190. assert result["items"] == {}
  191. assert result["escalated"] is False
  192. def test_normalize_ignores_side_channel_fields(tmp_path):
  193. analyzer = _analyzer(tmp_path, _score_questions())
  194. payload = {
  195. "answers": {
  196. "category": {
  197. "type": "choice",
  198. "choice": "sales",
  199. "confidence": 0.95,
  200. "answer_confidence": 0.9,
  201. "action": {"act" + "_probability": 0.99},
  202. }
  203. },
  204. "usage": {"input_tokens": 1, "output_tokens": 0},
  205. }
  206. result = analyzer.normalize(payload)
  207. assert result["items"]["category"]["flagged"] is False
  208. assert "act" + "_probability" not in json.dumps(result)
  209. source = Path(triage.__file__).read_text(encoding="utf-8")
  210. assert "act" + "_probability" not in source
  211. def test_normalize_gating_field_selectable(tmp_path):
  212. analyzer = _analyzer(tmp_path, _score_questions(), confidence_field="confidence")
  213. payload = {
  214. "answers": {
  215. "category": {
  216. "type": "choice",
  217. "choice": "sales",
  218. "confidence": 0.5,
  219. "answer_confidence": 0.99,
  220. }
  221. }
  222. }
  223. item = analyzer.normalize(payload)["items"]["category"]
  224. assert item["gate"] == 0.5 # gates on confidence, keeps both
  225. assert item["answer_confidence"] == 0.99
  226. assert item["flagged"] is True
  227. # --- todo 9: condensation ---------------------------------------------------
  228. def test_condense_keeps_newest_chronological_no_numerals(tmp_path):
  229. analyzer = _analyzer(tmp_path, _score_questions(), state_char_budget=40)
  230. window = ["alpha first", "beta second", "gamma third newest here"]
  231. state = analyzer.build_state(window)
  232. assert "gamma third newest here" in state
  233. assert "alpha first" not in state # oldest dropped under the budget
  234. lines = state.splitlines()
  235. assert all(line.startswith("- ") for line in lines)
  236. assert not any(ch.isdigit() for ch in state) # no numerals injected
  237. # chronological restore: kept lines stay in original order
  238. kept = [u for u in window if u in state]
  239. assert [line[2:] for line in lines] == kept
  240. def test_condense_empty_window(tmp_path):
  241. analyzer = _analyzer(tmp_path, _score_questions())
  242. assert analyzer.build_state([]) == ""
  243. # --- todo 10: escalation + extraction ---------------------------------------
  244. def _signals(choice_gate=0.9, noul_p=0.1, score_expected=0.2):
  245. return {
  246. "order": ["category", "churn_risk", "severity"],
  247. "items": {
  248. "category": {
  249. "kind": "choice",
  250. "choice": "sales",
  251. "confidence": choice_gate,
  252. "answer_confidence": choice_gate,
  253. "gate": choice_gate,
  254. "flagged": choice_gate < 0.85,
  255. },
  256. "churn_risk": {
  257. "kind": "noul",
  258. "p": noul_p,
  259. "confidence": noul_p,
  260. "answer_confidence": noul_p,
  261. "gate": noul_p,
  262. "flagged": noul_p >= 0.6,
  263. },
  264. "severity": {
  265. "kind": "score",
  266. "expected": score_expected,
  267. "level": 0,
  268. "label": "none",
  269. "confidence": 0.9,
  270. "answer_confidence": 0.9,
  271. "gate": 0.9,
  272. "flagged": score_expected >= 1.5,
  273. },
  274. },
  275. "escalated": False,
  276. "input_tokens": 0,
  277. }
  278. def test_escalation_arms_fire_independently(tmp_path):
  279. analyzer = _analyzer(tmp_path, _score_questions())
  280. assert analyzer.should_escalate(_signals(choice_gate=0.5)) is True # choice arm
  281. assert analyzer.should_escalate(_signals(noul_p=0.8)) is True # noul arm
  282. assert analyzer.should_escalate(_signals(score_expected=2.0)) is True # score arm
  283. assert analyzer.should_escalate(_signals()) is False
  284. def test_normalize_escalated_matches_should_escalate(tmp_path):
  285. analyzer = _analyzer(tmp_path, _score_questions())
  286. payload = {
  287. "answers": {
  288. "category": {
  289. "type": "choice",
  290. "choice": "sales",
  291. "confidence": 0.9,
  292. "answer_confidence": 0.9,
  293. },
  294. "churn_risk": {
  295. "type": "noul",
  296. "noul": 0.1,
  297. "confidence": 0.9,
  298. "answer_confidence": 0.9,
  299. },
  300. "severity": {
  301. "type": "score",
  302. "score": 0.1,
  303. "confidence": 0.9,
  304. "answer_confidence": 0.9,
  305. },
  306. }
  307. }
  308. result = analyzer.normalize(payload)
  309. assert result["escalated"] == analyzer.should_escalate(result) is False
  310. def test_build_extraction_prompt_words_not_dump(tmp_path):
  311. analyzer = _analyzer(tmp_path, _score_questions())
  312. prompt = analyzer.build_extraction_prompt(["please cancel my account"], _signals(noul_p=0.8))
  313. assert "please cancel my account" in prompt
  314. assert "churn_risk" in prompt # flagged signal named in words
  315. assert "category" not in prompt # unflagged signals omitted
  316. assert "{'kind'" not in prompt and '{"kind"' not in prompt # no raw dict dump
  317. for key in ("summary", "opportunities", "doubts", "action_items", "risks"):
  318. assert key in prompt
  319. def _extraction_doc(**overrides):
  320. doc = {
  321. "summary": "user wants to cancel",
  322. "opportunities": ["winback offer"],
  323. "doubts": ["reason unclear"],
  324. "action_items": [{"what": "call back", "why": "save account"}],
  325. "risks": ["churn"],
  326. }
  327. doc.update(overrides)
  328. return json.dumps(doc)
  329. def test_parse_extraction_valid_fenced(tmp_path):
  330. analyzer = _analyzer(tmp_path, _score_questions())
  331. text = "```json\n" + _extraction_doc() + "\n```"
  332. parsed = analyzer.parse_extraction(text)
  333. assert parsed is not None
  334. assert parsed["summary"] == "user wants to cancel"
  335. assert parsed["action_items"] == [{"what": "call back", "why": "save account"}]
  336. def test_parse_extraction_invalid_returns_none(tmp_path):
  337. analyzer = _analyzer(tmp_path, _score_questions())
  338. assert analyzer.parse_extraction("not json at all {{{") is None
  339. assert analyzer.parse_extraction(json.dumps({"summary": "only"})) is None # bad shape
  340. assert analyzer.parse_extraction(None) is None
  341. assert analyzer.parse_extraction("") is None
  342. assert analyzer.parse_extraction("x" * 30000) is None # oversized
  343. def test_parse_extraction_caps_lists_and_strings(tmp_path):
  344. analyzer = _analyzer(tmp_path, _score_questions())
  345. parsed = analyzer.parse_extraction(
  346. _extraction_doc(
  347. opportunities=["o%d" % i for i in range(9)],
  348. doubts=["d%d" % i for i in range(7)],
  349. risks=["r%d" % i for i in range(6)],
  350. summary="s" * 2000,
  351. )
  352. )
  353. assert parsed is not None
  354. assert len(parsed["opportunities"]) == 5
  355. assert len(parsed["doubts"]) == 5
  356. assert len(parsed["risks"]) == 5
  357. assert len(parsed["summary"]) <= 500
  358. # --- todo 11: cached state() ------------------------------------------------
  359. def test_state_initial_loading_with_good_questions(tmp_path):
  360. analyzer = _analyzer(tmp_path, _score_questions())
  361. assert analyzer.state() == ("loading", "")
  362. def test_state_initial_no_questions_with_bad_path(tmp_path):
  363. missing = str(tmp_path / "missing.json")
  364. analyzer = TriageAnalyzer(_cfg(missing))
  365. state, reason = analyzer.state()
  366. assert state == "no_questions"
  367. assert missing in reason
  368. def test_state_vocabulary_has_no_extra_member():
  369. assert set(triage.TRIAGE_REASONS) == {
  370. "ok",
  371. "no_questions",
  372. "loading",
  373. "laya_missing",
  374. "disabled",
  375. "error",
  376. }
  377. assert "service" + "_down" not in triage.TRIAGE_REASONS
  378. def test_refresh_transitions(tmp_path):
  379. analyzer = _analyzer(tmp_path, _score_questions())
  380. analyzer.refresh("ok")
  381. assert analyzer.state() == ("ok", "")
  382. analyzer.refresh("laya_missing", "run: uv sync --extra triage")
  383. assert analyzer.state() == ("laya_missing", "run: uv sync --extra triage")
  384. analyzer.refresh("error", "boom")
  385. assert analyzer.state() == ("error", "boom")
  386. def test_refresh_unknown_state_ignored(tmp_path, caplog):
  387. analyzer = _analyzer(tmp_path, _score_questions())
  388. analyzer.refresh("ok")
  389. with caplog.at_level(logging.WARNING, logger="stt_daemon.assistant.triage"):
  390. analyzer.refresh("bogus_state")
  391. assert analyzer.state() == ("ok", "")
  392. assert caplog.records
  393. def test_no_questions_state_cannot_be_overridden(tmp_path):
  394. analyzer = TriageAnalyzer(_cfg(str(tmp_path / "missing.json")))
  395. assert analyzer.state()[0] == "no_questions"
  396. analyzer.refresh("ok")
  397. analyzer.refresh("error", "boom")
  398. assert analyzer.state()[0] == "no_questions"
  399. def test_state_does_not_touch_lane(tmp_path):
  400. analyzer = _analyzer(tmp_path, _score_questions())
  401. class StrictLane:
  402. def __init__(self):
  403. self.calls = []
  404. def __getattr__(self, name):
  405. def record(*args, **kwargs):
  406. self.calls.append(name)
  407. return record
  408. lane = StrictLane()
  409. for _ in range(3):
  410. analyzer.state()
  411. analyzer.refresh("ok")
  412. analyzer.state()
  413. assert lane.calls == []
  414. # --- F3: end-to-end triage flow on fakes ------------------------------------
  415. EXTRACT_JSON = (
  416. '{"summary":"s","opportunities":[],"doubts":[],"action_items":[],"risks":[]}'
  417. )
  418. class _Clock:
  419. """Injected clock: no sleeps, fully deterministic."""
  420. def __init__(self, start=1000.0):
  421. self.t = float(start)
  422. def __call__(self):
  423. return self.t
  424. def advance(self, dt):
  425. self.t += float(dt)
  426. class _FakeSubscriber:
  427. def events(self):
  428. return iter(())
  429. def close(self):
  430. pass
  431. class _FakeLane:
  432. """Duck-typed LayaLane: canned-ready, records submits, counts drops."""
  433. def __init__(self):
  434. self.submits: list[tuple] = []
  435. self.drops = 0
  436. def ready(self) -> bool:
  437. return True
  438. def state(self):
  439. return ("ok", "")
  440. def submit(self, state, questions, lang, generation):
  441. self.submits.append((state, questions, lang, generation))
  442. return True
  443. def drop_pending(self):
  444. self.drops += 1
  445. return 1
  446. def _answers(noul_p=0.1):
  447. """A full laya-shaped answers payload for the example questions."""
  448. answers = {
  449. "category": {
  450. "type": "choice",
  451. "choice": "sales",
  452. "confidence": 0.9,
  453. "answer_confidence": 0.9,
  454. },
  455. "urgency": {
  456. "type": "choice",
  457. "choice": "low",
  458. "confidence": 0.9,
  459. "answer_confidence": 0.9,
  460. },
  461. }
  462. for qid in (
  463. "frustration",
  464. "churn_risk",
  465. "needs_action",
  466. "needs_clarification",
  467. "contains_idea",
  468. "business_opportunity",
  469. "positive_sentiment",
  470. ):
  471. answers[qid] = {
  472. "type": "noul",
  473. "noul": noul_p,
  474. "confidence": 0.9,
  475. "answer_confidence": 0.9,
  476. }
  477. return {"model": "multilingual", "answers": answers, "usage": {"input_tokens": 42}}
  478. def test_end_to_end_triage_flow():
  479. """signals -> content -> cleared across service, analyzer, lane, and ViewState.
  480. The lane result is wired by calling `service._on_triage_result(gen, payload)`
  481. directly (the runner does exactly this in production); the extraction job is
  482. drained with `job.run()` so no worker thread is started.
  483. """
  484. cfg = Config()
  485. cfg.assistant.turn_gap_s = 0.5
  486. cfg.triage.enabled = True
  487. cfg.triage.questions_file = EXAMPLE_PATH
  488. clock = _Clock(1000.0)
  489. lane = _FakeLane()
  490. emitted: list[dict] = []
  491. def emit(type_, **fields):
  492. emitted.append({"type": type_, **fields})
  493. analyzer = TriageAnalyzer(cfg.triage)
  494. service = AssistantService(
  495. cfg,
  496. _FakeSubscriber(),
  497. emit=emit,
  498. time_fn=clock,
  499. chat_fn=lambda text: "reply",
  500. triage=analyzer,
  501. laya_lane=lane,
  502. triage_extract_fn=lambda prompt: EXTRACT_JSON,
  503. )
  504. def triage_events():
  505. return [e for e in emitted if e["type"] == "triage"]
  506. def extract_jobs():
  507. return [j for j in service._inference._queue if j.name == "triage-extract"]
  508. # 1. settled turn -> exactly one lane submit, lang + generation recorded
  509. assert service.toggle_chat() is True
  510. service.handle_event(
  511. {"type": events.TRANSCRIPT, "text": "hola, necesito ayuda", "lang": "es"}
  512. )
  513. clock.advance(1.0)
  514. service.tick()
  515. assert len(lane.submits) == 1
  516. state_text, questions, lang, gen1 = lane.submits[0]
  517. assert "hola, necesito ayuda" in state_text
  518. assert questions is analyzer.questions
  519. assert lang == "es"
  520. assert gen1 == 0
  521. # 2. non-escalating result -> signals only, no extraction job queued
  522. service._on_triage_result(gen1, _answers(noul_p=0.1))
  523. assert [e["stage"] for e in triage_events()] == ["signals"]
  524. assert triage_events()[0]["triage"]["escalated"] is False
  525. assert service.last_triage is not None
  526. assert service.last_triage["escalated"] is False
  527. assert extract_jobs() == []
  528. # 3. escalating turn -> second submit, then exactly one extract job
  529. service.handle_event(
  530. {"type": events.TRANSCRIPT, "text": "quiero cancelar mi suscripcion", "lang": "es"}
  531. )
  532. clock.advance(1.0)
  533. service.tick()
  534. assert len(lane.submits) == 2
  535. gen2 = lane.submits[1][3]
  536. service._on_triage_result(gen2, _answers(noul_p=0.9))
  537. assert [e["stage"] for e in triage_events()] == ["signals", "signals"]
  538. assert triage_events()[1]["triage"]["escalated"] is True
  539. jobs = extract_jobs()
  540. assert len(jobs) == 1
  541. # 4. run the extraction job directly (deterministic, no worker thread)
  542. jobs[0].run()
  543. content_events = [e for e in triage_events() if e["stage"] == "content"]
  544. assert len(content_events) == 1
  545. merged = content_events[0]["triage"]
  546. assert merged["content"]["summary"] == "s"
  547. assert merged["escalated"] is True # signals preserved under the content
  548. assert merged["order"] == triage_events()[1]["triage"]["order"]
  549. # 5. drive the emitted stream through a fresh ViewState
  550. view = ViewState()
  551. for event in emitted:
  552. view.ingest(event)
  553. analyzer.refresh("ok") # the lane callback does this in production
  554. view.ingest({"type": "status", **service.status()})
  555. assert view.triage is not None
  556. assert view.triage["content"]["summary"] == "s"
  557. lines = view.triage_lines()
  558. assert lines
  559. assert any("summary" in line and "s" in line for line in lines)
  560. # 6. clear -> cleared event empties the panel and bumps the epoch
  561. baseline_epoch = view.triage_epoch
  562. already = len(emitted)
  563. service.clear()
  564. for event in emitted[already:]:
  565. view.ingest(event)
  566. assert view.triage is None
  567. assert view.triage_epoch > baseline_epoch
  568. # a stale result after clear must not re-populate the panel
  569. service._on_triage_result(gen2, _answers(noul_p=0.9))
  570. assert [e["stage"] for e in triage_events()] == [
  571. "signals",
  572. "signals",
  573. "content",
  574. "cleared",
  575. ]
  576. assert view.triage is None
  577. assert lane.drops == 1
  578. # 7. disabled control: no triage/lane -> status disabled, clear emits nothing
  579. cfg2 = Config()
  580. clock2 = _Clock(2000.0)
  581. emitted2: list[dict] = []
  582. def emit2(type_, **fields):
  583. emitted2.append({"type": type_, **fields})
  584. plain = AssistantService(cfg2, _FakeSubscriber(), emit=emit2, time_fn=clock2)
  585. assert plain.status()["triage_state"] == "disabled"
  586. assert plain.clear() is True
  587. assert [e for e in emitted2 if e["type"] == "triage"] == []