diff --git a/backend/app/api/chat_routes.py b/backend/app/api/chat_routes.py index db5fc7c..d732fd3 100644 --- a/backend/app/api/chat_routes.py +++ b/backend/app/api/chat_routes.py @@ -5,6 +5,7 @@ from collections.abc import Collection import functools import math import random +import secrets from flask import Blueprint, current_app, jsonify, request @@ -300,6 +301,44 @@ _FOLLOWUP_EN_RETURNERS = ( "Tried it, it's good — we'll go ahead and order. How does checkout work?", ) +_FOLLOWUP_SILENT = ( + "⏳ ผ่านไป 2 วันแล้ว ลูกค้ายังเงียบอยู่ — จะทักไปติดตามผลดีไหม?", + "⏳ เว้นมา 2 วัน ลูกค้ายังไม่ได้ติดต่อกลับ คุณจะส่งข้อความไปถามไถ่ไหม?", + "⏳ ลูกค้าเงียบไป 2 วันหลังทดลองใช้ ถึงเวลาทักไปติดตามแล้วหรือยัง?", + "⏳ ผ่านไป 2 วันแล้วยังไม่มีข่าวจากลูกค้า ลองทักไปติดตามผลดูไหม?", +) + +_FOLLOWUP_EN_SILENT = ( + "⏳ Two days have passed and the customer is still quiet — would you follow up?", + "⏳ It's been two days since the trial and they haven't replied. Want to check in?", + "⏳ The customer has been quiet for two days. Would you send a follow-up message?", + "⏳ Two days later, still no word from the customer. Is it time to reach out?", +) + +_FOLLOWUP_RETURNED_NOTICE = ( + "⏳ ผ่านไป 2 วัน — ลูกค้าทักมาหลังได้ลองใช้แล้ว", + "⏳ เว้นไป 2 วัน ลูกค้ากลับมาส่งข้อความหลังทดลองใช้", + "⏳ 2 วันหลังจากทดลอง ลูกค้าติดต่อกลับมาเอง", +) + +_FOLLOWUP_EN_RETURNED_NOTICE = ( + "⏳ Two days later — the customer messages you after trying it.", + "⏳ After two days, the customer gets back in touch following the trial.", + "⏳ Two days pass, and the customer reaches out after trying the product.", +) + +_FOLLOWUP_GONE = ( + "⏳ ลูกค้าไม่ตอบกลับหลังจากคุณติดตามผล จึงต้องยุติการขายครั้งนี้", + "⏳ หลังคุณทักไป ลูกค้ายังคงเงียบและไม่ติดต่อกลับ การขายครั้งนี้จบลงแล้ว", + "⏳ ลูกค้าไม่ได้ตอบข้อความติดตามผล เคสนี้จึงปิดเป็นการขายที่ไม่สำเร็จ", +) + +_FOLLOWUP_EN_GONE = ( + "⏳ The customer doesn't reply to your follow-up, so this sale is lost.", + "⏳ The customer stays silent after your follow-up; this sale has ended.", + "⏳ No response to your follow-up. This opportunity is now closed as lost.", +) + _FOLLOWUP_HESSITANT = ( "โอเคค่ะ ขอบคุณที่ติดต่อมา จะพิจารณาอย่างจริงจังนะคะ", "ขอบคุณที่ทักมาค่ะ จะลองพิจารณาจริงจังดู", @@ -312,7 +351,12 @@ _FOLLOWUP_EN_HESSITANT = ( def _followup_note(kind: str, locale: str) -> str: - return _NOTES["en" if locale == "en" else "th"][kind] + pools = { + "silent": _FOLLOWUP_EN_SILENT if locale == "en" else _FOLLOWUP_SILENT, + "returned": _FOLLOWUP_EN_RETURNED_NOTICE if locale == "en" else _FOLLOWUP_RETURNED_NOTICE, + "gone": _FOLLOWUP_EN_GONE if locale == "en" else _FOLLOWUP_GONE, + } + return secrets.choice(pools[kind]) def _post_trial_reply(locale: str) -> str: @@ -345,6 +389,12 @@ _SAFE_SYSTEM_MESSAGES = frozenset({ "⏳ 2-3 weeks later ... the customer who asked earlier went quiet; now they re-contact, more ready to decide.", *_NOTES["th"].values(), *_NOTES["en"].values(), + *_FOLLOWUP_SILENT, + *_FOLLOWUP_EN_SILENT, + *_FOLLOWUP_RETURNED_NOTICE, + *_FOLLOWUP_EN_RETURNED_NOTICE, + *_FOLLOWUP_GONE, + *_FOLLOWUP_EN_GONE, }) @@ -416,21 +466,46 @@ def _finalize_session(s, session: dict, group: dict, persona: dict) -> tuple[dic return session, debrief messages = _safe_session_messages(session.get("messages")) - internal = _safe_roleplay_internal(session.get("internal")) + raw_internal = session.get("internal") + followup_kind = ( + raw_internal.get("followup") + if isinstance(raw_internal, dict) + and raw_internal.get("followup") in {"silent", "returned", "gone", "hesitant"} + else None + ) + internal = _safe_roleplay_internal(raw_internal) # Persist the latest transcript before the provider call. A failed judge # therefore leaves an active, retryable session rather than losing turns. - s["sessions"].update(session["id"], messages=messages, internal=internal) + persisted_internal = ( + {**internal, "followup": followup_kind} + if followup_kind is not None + else internal + ) + s["sessions"].update(session["id"], messages=messages, internal=persisted_internal) sim = _sim(group, persona) verdict = sim.judge(persona=persona, messages=messages, internal=internal) if not isinstance(verdict, dict): raise LLMError("judge returned an invalid response") - outcome = "won" if verdict.get("outcome") == "won" else "lost" + outcome = "lost" if followup_kind == "gone" else ("won" if verdict.get("outcome") == "won" else "lost") score = ( _bounded_int(verdict.get("score", 0), default=0, minimum=0, maximum=100) if isinstance(verdict, dict) else 0 ) public_debrief = _public_debrief(sim, messages, outcome, score) + if followup_kind == "gone": + possible_reasons = ( + "สาเหตุจริงยังยืนยันไม่ได้ ลูกค้าอาจเปลี่ยนใจ ไม่พอใจกับการทดลองใช้ " + "หรือพบทางเลือกที่เหมาะกว่า — ควรถือเป็นความเป็นไปได้ ไม่ใช่ข้อเท็จจริง" + ) + existing_why = _bounded_text(public_debrief.get("why")) + public_debrief["why"] = f"{existing_why} {possible_reasons}".strip() + coaching = _string_list(public_debrief.get("coaching")) + coaching.append( + "เมื่อลูกค้าขอทดลองใช้ ให้นัดวันติดตามและตกลงช่องทางไว้ล่วงหน้า " + "จากนั้นติดตามอย่างสุภาพ พร้อมถามประสบการณ์ใช้งานก่อนเสนอขั้นต่อไป" + ) + public_debrief["coaching"] = coaching debrief = _safe_judge_debrief(verdict, outcome, persona, public_debrief) stored_debrief = {**debrief, "_public_debrief": public_debrief} updated = s["sessions"].update( @@ -810,6 +885,26 @@ def send_message(gid: str, pid: str): # hesitant -> customer re-engages, chat continues). ── raw_internal = session.get("internal") followup_phase = raw_internal.get("followup") if isinstance(raw_internal, dict) else None + if followup_phase == "gone": + # A prior final-judge outage must not reopen the roleplay after the + # customer has gone. Keep retries on the same deterministic loss path. + try: + finalized, debrief = _finalize_session( + s, + {**session, "messages": messages, "internal": raw_internal}, + group, + persona, + ) + except LLMError as exc: + raise internal_error("LLM service unavailable", exc) + return jsonify({ + "reply": None, + "messages": _safe_session_messages(finalized.get("messages") or messages), + "finished": True, + "outcome": finalized.get("outcome"), + "debrief": debrief, + "session": serialize_session(finalized), + }) if followup_phase == "silent": followup_internal = _safe_roleplay_internal(session.get("internal")) followup_internal["followup"] = random.choice(["gone", "hesitant"]) diff --git a/backend/app/api/group_routes.py b/backend/app/api/group_routes.py index 4e15bdd..547f934 100644 --- a/backend/app/api/group_routes.py +++ b/backend/app/api/group_routes.py @@ -73,6 +73,7 @@ ADMIN_EDITABLE_PERSONA_FIELDS = ADMIN_VISIBLE_PERSONA_FIELDS - {"id"} GROUP_VISIBLE_FIELDS = { "id", "org_id", "title", "status", "visibility", "created_at", "updated_at", "input", "sales_kit", "personas", "report", "error", + "analysis_progress", } GROUP_INPUT_LIMITS = { @@ -131,6 +132,24 @@ def _canonical_personas(value: object) -> list[dict]: return [persona for raw in value if (persona := _validated_persona(raw)) is not None] +def _safe_analysis_progress(value: object) -> dict[str, int | str]: + """Expose only bounded progress fields, never worker inputs or exceptions.""" + if not isinstance(value, dict): + return {} + stage = value.get("stage") + if stage not in {"sales_kit", "personas", "report", "complete"}: + return {} + completed = value.get("completed") + total = value.get("total") + if ( + isinstance(completed, bool) or not isinstance(completed, int) + or isinstance(total, bool) or not isinstance(total, int) + or total < 0 or completed < 0 or completed > total + ): + return {} + return {"stage": stage, "completed": completed, "total": total} + + def serialize_group(group: dict, actor: dict) -> dict: """Serialize a group without exposing latent persona recipe data.""" source = safe_group_input(group.get("input")) @@ -147,6 +166,7 @@ def serialize_group(group: dict, actor: dict) -> dict: org_id=actor.get("org_id"), ) ) + view["analysis_progress"] = _safe_analysis_progress(group.get("analysis_progress")) # Historical groups may contain legacy raw exception text. Normalize at the API # boundary so old records cannot leak paths/provider responses either. if view.get("error"): @@ -656,7 +676,13 @@ def analyze_group(gid: str): if group.get("status") == "analyzing" and not _is_stale_analyzing(group): return jsonify({"group": serialize_group(group, current_user()), "status": "analyzing"}), 202 - s["groups"].update(gid, status="analyzing", error=None, analysis_started_at=_now_iso()) + s["groups"].update( + gid, + status="analyzing", + error=None, + analysis_started_at=_now_iso(), + analysis_progress={"stage": "sales_kit", "completed": 0, "total": 1}, + ) app = current_app._get_current_object() llm = s["llm"] if app.testing: @@ -740,11 +766,27 @@ def _run_analysis(app, gid: str, inp: dict, persona_channel: str, llm) -> None: app.logger.exception("analysis failed for group %s (sales kit)", gid) s["groups"].update(gid, status="failed", error="analysis_failed") return + s["groups"].update( + gid, + analysis_progress={"stage": "personas", "completed": 0, "total": 15}, + ) + + def report_persona_progress(completed: int, total: int) -> None: + s["groups"].update( + gid, + analysis_progress={ + "stage": "personas", + "completed": completed, + "total": total, + }, + ) + try: generated_personas = PersonaGenerator(llm).generate( sales_kit=sales_kit, language=inp.get("language", "th"), channel=persona_channel, + on_progress=report_persona_progress, ) if not isinstance(generated_personas, list) or not generated_personas: raise ValueError("persona generation returned no usable personas") @@ -764,6 +806,10 @@ def _run_analysis(app, gid: str, inp: dict, persona_channel: str, llm) -> None: current_before_publish.get("personas") if isinstance(current_before_publish, dict) else [], personas, ) + s["groups"].update( + gid, + analysis_progress={"stage": "report", "completed": 0, "total": 1}, + ) try: report = build_report(sales_kit=sales_kit, personas=personas, language=inp.get("language", "th")) except Exception: @@ -780,6 +826,10 @@ def _run_analysis(app, gid: str, inp: dict, persona_channel: str, llm) -> None: personas=personas, report=report, ) + s["groups"].update( + gid, + analysis_progress={"stage": "complete", "completed": 1, "total": 1}, + ) except (TypeError, ValueError): app.logger.exception("analysis failed for group %s (publish)", gid) s["groups"].update(gid, status="failed", error="analysis_failed") diff --git a/backend/app/llm.py b/backend/app/llm.py index b4e4430..e8b45c8 100644 --- a/backend/app/llm.py +++ b/backend/app/llm.py @@ -55,7 +55,7 @@ class LLMClient: raise LLMError("LLM_API_KEY is not configured in .env") if not self.base_url: raise LLMError("LLM_BASE_URL is not configured (unknown provider)") - self.client = OpenAI(base_url=self.base_url, api_key=self.api_key, timeout=105.0, max_retries=0) + self.client = OpenAI(base_url=self.base_url, api_key=self.api_key, timeout=180.0, max_retries=0) def complete( self, diff --git a/backend/app/services/persona_generator.py b/backend/app/services/persona_generator.py index 9adf26b..9b061e3 100644 --- a/backend/app/services/persona_generator.py +++ b/backend/app/services/persona_generator.py @@ -10,8 +10,8 @@ from __future__ import annotations import json import os import time -from concurrent.futures import ThreadPoolExecutor -from typing import Any +from concurrent.futures import ThreadPoolExecutor, as_completed +from typing import Any, Callable from ..llm import LLMClient, LLMError from .persona_prompts import PERSONA_SYSTEM, PERSONA_SYSTEM_TIER @@ -43,6 +43,7 @@ class PersonaGenerator: sales_kit: dict[str, Any], language: str = "en", channel: str = "facebook", + on_progress: Callable[[int, int], None] | None = None, ) -> list[dict[str, Any]]: if channel not in PERSONA_CHANNELS: raise ValueError("persona channel must be facebook or line") @@ -56,16 +57,19 @@ class PersonaGenerator: # One persona per call, 15 calls total (5 per tier). Each call is small enough # to finish under the proxy timeout; they run in a small thread pool. slots = [(tier, slot) for tier in TIERS for slot in range(PER_TIER)] + personas: list[dict[str, Any] | None] = [None] * len(slots) with ThreadPoolExecutor(max_workers=_parallel_workers()) as pool: futures = { - pool.submit(self._generate_one, base, tier, slot, channel): (tier, slot) - for tier, slot in slots + pool.submit(self._generate_one, base, tier, slot, channel): index + for index, (tier, slot) in enumerate(slots) } - personas: list[dict[str, Any]] = [] - for future in futures: - tier, slot = futures[future] - personas.append(future.result()) - return self._normalize_personas(personas, channel) + for completed, future in enumerate(as_completed(futures), start=1): + personas[futures[future]] = future.result() + if on_progress is not None: + on_progress(completed, len(slots)) + return self._normalize_personas( + [persona for persona in personas if persona is not None], channel + ) def _generate_one(self, base: str, tier: str, slot: int, channel: str) -> dict[str, Any]: """Generate a single persona (one LLM call) and validate it. Retries on its own.""" diff --git a/backend/tests/test_analysis_progress.py b/backend/tests/test_analysis_progress.py new file mode 100644 index 0000000..a1b59ca --- /dev/null +++ b/backend/tests/test_analysis_progress.py @@ -0,0 +1,35 @@ +from app.api.group_routes import _safe_analysis_progress, serialize_group + + +def test_analysis_progress_serializer_keeps_only_bounded_public_fields(): + assert _safe_analysis_progress({ + "stage": "personas", + "completed": 4, + "total": 15, + "prompt": "private prompt", + "provider_error": "/private/path", + }) == {"stage": "personas", "completed": 4, "total": 15} + + +def test_analysis_progress_serializer_rejects_invalid_or_unknown_state(): + assert _safe_analysis_progress({"stage": "secret", "completed": 1, "total": 1}) == {} + assert _safe_analysis_progress({"stage": "personas", "completed": True, "total": 15}) == {} + assert _safe_analysis_progress({"stage": "personas", "completed": 16, "total": 15}) == {} + + +def test_group_serializer_exposes_sanitized_analysis_progress_only(): + view = serialize_group({ + "id": "group-1", + "status": "analyzing", + "analysis_progress": { + "stage": "report", + "completed": 0, + "total": 1, + "error": "private provider detail", + }, + "worker_input": "must not leak", + }, {"role": "user"}) + + assert view["analysis_progress"] == {"stage": "report", "completed": 0, "total": 1} + assert "worker_input" not in view + assert "private provider detail" not in str(view) diff --git a/backend/tests/test_auto_close_try.py b/backend/tests/test_auto_close_try.py index 5af6b64..a313201 100644 --- a/backend/tests/test_auto_close_try.py +++ b/backend/tests/test_auto_close_try.py @@ -36,6 +36,7 @@ class StubSim: self.decision = decision self.persona_calls = 0 self.evaluate_calls = 0 + self.judge_error_once = False self.judge_verdict = { "outcome": "lost", "score": 55, @@ -60,6 +61,9 @@ class StubSim: } def judge(self, **kwargs): + if self.judge_error_once: + self.judge_error_once = False + raise LLMError("temporary judge outage") return dict(self.judge_verdict) @@ -136,7 +140,7 @@ def test_try_decision_does_not_close_session(client, user_store, login, monkeypa 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) + assert any("2 วัน" in t and "ลูกค้า" in t for t in texts) def test_silent_followup_gone_closes_lost(client, user_store, login, monkeypatch): @@ -144,6 +148,7 @@ def test_silent_followup_gone_closes_lost(client, user_store, login, monkeypatch _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"])) @@ -169,13 +174,43 @@ def test_silent_followup_gone_closes_lost(client, user_store, login, monkeypatch assert body["outcome"] == "lost" assert body["session"]["status"] == "finished" assert body["debrief"] is not None - assert any("หายไปเลย" in t for t in _system_texts(body)) + 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) @@ -219,6 +254,11 @@ def test_returned_event_customer_messages_back(client, user_store, login, monkey 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", @@ -232,11 +272,46 @@ def test_returned_event_customer_messages_back(client, user_store, login, monkey 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 for t in texts) + 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) diff --git a/backend/tests/test_demo_accounts.py b/backend/tests/test_demo_accounts.py index fcd2b4a..969ff40 100644 --- a/backend/tests/test_demo_accounts.py +++ b/backend/tests/test_demo_accounts.py @@ -15,7 +15,7 @@ from app.services.demo_delivery import _HttpsOnlyRedirectHandler from scripts.mock_llm import MockLLM -FIXED_NOW = dt.datetime(2026, 8, 23, 12, 0, tzinfo=dt.timezone.utc) +FIXED_NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0) def _headers(token: str) -> dict[str, str]: diff --git a/backend/tests/test_final_judge.py b/backend/tests/test_final_judge.py index 860fb74..6fa358f 100644 --- a/backend/tests/test_final_judge.py +++ b/backend/tests/test_final_judge.py @@ -88,6 +88,26 @@ def _run(monkeypatch, *, verdict=None, error=False, session=None): return sessions, sim, updated, debrief +def test_gone_followup_marker_survives_final_judge_failure_for_safe_retry(monkeypatch): + session = _session() + session["internal"]["followup"] = "gone" + sessions = FakeSessions(session) + sim = StubSim(error=True) + monkeypatch.setattr(chat_routes, "_sim", lambda group, persona: sim) + + with pytest.raises(LLMError): + chat_routes._finalize_session( + {"sessions": sessions}, + sessions.row, + {"sales_kit": {}}, + {"name": "Customer", "pains": []}, + ) + + assert sessions.row["status"] == "active" + assert sessions.row["internal"]["followup"] == "gone" + assert sim.judge_calls == 1 + + def test_final_judge_supplies_score_and_debrief_for_automatic_buy(monkeypatch): sessions, sim, updated, debrief = _run(monkeypatch) diff --git a/backend/tests/test_llm_timeout.py b/backend/tests/test_llm_timeout.py new file mode 100644 index 0000000..cc20831 --- /dev/null +++ b/backend/tests/test_llm_timeout.py @@ -0,0 +1,15 @@ +from app.llm import LLMClient + + +def test_llm_client_allows_slow_model_calls(monkeypatch): + captured = {} + + class StubOpenAI: + def __init__(self, **kwargs): + captured.update(kwargs) + + monkeypatch.setattr("app.llm.OpenAI", StubOpenAI) + LLMClient(base_url="https://llm.example/v1", api_key="test-key", model="slow-model") + + assert captured["timeout"] == 180.0 + assert captured["max_retries"] == 0 diff --git a/backend/tests/test_persona_generator_progress.py b/backend/tests/test_persona_generator_progress.py new file mode 100644 index 0000000..58a87c0 --- /dev/null +++ b/backend/tests/test_persona_generator_progress.py @@ -0,0 +1,31 @@ +from app.services.persona_generator import PersonaGenerator + + +class StubLLM: + def complete_json(self, _system_prompt, user_prompt, **_kwargs): + tier = next(t for t in ("A", "B", "C") if f"tier {t}" in user_prompt) + return {"personas": [{ + "name": "Test customer", + "tier": tier, + "channel": "facebook", + "initiation_mode": "customer", + "pains": [], + "objections": [], + "negotiation_levers": [], + "special": "wrong_text" if tier == "C" else "", + }]} + + +def test_generate_reports_each_persona_completion(monkeypatch): + monkeypatch.setattr("app.services.persona_generator.TIERS", ["A", "B", "C"]) + monkeypatch.setattr("app.services.persona_generator.PER_TIER", 1) + monkeypatch.setattr("app.services.persona_generator.TARGET", 3) + progress = [] + + PersonaGenerator(StubLLM()).generate( + sales_kit={}, + channel="facebook", + on_progress=lambda completed, total: progress.append((completed, total)), + ) + + assert progress == [(1, 3), (2, 3), (3, 3)] diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index d524f22..1b36c24 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -238,3 +238,11 @@ cd backend && uv run python run.py # Flask :5001 - `docs/engineering-log/2026-08-15-s4-3-org-users-repositories.md` — tenant-scoped repository contracts and adapters, with no runtime cutover. - `docs/engineering-log/2026-08-15-s4-3-offline-dialect-remediation.md` — offline Alembic dialect finding, test-first fix, verification, and pending review. - `docs/engineering-log/2026-08-16-s4-4-importer-errorhandler-commit.md` — re-verification (330 tests on clean lock venv) and commit of the staged S4.4 importer + error-handler hardening increment. + +## 2026-10-02 trial follow-up and analysis progress — local verification +- Working tree is on `main` at HEAD `8c89b17`; all changes below are uncommitted. Do not push/deploy without owner approval (`project.md` CON-003). +- Implemented: follow-up notice variants, gone/loss debrief with possibility-framed explanations, retained retry marker across judge outage, forced gone outcome to loss, persisted bounded analysis progress + UI polling, progress indicator, LLM timeout 180s, finite client polling 30m. +- Confirmed existing lifecycle: one-shot finished persona exposes summary and cannot start another trainee chat; see existing chat route/list persona tests. +- Historic “customer will try” runtime error could not be confirmed from local logs; code-path regression was reproduced by tests. Do not claim the exact old error was reproduced. +- Verification: backend `python -m pytest -q` **532 passed**; `python -m compileall -q app tests` passed; frontend `npm run test:unit -- --reporter=dot` **29 passed**; `npm run build` passed; local served SPA returned HTTP 200 and fresh progress UI bundle verified; `git diff --check` passed. Full evidence: `docs/engineering-log/2026-10-02-trial-progress-followup.md`. +- Review: independent current-tree reviewer `deleg_5ef11e88` returned REJECT on one finding (gone session reopenable after judge failure). Verified **stale** against the final tree: the reviewer read a pre-fix `chat_routes.py` snapshot — the current tree has the `followup_phase == "gone"` retry branch (`chat_routes.py:888`) plus the regression tests the reviewer called missing, and both pass; full suite re-run green post-review (532). No other confirmed blocker. Status: local verification and review complete; uncommitted, no push/deploy per CON-003. No production/live-model/tenant testing performed. diff --git a/docs/engineering-log.md b/docs/engineering-log.md index d791f45..eeb4c34 100644 --- a/docs/engineering-log.md +++ b/docs/engineering-log.md @@ -32,7 +32,7 @@ Informed by MiroFish (CrowdSight engine) + the hermes-brain-and-tools CrowdSight | S4.4 JSON importer | local SQLite and temporary-local PostgreSQL dry-run/apply/idempotency/conflict-rollback gates passed; importer + error-handler hardening committed; target apply blocked | 2026-08-16 | `docs/engineering-log/2026-08-15-s4-4-json-import.md`, `docs/engineering-log/2026-08-15-postgresql-import-gate.md`, `docs/engineering-log/2026-08-16-s4-4-importer-errorhandler-commit.md`, `docs/test-evidence/2026-08-15-postgresql-import.md` | target snapshot checksum/count comparison, retained backup, and operator-approved rollback rehearsal | | UX/UI redesign + marketing website | implemented + locally verified (build clean, 4/4 unit tests, independent review PASS, responsive verified); uncommitted; deploy pending operator approval | 2026-08-19 | `docs/engineering-log/2026-08-19-ux-redesign-and-marketing-site.md`, `website/`, `git diff` | operator approves push (auto-deploys); confirm production `JWT_SECRET` before deploy | | OAuth Google + Facebook login/register | implemented + locally verified (348 backend tests incl. 11 new, frontend build + 4/4 unit, manual security review PASS, no new deps); uncommitted | 2026-08-20 | `docs/engineering-log/2026-08-20-oauth-google-facebook.md`, `backend/app/services/oauth.py`, `backend/app/api/oauth_routes.py`, `backend/tests/test_oauth.py` | operator approves push; set OAUTH_* creds + OAUTH_DEFAULT_ORG in EasyPanel env to enable (disabled by default, fail-closed) | -| Training product-to-persona flow + security remediation | exact-current local code/security gate passed 8/8 independent scopes; production-operation gate pending | 2026-08-25 | `docs/engineering-log/2026-08-24-training-security-review.md`, `docs/test-evidence/2026-08-24-training-security-review.md` | operator decides whether to stage/commit/push; live OAuth or production verification remains a separate approval gate | +| Sales Trainer — try follow-up, gone/loss retry, analysis progress, slow-model timeout | implemented; local verification passed; exact-current reviewer pending | 2026-10-02 | `docs/engineering-log/2026-10-02-trial-progress-followup.md` (532 backend tests, 29 frontend tests, build + served bundle) | apply any blocking reviewer feedback; operator approval needed before commit/push/deploy | ## Guardrails - Public self-registration may create only role `user`; super-admin bootstrap is @@ -43,6 +43,7 @@ Informed by MiroFish (CrowdSight engine) + the hermes-brain-and-tools CrowdSight ## Entry index - `2026-08-24-training-security-review.md` — current Training flow/security remediation evidence, review timeout handling, and blocked stage/commit/push gate. +- `2026-10-02-trial-progress-followup.md` — `try` follow-up state machine/debrief retry, safe progress polling/UI, 180-second LLM timeout, and local verification; exact-current independent review pending. - `2026-08-07-build-out.md` — M0–M7 build-out, decisions, verification, current state. - `2026-08-07-security-ux.md` — security hardening (path traversal, IDOR, XSS) + UX/UI polish. - `2026-08-07-auth-gitea.md` — username login + first-time admin setup + Gitea push. diff --git a/docs/engineering-log/2026-10-02-trial-progress-followup.md b/docs/engineering-log/2026-10-02-trial-progress-followup.md new file mode 100644 index 0000000..d4ba28c --- /dev/null +++ b/docs/engineering-log/2026-10-02-trial-progress-followup.md @@ -0,0 +1,41 @@ +# Sales Trainer — Trial Follow-up and Persona Progress + +## Status +Complete. Implementation, local verification, and independent review are all closed. No commit, push, deploy, production access, or live-provider call was performed. + +## Scope and findings +- Follow-up flow preserves the randomized silent / customer-recontacts-first branches, with multiple locale-specific system notice variants. A silent customer's first seller follow-up can resolve to gone/loss or hesitant/re-engagement. +- Confirmed bug: `_safe_roleplay_internal()` intentionally drops follow-up metadata for the roleplay prompt. `_finalize_session()` then could lose `followup=gone` before final judging, which removed the gone-specific debrief rationale and could leave retry behavior inconsistent after a judge outage. Kept the marker only in persisted internal session state, passed sanitized state to roleplay/judge, forced gone outcome to lost, and retried the deterministic loss path without reopening roleplay. +- Exact historic error reported at the “customer will try” message was not available in local logs and was not represented as reproduced. The confirmed code-path defect above was reproduced with regression tests. +- Persona completion progress is persisted as bounded stage/count metadata, exposed only through the existing group serializer, polled by the frontend, and displayed accessibly during generation. +- Existing one-shot lifecycle behavior was inspected: finished sessions are served as summaries and cannot be restarted as trainee sessions; the persona card switches from Chat to Summary based on `my_outcome`. Existing backend tests remain part of the full suite. +- OpenAI-compatible LLM HTTP timeout increased from 105 to 180 seconds. Frontend analysis polling remains finite at 30 minutes. +- Made the demo-account test clock relative to current UTC because the old August 2026 constant caused otherwise unrelated trial-expiry failures in October 2026. + +## Changed files +- `backend/app/api/chat_routes.py` +- `backend/app/api/group_routes.py` +- `backend/app/llm.py` +- `backend/app/services/persona_generator.py` +- `backend/tests/test_auto_close_try.py` +- `backend/tests/test_final_judge.py` +- `backend/tests/test_analysis_progress.py` +- `backend/tests/test_llm_timeout.py` +- `backend/tests/test_persona_generator_progress.py` +- `backend/tests/test_demo_accounts.py` +- `frontend/src/api/index.js` +- `frontend/src/views/GroupBuilder.vue` +- `frontend/src/views/GroupBuilder.spec.js` + +## Verification evidence +- `cd backend && python -m pytest -q` — **532 passed**. +- `cd backend && python -m compileall -q app tests` — passed. +- `cd frontend && npm run test:unit -- --reporter=dot` — **29 passed / 7 test files**. +- `cd frontend && npm run build` — passed, Vite transformed 1,775 modules. +- Served local built SPA on port 4321; HTTP 200 and the fresh `GroupBuilder` bundle contained `analysis_progress` and the Thai progress stage label. +- `git diff --check` — passed. +- Static scan of added diff lines found no hardcoded-secret patterns, shell injection, eval/exec, pickle loading, or formatted SQL execution patterns. +- Independent current-tree reviewer — verdict received: REJECT on one finding (a "gone" session reopenable after final-judge failure, retry falling through to normal persona reply). Verified against the final tree: **stale/invalid** — the reviewer read a pre-fix snapshot of `chat_routes.py`. The current tree has the `followup_phase == "gone"` retry branch (`chat_routes.py:888`) and the exact regression tests the reviewer called missing (`test_gone_followup_retries_final_judge_without_reopening_roleplay`, `test_gone_followup_marker_survives_final_judge_failure_for_safe_retry`); both pass, and the full suite is re-run green after the review. No other confirmed blocker was reported. + +## Remaining / next action +None in scope. Push/deploy intentionally out of scope per `project.md` (CON-003: commit/push/deploy requires operator approval). diff --git a/frontend/src/api/index.js b/frontend/src/api/index.js index 99f382d..4457aea 100644 --- a/frontend/src/api/index.js +++ b/frontend/src/api/index.js @@ -51,14 +51,16 @@ export const api = { updateGroupVisibility: (id, visibility) => request('PATCH', `/api/groups/${id}/visibility`, { visibility }), groupReport: (id) => request('GET', `/api/groups/${id}/report?format=json`), deleteGroup: (id) => request('DELETE', `/api/groups/${id}`), - analyzeGroup: async (id) => { - await request('POST', `/api/groups/${id}/analyze`) + analyzeGroup: async (id, onProgress = () => {}) => { + const started = await request('POST', `/api/groups/${id}/analyze`) + onProgress(started?.group) // Analysis runs server-side because local LLM generation can take several minutes. // Poll the existing group resource until it is ready/failed; stop after 30 minutes. const deadline = Date.now() + 30 * 60 * 1000 while (Date.now() < deadline) { await new Promise((resolve) => setTimeout(resolve, 3000)) const result = await request('GET', `/api/groups/${id}`) + onProgress(result?.group) const status = result?.group?.status if (status === 'ready') return result if (status === 'failed') throw new Error('analysis failed') diff --git a/frontend/src/views/GroupBuilder.spec.js b/frontend/src/views/GroupBuilder.spec.js new file mode 100644 index 0000000..b2f4939 --- /dev/null +++ b/frontend/src/views/GroupBuilder.spec.js @@ -0,0 +1,42 @@ +import { mount, flushPromises } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import GroupBuilder from './GroupBuilder.vue' +import { api } from '../api' + +const push = vi.fn() +vi.mock('vue-router', () => ({ useRouter: () => ({ push }) })) +vi.mock('../api', async (importOriginal) => ({ + ...(await importOriginal()), + api: { + createGroup: vi.fn(), + analyzeGroup: vi.fn(), + }, +})) + +describe('GroupBuilder analysis progress', () => { + let finishAnalysis + beforeEach(() => { + vi.clearAllMocks() + api.createGroup.mockResolvedValue({ group: { id: 'group-1' } }) + api.analyzeGroup.mockImplementation(async (_id, onProgress) => { + onProgress({ analysis_progress: { stage: 'personas', completed: 4, total: 15 } }) + await new Promise((resolve) => { finishAnalysis = resolve }) + return { group: { status: 'ready' } } + }) + }) + + it('passes polled analysis progress through to the visible progress indicator', async () => { + const wrapper = mount(GroupBuilder, { + global: { stubs: { RouterLink: { template: '' } } }, + }) + await wrapper.get('textarea').setValue('ระบบ POS สำหรับร้านอาหาร') + await wrapper.get('[data-testid="create-group"]').trigger('click') + await flushPromises() + + expect(api.analyzeGroup).toHaveBeenCalledWith('group-1', expect.any(Function)) + expect(wrapper.text()).toContain('4 / 15 persona') + expect(wrapper.text()).toContain('กำลังสร้างบุคคลต้นแบบ') + finishAnalysis() + await flushPromises() + }) +}) diff --git a/frontend/src/views/GroupBuilder.vue b/frontend/src/views/GroupBuilder.vue index f2be3ae..b480c5f 100644 --- a/frontend/src/views/GroupBuilder.vue +++ b/frontend/src/views/GroupBuilder.vue @@ -75,6 +75,14 @@
อัปโหลดไฟล์กลุ่มเป้าหมายหรือรายละเอียดสินค้าที่มีอยู่แล้ว แทนการกรอกช่องด้านบนได้ (กรอกหรืออัปโหลดอย่างใดอย่างหนึ่งก็พอ)
+
+ {{ progressLabel }} + + + {{ progress.completed }} / {{ progress.total }} persona + + ระบบกำลังประมวลผล อาจใช้เวลาสักครู่ +