Files
sales-trainer/backend/tests/test_auto_close_try.py
T
Macky f63f1867f5 feat: trial follow-up drills, persona progress UI, LLM timeout 180s
- social trial: silent/gone follow-up outcomes with localized notice
  variants; gone is always a loss with possibility-framed debrief
- gone marker persists across judge outages; retries stay on the
  deterministic loss path (no roleplay reopen)
- bounded analysis_progress persisted during persona generation,
  exposed via safe serializer, polled + rendered as accessible UI
- LLM HTTP timeout 105s -> 180s for Qwen 3.8 (enable_thinking off)
- demo-account test clock made relative to current UTC
- regression coverage: follow-up branches, judge-failure retry,
  progress callback, timeout contract, progress serializer
- independent review finding verified stale against final tree

Tests: 532 backend, 29 frontend, prod build green
2026-10-02 12:53:59 +07:00

353 lines
14 KiB
Python

"""Follow-up contract: a sale chat ends only on win/loss.
`buy` / `walk` auto-close + summarize. `try` (customer will trial first) does
NOT close the session — a random follow-up event is rolled so the trainee
practices the follow-up:
1. customer goes silent (~2 days) -> trainee must follow up -> roll:
gone for good (instant loss + debrief) or hesitant (re-engages,
chat continues);
2. customer comes back on their own with a post-trial message.
"""
from __future__ import annotations
from app.llm import LLMError
class StubRandom:
"""Deterministic random.choice: pops from a queue, falls back to first."""
def __init__(self, seq: list):
self._seq = list(seq)
def choice(self, options):
if self._seq:
return self._seq.pop(0)
return options[0]
class StubSim:
"""Stubbed simulator: a persona reply + a per-turn judge.
Counts calls so tests can assert which turns skipped the LLM (the
follow-up canned-reply turns must not call persona_reply/evaluate_turn).
"""
def __init__(self, decision: str = "try"):
self.decision = decision
self.persona_calls = 0
self.evaluate_calls = 0
self.judge_error_once = False
self.judge_verdict = {
"outcome": "lost",
"score": 55,
"pain": "wants to trial before committing",
"why": "customer trialing first, not closed yet",
"failurePoints": [],
"coaching": [],
"painProgress": {"trial": 60},
}
def persona_reply(self, **kwargs):
self.persona_calls += 1
return "โอเคครับ ลองใช้ก่อนได้", {"decision": "none", "mood": 1}
def evaluate_turn(self, **kwargs):
self.evaluate_calls += 1
return {
"mood": 1,
"decision": self.decision,
"score_delta": 3,
"reason": "ลูกค้าตัดสินใจลองใช้ก่อน",
}
def judge(self, **kwargs):
if self.judge_error_once:
self.judge_error_once = False
raise LLMError("temporary judge outage")
return dict(self.judge_verdict)
def _auth_headers(token):
return {"Authorization": f"Bearer {token}"}
def _ready(client, user_store, login):
from scripts.mock_llm import MockLLM
user_store.complete_setup(
"admin", "[email protected]", "admin-ready-password",
accepted_terms=True, accepted_terms_at="2026-08-13T00:00:00Z",
)
token = login("admin", "admin-ready-password")["token"]
headers = _auth_headers(token)
client.application.extensions["llm"] = MockLLM()
response = client.post(
"/api/groups", json={"product": "CRM", "segment": "SME"}, headers=headers
)
assert response.status_code == 201, response.get_json()
gid = response.get_json()["group"]["id"]
analyzed = client.post(f"/api/groups/{gid}/analyze", headers=headers)
assert analyzed.status_code == 200, analyzed.get_json()
pid = analyzed.get_json()["personas"][0]["id"]
return gid, pid, headers
def _start(client, gid, pid, headers):
started = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/start",
json={"scenario": "social", "locale": "th", "mode": "preview"},
headers=headers,
)
assert started.status_code == 200, started.get_json()
assert started.get_json()["session"]["status"] == "active"
def _system_texts(body):
return [m.get("text", "") for m in body["messages"] if m.get("role") == "system"]
def _customer_texts(body):
return [m.get("text", "") for m in body["messages"] if m.get("role") == "customer"]
def _resume_status(client, gid, pid, headers):
r = client.get(
f"/api/chat/{gid}/personas/{pid}/chat/resume", headers=headers
)
assert r.status_code == 200, r.get_json()
return r.get_json()["session"]["status"]
def test_try_decision_does_not_close_session(client, user_store, login, monkeypatch):
gid, pid, headers = _ready(client, user_store, login)
_start(client, gid, pid, headers)
stub = StubSim(decision="try")
monkeypatch.setattr("app.api.chat_routes._sim", lambda g, p: stub)
# Force the follow-up roll to the "silent" event.
monkeypatch.setattr("app.api.chat_routes.random", StubRandom(["silent"]))
sent = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "ได้เลยครับ ลองใช้ก่อนได้"},
headers=headers,
)
assert sent.status_code == 200, sent.get_json()
body = sent.get_json()
# The chat does NOT close: no finished/debrief, session stays active.
assert body.get("finished") is not True
assert _resume_status(client, gid, pid, headers) == "active"
# A follow-up system note (silent event) is in the transcript.
texts = _system_texts(body)
assert any("2 วัน" in t and "ลูกค้า" in t for t in texts)
def test_silent_followup_gone_closes_lost(client, user_store, login, monkeypatch):
gid, pid, headers = _ready(client, user_store, login)
_start(client, gid, pid, headers)
stub = StubSim(decision="try")
stub.judge_verdict["outcome"] = "won"
monkeypatch.setattr("app.api.chat_routes._sim", lambda g, p: stub)
# try -> silent; trainee's follow-up -> gone for good.
monkeypatch.setattr("app.api.chat_routes.random", StubRandom(["silent", "gone"]))
client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "ได้เลยครับ ลองใช้ก่อนได้"},
headers=headers,
)
first_turn_persona, first_turn_eval = stub.persona_calls, stub.evaluate_calls
assert (first_turn_persona, first_turn_eval) == (1, 1) # the try turn used the LLM
# The trainee follows up — the customer is gone: instant loss + debrief.
sent = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "สวัสดีครับ พอดีลองใช้ดูเป็นยังไงบ้างครับ?"},
headers=headers,
)
assert sent.status_code == 200, sent.get_json()
body = sent.get_json()
assert body["finished"] is True
assert body["outcome"] == "lost"
assert body["session"]["status"] == "finished"
assert body["debrief"] is not None
assert any("ลูกค้า" in t and ("ขายครั้งนี้" in t or "การขาย" in t or "opportunity" in t) for t in _system_texts(body))
# The follow-up attempt itself is NOT an LLM turn (no persona reply,
# no per-turn evaluation) — only the final judge ran.
assert stub.persona_calls == first_turn_persona
assert stub.evaluate_calls == first_turn_eval
def test_gone_followup_retries_final_judge_without_reopening_roleplay(client, user_store, login, monkeypatch):
gid, pid, headers = _ready(client, user_store, login)
_start(client, gid, pid, headers)
stub = StubSim(decision="try")
stub.judge_error_once = True
monkeypatch.setattr("app.api.chat_routes._sim", lambda g, p: stub)
monkeypatch.setattr("app.api.chat_routes.random", StubRandom(["silent", "gone"]))
client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "ลองใช้ดูก่อนได้ครับ"}, headers=headers,
)
failed = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "ขอติดตามผลการทดลองใช้ครับ"}, headers=headers,
)
assert failed.status_code >= 500
persona_calls = stub.persona_calls
retried = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "ขอติดตามอีกครั้งครับ"}, headers=headers,
)
assert retried.status_code == 200, retried.get_json()
body = retried.get_json()
assert body["finished"] is True
assert body["outcome"] == "lost"
assert stub.persona_calls == persona_calls
def test_silent_followup_hesitant_reengages(client, user_store, login, monkeypatch):
gid, pid, headers = _ready(client, user_store, login)
_start(client, gid, pid, headers)
stub = StubSim(decision="try")
monkeypatch.setattr("app.api.chat_routes._sim", lambda g, p: stub)
# try -> silent; trainee's follow-up -> hesitant (re-engages, continues).
monkeypatch.setattr("app.api.chat_routes.random", StubRandom(["silent", "hesitant"]))
client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "ได้เลยครับ ลองใช้ก่อนได้"},
headers=headers,
)
first_turn_persona, first_turn_eval = stub.persona_calls, stub.evaluate_calls
assert (first_turn_persona, first_turn_eval) == (1, 1) # the try turn used the LLM
sent = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "สวัสดีครับ พอดีลองใช้ดูเป็นยังไงบ้างครับ?"},
headers=headers,
)
assert sent.status_code == 200, sent.get_json()
body = sent.get_json()
# The follow-up landed: the customer re-engages and the chat continues.
assert body.get("finished") is not True
assert _resume_status(client, gid, pid, headers) == "active"
assert any("ขอบคุณ" in t for t in _customer_texts(body))
# The follow-up attempt is NOT an LLM turn — the canned re-engagement
# reply is the customer line.
assert stub.persona_calls == first_turn_persona
assert stub.evaluate_calls == first_turn_eval
def test_returned_event_customer_messages_back(client, user_store, login, monkeypatch):
gid, pid, headers = _ready(client, user_store, login)
_start(client, gid, pid, headers)
stub = StubSim(decision="try")
monkeypatch.setattr("app.api.chat_routes._sim", lambda g, p: stub)
# try -> the customer comes back on their own with a post-trial message.
monkeypatch.setattr("app.api.chat_routes.random", StubRandom(["returned"]))
monkeypatch.setattr(
"app.api.chat_routes._followup_note",
lambda kind, locale: "⏳ ผ่านไป 2 วัน — ลูกค้าทักมาหลังได้ลองใช้แล้ว"
if kind == "returned" else "test follow-up notice",
)
sent = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "ได้เลยครับ ลองใช้ก่อนได้"},
headers=headers,
)
assert sent.status_code == 200, sent.get_json()
body = sent.get_json()
assert body.get("finished") is not True
assert _resume_status(client, gid, pid, headers) == "active"
# System note + the customer's own post-trial message are in the transcript.
texts = _system_texts(body)
assert any("2 วัน" in t and "ลูกค้า" in t and ("ทัก" in t or "ติดต่อกลับ" in t) for t in texts)
customers = _customer_texts(body)
assert any("ลอง" in t for t in customers)
def test_followup_notice_pools_have_multiple_safe_variants():
from app.api.chat_routes import (
_FOLLOWUP_SILENT,
_FOLLOWUP_EN_SILENT,
_SAFE_SYSTEM_MESSAGES,
)
assert len(_FOLLOWUP_SILENT) >= 3
assert len(_FOLLOWUP_EN_SILENT) >= 3
assert set(_FOLLOWUP_SILENT + _FOLLOWUP_EN_SILENT) <= _SAFE_SYSTEM_MESSAGES
def test_gone_debrief_explains_external_reasons_as_possibilities(client, user_store, login, monkeypatch):
gid, pid, headers = _ready(client, user_store, login)
_start(client, gid, pid, headers)
stub = StubSim(decision="try")
monkeypatch.setattr("app.api.chat_routes._sim", lambda g, p: stub)
monkeypatch.setattr("app.api.chat_routes.random", StubRandom(["silent", "gone"]))
client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "ลองใช้ดูก่อนได้ครับ"}, headers=headers,
)
sent = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "ขอติดตามผลการทดลองใช้ครับ"}, headers=headers,
)
assert sent.status_code == 200, sent.get_json()
body = sent.get_json()
assert body["finished"] is True
assert body["outcome"] == "lost"
assert body["debrief"] is not None
assert any(word in str(body["debrief"]).lower() for word in ("เปลี่ยนใจ", "ทดลองใช้", "คู่แข่ง", "better", "changed"))
def test_buy_decision_auto_closes_won(client, user_store, login, monkeypatch):
gid, pid, headers = _ready(client, user_store, login)
_start(client, gid, pid, headers)
stub = StubSim(decision="buy")
stub.judge_verdict["outcome"] = "won"
monkeypatch.setattr("app.api.chat_routes._sim", lambda g, p: stub)
sent = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "โอเค เอาเลยครับ"},
headers=headers,
)
assert sent.status_code == 200, sent.get_json()
body = sent.get_json()
assert body["finished"] is True
assert body["outcome"] == "won"
assert body["session"]["status"] == "finished"
def test_walk_decision_auto_closes_lost(client, user_store, login, monkeypatch):
gid, pid, headers = _ready(client, user_store, login)
_start(client, gid, pid, headers)
stub = StubSim(decision="walk")
stub.judge_verdict["outcome"] = "lost"
monkeypatch.setattr("app.api.chat_routes._sim", lambda g, p: stub)
sent = client.post(
f"/api/chat/{gid}/personas/{pid}/chat/send",
json={"text": "งั้นไม่เอาดีกว่าครับ"},
headers=headers,
)
assert sent.status_code == 200, sent.get_json()
body = sent.get_json()
assert body["finished"] is True
assert body["outcome"] == "lost"
assert body["session"]["status"] == "finished"