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
This commit is contained in:
Macky committed 2026-10-02 12:53:59 +07:00
1 parent 8c89b17f64
commit f63f1867f5
18 files changed
+545 -24

No files matched your search

+99 -4
View File
@@ -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"])
+51 -1
View File
@@ -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")
+1 -1
View File
@@ -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,
+13 -9
View File
@@ -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."""
+35
View File
@@ -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)
+78 -3
View File
@@ -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)
+1 -1
View File
@@ -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]:
+20
View File
@@ -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)
+15
View File
@@ -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
@@ -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)]
+8
View File
@@ -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.
+2 -1
View File
@@ -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.
@@ -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).
+4 -2
View File
@@ -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')
+42
View File
@@ -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: '<a><slot /></a>' } } },
})
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()
})
})
+19 -2
View File
@@ -75,6 +75,14 @@
<div class="muted label-hint">อัปโหลดไฟล์กลุ่มเป้าหมายหรือรายละเอียดสินค้าที่มีอยู่แล้ว แทนการกรอกช่องด้านบนได้ (กรอกหรืออัปโหลดอย่างใดอย่างหนึ่งก็พอ)</div>
<input type="file" multiple accept=".pdf,.md,.txt,.docx,.xlsx" @change="onFiles" />
<div v-if="busy" class="analysis-progress" role="status" aria-live="polite">
<strong>{{ progressLabel }}</strong>
<progress :value="progress.completed" :max="Math.max(progress.total, 1)"></progress>
<span v-if="progress.stage === 'personas'" class="muted">
{{ progress.completed }} / {{ progress.total }} persona
</span>
<span v-else class="muted">ระบบกำลังประมวลผล อาจใช้เวลาสักครู่</span>
</div>
<div class="error" v-if="error" role="alert">
{{ error }}
<router-link v-if="failedGroupPath" :to="failedGroupPath" class="btn-back">{{ i18n.t('training') }}</router-link>
@@ -87,7 +95,7 @@
</template>
<script setup>
import { ref } from 'vue'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Box, ListChecks, Paperclip, PlusCircle, ArrowLeft, Layers } from 'lucide-vue-next'
import { api } from '../api'
@@ -100,6 +108,13 @@ const files = ref([])
const error = ref('')
const failedGroupPath = ref('')
const busy = ref(false)
const progress = ref({ stage: 'sales_kit', completed: 0, total: 1 })
const progressLabel = computed(() => ({
sales_kit: 'กำลังวิเคราะห์ข้อมูลสินค้า',
personas: 'กำลังสร้างบุคคลต้นแบบ',
report: 'กำลังจัดทำรายงานสรุป',
complete: 'สร้างบุคคลต้นแบบเสร็จแล้ว',
}[progress.value.stage] || 'กำลังเตรียมการ'))
function onFiles(e) {
files.value = Array.from(e.target.files || [])
@@ -120,7 +135,9 @@ async function create() {
const gid = data.group.id
// Auto-generate personas right away (no separate Analyze button needed).
try {
await api.analyzeGroup(gid)
await api.analyzeGroup(gid, (group) => {
if (group?.analysis_progress) progress.value = group.analysis_progress
})
} catch {
// Keep the newly created product reachable and show the failure before
// the user chooses where to retry it.
+38
View File
@@ -0,0 +1,38 @@
# Sales Trainer — Current Execution Plan
## Status
Complete. Implementation, local verification, and independent review are all closed. No commit, push, deploy, or live-provider testing.
## Current phase / active task
Complete. All implementation, local verification, and independent review closed. Awaiting owner approval for commit/push/deploy (CON-003).
## Last update
2026-10-02. Project requirements reconciled from the latest owner instruction in `project.md`. Legacy architecture and security context reviewed in `docs/plan.md`, `docs/HANDOFF.md`, and `docs/engineering-log/2026-08-24-training-security-review.md`.
## Next action
None in scope. Awaiting owner approval for commit/push/deploy (CON-003). No further implementation work.
## Blockers
None known. Do not commit, push, or deploy. Do not access `.env` or production data.
## Task breakdown
- [x] TASK-001 — Trace follow-up/session state machine, progress/polling, one-shot lifecycle, timeout chain, and historic error path. Covers REQ-001–REQ-007; exact historic error remains unverified because local logs/reproduction are unavailable.
- [x] TASK-002 — Add regression coverage for follow-up branches, notice variants, gone debrief/loss, and judge retry. Covers REQ-001–REQ-003, AC-001.
- [x] TASK-003 — Verify existing completed-persona API/UI lifecycle and one-shot guards; no extra change needed. Covers REQ-004, AC-001.
- [x] TASK-004 — Persist bounded progress, expose safe serializer, poll, and display accessible generation progress. Covers REQ-005, AC-002.
- [x] TASK-005 — Increase LLM timeout to 180s, retain finite 30-minute async polling, investigate error from code evidence. Covers REQ-006–REQ-007, AC-003/AC-005.
- [x] TASK-006 — Full backend/frontend checks and security scan passed; independent reviewer verdict received and verified. Single REJECT finding (gone session reopenable after judge failure) confirmed **stale** — reviewer read a pre-fix `chat_routes.py` snapshot; current tree has the `followup_phase == "gone"` retry branch (chat_routes.py:888) plus both regression tests, which pass. Full suite re-run green post-review (532). No other confirmed blocker. Covers AC-001–AC-005.
- [x] TASK-007 — Engineering log, handoff, test evidence, and this plan updated with the reviewer verdict. Covers AC-004/AC-005.
## Dependencies
TASK-002–TASK-005 depend on TASK-001. TASK-006 depends on all implementation tasks; TASK-007 depends on verification results.
## Requirement coverage
REQ-001/002/003 → TASK-002; REQ-004 → TASK-003; REQ-005 → TASK-004; REQ-006/007 → TASK-005; all acceptance criteria → TASK-006/007.
## Verification and evidence
- RED/GREEN targeted pytest for each backend behavior before implementation.
- Run complete backend pytest suite, `python -m compileall -q app tests`, frontend unit tests and production build.
- Inspect `git diff --check`; scan changed lines for secrets, injection, unsafe execution, and debug leftovers.
- Independently review exact current diff with diagnosis reviewer; do not treat timeout/no verdict as approval.
- No production/real-provider claims unless explicitly verified; no push/deploy.
+47
View File
@@ -0,0 +1,47 @@
# Sales Trainer — Project Requirements
## Purpose
Provide realistic, one-shot sales practice against simulated customer personas, with a useful post-chat evaluation and coaching debrief.
## Governing documents
- `docs/plan.md` — legacy product architecture and requirements; authoritative for unchanged product behavior.
- `docs/HANDOFF.md` — operational constraints, repo/deploy conventions, and safety notes.
- `docs/engineering-log.md` — prior evidence and project history; not a substitute for current verification.
## Requirements
- REQ-001: When a customer decides to try a product, branch into a follow-up scenario rather than concluding the chat immediately.
- REQ-002: Randomize among (a) customer silent after two days and trainee must follow up; (b) customer contacts first after two days; and (c) silent then gone/no response after trainee follows up. Silent notices must have multiple natural variants per supported locale.
- REQ-003: In the gone/no-response case, end as a loss after the trainee's follow-up and provide the usual evaluation/coaching debrief, explaining possible external reasons without presenting guesses as known facts.
- REQ-004: A concluded one-shot persona session must change to a completed state, be unavailable for another chat, and expose a summary/result action rather than a start-chat action. Enforce this in both API and UI.
- REQ-005: Persona generation must expose meaningful progress while analysis runs, including understandable stages and failure/completion states.
- REQ-006: Review end-to-end LLM/server/client timeout behavior for slow models; increase finite, appropriate limits and tests where justified.
- REQ-007: Investigate the previously reported error at the “customer will try” system message; reproduce or identify likely code path from evidence, and fix any confirmed defect.
## Constraints
- CON-001: Preserve one-chat-per-user/persona, tenant scoping, transcript allowlists, and latent persona privacy.
- CON-002: Do not read or modify secrets, `.env`, production data, or credentials.
- CON-003: Do not commit, push, deploy, reset, or stash; these operations are outside this change unless separately directed.
- CON-004: Keep LLM/network work asynchronous where it already is; progress indicators must not expose hidden persona data.
- CON-005: Use Thai-first natural product language; keep the interface professional and accessible.
## Prohibitions
- MUST-NOT-001: Do not claim speculative reasons for a customer disappearing as established facts; frame them as plausible possibilities.
- MUST-NOT-002: Do not allow a completed chat to be reopened/resumed or accidentally create a second session.
## Acceptance criteria
- AC-001: Tests cover each follow-up branch, randomized notice variants, locale allowlist/serialization, completed-session start/resume/send behavior, and preserved one-shot semantics.
- AC-002: Tests cover progress stages/status serialization and the frontend displays progress during generation and handles failure/completion.
- AC-003: Timeout changes are finite, consistent across LLM calls and hosting/client polling, and regression-tested.
- AC-004: Existing backend suite and frontend unit/build checks pass; independent code review returns no blocking security or logic findings.
- AC-005: Error-path investigation is evidence-based and documented; no unverified production failure is described as reproduced.
## Decisions
- DEC-001: `try` branches into three follow-up outcomes: trainee follow-up→gone/loss; trainee follow-up→hesitant/re-engagement; or customer messages first after two days. Never close at initial `try`.
- DEC-002: Keep exact generated system notices in the transcript allowlist; any randomized pool must remain safe under existing message sanitization.
- DEC-003: Progress is persisted as bounded, non-sensitive stage metadata on the group record and exposed by the existing group poll API unless inspection proves a safer existing mechanism.
## Open questions
- OQ-001: Is the old reported system-message error present in current application logs or reproducible in tests? Investigate without reading secrets or production records.
## Requirement change log
- 2026-10-02: Owner refined the prior follow-up behavior: `try` must randomize among silent (trainee follows up), customer re-engages first, and silent-then-gone; notices should vary; gone is a loss with evaluated coaching. Owner additionally requests stage/button lifecycle correction, live generation progress, finite longer timeouts for slower models, and investigation of the earlier error.