Spaces:
Sleeping
fix(voice/brain): remove hold-space, fix silent TTS + policy-Q&A refusal
Browse filesBug 1: remove the hold-SPACE-to-talk path entirely (listeners, state,
delegated fns, all SPACE UI strings, the welcome 'Hold SPACE' tile +
ModeIcon). Push-to-talk button is the only voice-capture control.
Deleted the now-invalid test_space_hold_ptt_delegation.py; corrected the
stale test_ptt_preroll_warm_stream.py docstring.
Bug 2: single_brain.py overwrote accumulated prose with '' when a
tool-only Gemini iteration returned no text (two sites: CASE A end-of-loop,
CASE B tool-iteration). Guarded both with 'if text:' so the spoken reply
survives -> TTS no longer skipped after profile/recommendation.
Bug 3: in-chat CitedPolicyCards never fetched insurer reviews; added a
getInsurerReviews fetch + a 'Reviews:' line (claim ratio / grade /
headline) mirroring the #65 claim-experience pattern + the #76 'never
silently vanish' rule.
Bug 4/5: the brain had NO tool for claim-settlement / denial / complaint /
review data (retrieve_policies returns wording only) and was never shown
its own shortlist, so it refused policy Q&A and could not compare
policies. Added brain_tools.get_policy_facts (reuses the same
reviews/scorecard loaders the detail modal uses), registered + wired the
tool, added RULE 3.5 (anti-refusal) + RULE 5 update + ACTIVE SHORTLIST
injection into the system instruction. New regression tests:
test_get_policy_facts_tool.py, test_last_text_preserved_across_tool_iters.py.
Verified: API E2E 3/3 loops + browser E2E 24/24 + full pytest exit 0 +
audit static/build/functional all green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- backend/brain_tools.py +116 -0
- backend/single_brain.py +141 -10
- frontend/src/app/page.tsx +78 -233
- tests/test_get_policy_facts_tool.py +106 -0
- tests/test_last_text_preserved_across_tool_iters.py +226 -0
- tests/test_ptt_preroll_warm_stream.py +21 -25
- tests/test_space_hold_ptt_delegation.py +0 -239
|
@@ -1263,6 +1263,122 @@ async def retrieve_policies(
|
|
| 1263 |
|
| 1264 |
# ---- mark_recommendation ---------------------------------------------------
|
| 1265 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1266 |
def mark_recommendation(
|
| 1267 |
session,
|
| 1268 |
policy_ids: list[str],
|
|
|
|
| 1263 |
|
| 1264 |
# ---- mark_recommendation ---------------------------------------------------
|
| 1265 |
|
| 1266 |
+
def get_policy_facts(session, policy_ids: Optional[list[str]] = None) -> dict:
|
| 1267 |
+
"""Return AUTHORITATIVE claim / reputation / scorecard / coverage facts
|
| 1268 |
+
for one or more policy_ids β the SAME data the frontend detail-modal
|
| 1269 |
+
shows (insurer reviews `claim_metrics` + scorecard grade + the curated
|
| 1270 |
+
coverage facts). This is the tool the brain calls for ANY follow-up
|
| 1271 |
+
about claim-settlement ratio, claim denials/rejections, complaints,
|
| 1272 |
+
incurred-claim ratio, insurer reputation, or to COMPARE two policies
|
| 1273 |
+
the user already saw.
|
| 1274 |
+
|
| 1275 |
+
Root cause (2026-05-18): the brain previously had NO way to reach
|
| 1276 |
+
claim/denial/complaint/review data β retrieve_policies returns policy
|
| 1277 |
+
WORDING chunks only β so it falsely answered "I don't have enough
|
| 1278 |
+
information" for claims questions and could not back a verbal
|
| 1279 |
+
comparison. This tool closes that gap; it reuses the existing
|
| 1280 |
+
`_insurer_reviews` / `_scorecard_signal` / `_load_policy_facts` /
|
| 1281 |
+
`_curated_facts_all` loaders so a verbal answer matches the modal.
|
| 1282 |
+
|
| 1283 |
+
`policy_ids` empty/None β falls back to the active shortlist
|
| 1284 |
+
(`session.last_recommendation_ids`) so "compare the ones you showed"
|
| 1285 |
+
works without the model re-deriving ids.
|
| 1286 |
+
"""
|
| 1287 |
+
ids = [str(p).strip() for p in (policy_ids or []) if str(p).strip()]
|
| 1288 |
+
if not ids:
|
| 1289 |
+
ids = [
|
| 1290 |
+
str(p).strip()
|
| 1291 |
+
for p in (getattr(session, "last_recommendation_ids", []) or [])
|
| 1292 |
+
if str(p).strip()
|
| 1293 |
+
]
|
| 1294 |
+
if not ids:
|
| 1295 |
+
return {
|
| 1296 |
+
"ok": False,
|
| 1297 |
+
"error": (
|
| 1298 |
+
"no_policy_ids β pass policy_ids, or recommend policies "
|
| 1299 |
+
"first so there is an active shortlist"
|
| 1300 |
+
),
|
| 1301 |
+
}
|
| 1302 |
+
|
| 1303 |
+
# Resolve policy_id β (policy_name, insurer_slug) from the caches
|
| 1304 |
+
# retrieve_policies stashed this session, then the curated catalogue.
|
| 1305 |
+
slug_map = dict(getattr(session, "slug_to_insurer", {}) or {})
|
| 1306 |
+
name_by_id: dict[str, str] = {}
|
| 1307 |
+
for c in getattr(session, "last_retrieved_chunks", []) or []:
|
| 1308 |
+
pid = (c.get("policy_id") or "").strip()
|
| 1309 |
+
if not pid:
|
| 1310 |
+
continue
|
| 1311 |
+
name_by_id.setdefault(pid, c.get("policy_name") or pid)
|
| 1312 |
+
if pid not in slug_map and c.get("insurer_slug"):
|
| 1313 |
+
slug_map[pid] = c.get("insurer_slug")
|
| 1314 |
+
try:
|
| 1315 |
+
curated = _curated_facts_all()
|
| 1316 |
+
except Exception: # noqa: BLE001 β curated layer optional
|
| 1317 |
+
curated = {}
|
| 1318 |
+
|
| 1319 |
+
out: list[dict] = []
|
| 1320 |
+
for pid in ids:
|
| 1321 |
+
cur = curated.get(pid) or {}
|
| 1322 |
+
slug = (slug_map.get(pid) or cur.get("insurer_slug") or "").strip()
|
| 1323 |
+
pname = name_by_id.get(pid) or cur.get("policy_name") or pid
|
| 1324 |
+
rv = _insurer_reviews(slug) or {}
|
| 1325 |
+
cm = rv.get("claim_metrics") or {}
|
| 1326 |
+
agg = rv.get("aggregate_score") or {}
|
| 1327 |
+
sig = _scorecard_signal(pid) or {}
|
| 1328 |
+
try:
|
| 1329 |
+
facts = _load_policy_facts(pid) or {}
|
| 1330 |
+
except Exception: # noqa: BLE001 β facts optional
|
| 1331 |
+
facts = {}
|
| 1332 |
+
out.append(
|
| 1333 |
+
{
|
| 1334 |
+
"policy_id": pid,
|
| 1335 |
+
"policy_name": pname,
|
| 1336 |
+
"insurer_slug": slug,
|
| 1337 |
+
"insurer_name": rv.get("insurer_name")
|
| 1338 |
+
or (slug.replace("-", " ").title() if slug else ""),
|
| 1339 |
+
"scorecard_grade": sig.get("_grade"),
|
| 1340 |
+
"scorecard_overall_0_100": sig.get("_overall_score"),
|
| 1341 |
+
"claim_settlement_ratio_pct": cm.get(
|
| 1342 |
+
"claim_settlement_ratio_pct"
|
| 1343 |
+
),
|
| 1344 |
+
"claim_settlement_ratio_year": cm.get(
|
| 1345 |
+
"claim_settlement_ratio_year"
|
| 1346 |
+
),
|
| 1347 |
+
"three_year_avg_csr_pct": cm.get("three_year_avg_csr_pct"),
|
| 1348 |
+
"complaints_per_10k_policies": cm.get(
|
| 1349 |
+
"complaints_per_10k_policies"
|
| 1350 |
+
),
|
| 1351 |
+
"complaints_year": cm.get("complaints_year"),
|
| 1352 |
+
"claims_rejected_fy24": cm.get("claims_rejected_fy24"),
|
| 1353 |
+
"incurred_claim_ratio_pct": cm.get("incurred_claim_ratio_pct"),
|
| 1354 |
+
"reputation_headline": agg.get("headline"),
|
| 1355 |
+
"reputation_grade": agg.get("letter_grade"),
|
| 1356 |
+
"claim_data_source_url": (
|
| 1357 |
+
cm.get("source_irdai_url")
|
| 1358 |
+
or cm.get("source_secondary_url")
|
| 1359 |
+
or cm.get("source_complaints_url")
|
| 1360 |
+
),
|
| 1361 |
+
"key_coverage_facts": {
|
| 1362 |
+
k: v for k, v in facts.items() if v not in (None, "", [])
|
| 1363 |
+
},
|
| 1364 |
+
"reviews_available": bool(rv),
|
| 1365 |
+
}
|
| 1366 |
+
)
|
| 1367 |
+
|
| 1368 |
+
return {
|
| 1369 |
+
"ok": True,
|
| 1370 |
+
"count": len(out),
|
| 1371 |
+
"policies": out,
|
| 1372 |
+
"note": (
|
| 1373 |
+
"This is the authoritative claim-settlement / complaint / "
|
| 1374 |
+
"denial / scorecard data (IRDAI + scorecard) β answer the "
|
| 1375 |
+
"user's question directly from it; do NOT say you lack this "
|
| 1376 |
+
"information. Cite as "
|
| 1377 |
+
"[Source: <insurer> claim data (IRDAI), <claim_data_source_url>]."
|
| 1378 |
+
),
|
| 1379 |
+
}
|
| 1380 |
+
|
| 1381 |
+
|
| 1382 |
def mark_recommendation(
|
| 1383 |
session,
|
| 1384 |
policy_ids: list[str],
|
|
@@ -263,6 +263,28 @@ RULE 3 β Follow-ups + mark_recommendation
|
|
| 263 |
- After producing a ranked shortlist, call mark_recommendation(policy_ids=[...ordered IDs you cited...]).
|
| 264 |
- For "tell me about #2" / "second one" follow-ups, call retrieve_policies(query, policy_filter_ids=[policy_id_of_#2]) to narrow to that policy.
|
| 265 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
βββββββββββββββββββββββββββββββββββ
|
| 267 |
RULE 4 β Returning-user greeting (pre-populated profile)
|
| 268 |
βββββββββββββββββββββββββββββββββββ
|
|
@@ -320,14 +342,20 @@ RULE 5 β Comparison view ("compare #1 and #3")
|
|
| 320 |
When the user asks to compare two or more shortlisted policies ("compare
|
| 321 |
#1 and #3", "what's the difference between Plan A and Plan B",
|
| 322 |
"#2 vs #4"):
|
| 323 |
-
1. Call
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
| 325 |
2. Produce an explicit side-by-side comparison β markdown table with
|
| 326 |
columns | Feature | Policy A | Policy B | OR paired bullets
|
| 327 |
("Sum insured: A = βΉ10L, B = βΉ15L"). Cover at minimum: sum insured,
|
| 328 |
-
premium, room rent, PED waiting period, key exclusions
|
| 329 |
-
|
| 330 |
-
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
βββββββββββββββββββββββββββββββββββ
|
| 333 |
RULE 6 β Out-of-scope refusal (non-health products)
|
|
@@ -533,6 +561,38 @@ TOOL_SCHEMAS: list[dict] = [
|
|
| 533 |
"required": ["policy_ids"],
|
| 534 |
},
|
| 535 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
]
|
| 537 |
|
| 538 |
|
|
@@ -596,7 +656,9 @@ def _build_contents(
|
|
| 596 |
return out
|
| 597 |
|
| 598 |
|
| 599 |
-
def _system_instruction(
|
|
|
|
|
|
|
| 600 |
"""Bake the profile snapshot into the system prompt so each turn the
|
| 601 |
LLM knows what's already captured. Returned in Gemini's expected
|
| 602 |
`systemInstruction` shape.
|
|
@@ -632,7 +694,7 @@ def _system_instruction(profile, is_returning_user: bool = False) -> dict:
|
|
| 632 |
"say 'Welcome back'):\n"
|
| 633 |
+ json.dumps(snapshot, ensure_ascii=False, sort_keys=True)
|
| 634 |
)
|
| 635 |
-
text = SYSTEM_PROMPT + extra
|
| 636 |
return {"parts": [{"text": text}]}
|
| 637 |
|
| 638 |
|
|
@@ -1542,6 +1604,11 @@ async def _execute_tool(session, name: str, args: dict) -> dict:
|
|
| 1542 |
policy_ids=args.get("policy_ids") or [],
|
| 1543 |
is_final=bool(args.get("is_final") or False),
|
| 1544 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1545 |
return {"ok": False, "error": f"unknown_tool:{name}"}
|
| 1546 |
except Exception as e: # noqa: BLE001 β never crash the loop
|
| 1547 |
_log.warning(
|
|
@@ -1610,8 +1677,43 @@ async def handle_turn(
|
|
| 1610 |
if not api_key:
|
| 1611 |
raise SingleBrainError("GOOGLE_API_KEY not set")
|
| 1612 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1613 |
system_instruction = _system_instruction(
|
| 1614 |
-
session.profile,
|
|
|
|
|
|
|
| 1615 |
)
|
| 1616 |
|
| 1617 |
# Bug #108 + #110 β if the user explicitly declines the pricing /
|
|
@@ -1686,8 +1788,22 @@ async def handle_turn(
|
|
| 1686 |
# CASE A β no function calls: this is the final text reply.
|
| 1687 |
# Includes the "Gemini just chats on turn 1" path the spec
|
| 1688 |
# called out β completely valid, return immediately.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1689 |
if not function_calls:
|
| 1690 |
-
|
|
|
|
| 1691 |
_log.info(
|
| 1692 |
"single_brain iter=%d gemini=%.2fs tools=%.2fs "
|
| 1693 |
"tool_calls=[] final_text=True",
|
|
@@ -1768,7 +1884,22 @@ async def handle_turn(
|
|
| 1768 |
contents.append({"role": "user", "parts": response_parts})
|
| 1769 |
# And loop β Gemini gets another shot to either call more
|
| 1770 |
# tools or emit a final text reply.
|
| 1771 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1772 |
else:
|
| 1773 |
# Hit MAX_ITERATIONS without break β honest signal, not a
|
| 1774 |
# fabricated slot-question.
|
|
|
|
| 263 |
- After producing a ranked shortlist, call mark_recommendation(policy_ids=[...ordered IDs you cited...]).
|
| 264 |
- For "tell me about #2" / "second one" follow-ups, call retrieve_policies(query, policy_filter_ids=[policy_id_of_#2]) to narrow to that policy.
|
| 265 |
|
| 266 |
+
βββββββββββββββββββββββββββββββββββ
|
| 267 |
+
RULE 3.5 β Claims / denials / complaints / reputation / comparison β get_policy_facts (NEVER refuse)
|
| 268 |
+
βββββββββββββββββββββββββββββββββββ
|
| 269 |
+
If the user asks ANYTHING about claim settlement ratio, claim
|
| 270 |
+
denials/rejections, complaints, incurred-claim ratio, insurer
|
| 271 |
+
reputation/track record, "how good is their claims process", or a
|
| 272 |
+
side-by-side COMPARISON of policies on the ACTIVE SHORTLIST (or names one
|
| 273 |
+
of them):
|
| 274 |
+
1. Call get_policy_facts(policy_ids=[...]) β resolve the ids EXACTLY
|
| 275 |
+
like RULE 7 ("#1"βshortlist[0], "the HDFC one"βmatching insurer,
|
| 276 |
+
"compare the two you showed"βthe whole shortlist; omit policy_ids to
|
| 277 |
+
use the entire shortlist).
|
| 278 |
+
2. Answer DIRECTLY from the returned numbers (claim_settlement_ratio_pct,
|
| 279 |
+
three_year_avg_csr_pct, complaints_per_10k_policies,
|
| 280 |
+
claims_rejected_fy24, incurred_claim_ratio_pct, scorecard_grade).
|
| 281 |
+
3. Cite as [Source: <insurer> claim data (IRDAI), <claim_data_source_url>].
|
| 282 |
+
You MUST NOT reply "I don't have enough information" / "I can't tell you
|
| 283 |
+
the claim ratio" / "claim data is only at insurer level so I can't help"
|
| 284 |
+
when the ACTIVE SHORTLIST is non-empty β that data IS available via
|
| 285 |
+
get_policy_facts. retrieve_policies returns policy WORDING only; it does
|
| 286 |
+
NOT contain claim/complaint/denial data β use get_policy_facts for those.
|
| 287 |
+
|
| 288 |
βββββββββββββββββββββββββββββββββββ
|
| 289 |
RULE 4 β Returning-user greeting (pre-populated profile)
|
| 290 |
βββββββββββββββββββββββββββββββββββ
|
|
|
|
| 342 |
When the user asks to compare two or more shortlisted policies ("compare
|
| 343 |
#1 and #3", "what's the difference between Plan A and Plan B",
|
| 344 |
"#2 vs #4"):
|
| 345 |
+
1. Call get_policy_facts(policy_ids=[id_of_A, id_of_B]) for the claim
|
| 346 |
+
record / scorecard / reputation columns (claim settlement ratio,
|
| 347 |
+
complaints, denials, grade), AND retrieve_policies(
|
| 348 |
+
policy_filter_ids=[id_of_A, id_of_B], top_k=4) in ONE call for the
|
| 349 |
+
wording columns (sum insured, room rent, PED wait, exclusions).
|
| 350 |
2. Produce an explicit side-by-side comparison β markdown table with
|
| 351 |
columns | Feature | Policy A | Policy B | OR paired bullets
|
| 352 |
("Sum insured: A = βΉ10L, B = βΉ15L"). Cover at minimum: sum insured,
|
| 353 |
+
premium, room rent, PED waiting period, key exclusions, AND
|
| 354 |
+
claim-settlement ratio + complaints (from get_policy_facts).
|
| 355 |
+
3. Cite each cell with [Source: ..., UIN] for wording and
|
| 356 |
+
[Source: <insurer> claim data (IRDAI), <url>] for claim metrics. Do
|
| 357 |
+
NOT just dump retrieved text β explicitly contrast. NEVER say you
|
| 358 |
+
can't compare claim records β get_policy_facts provides them.
|
| 359 |
|
| 360 |
βββββββββββββββββββββββββββββββββββ
|
| 361 |
RULE 6 β Out-of-scope refusal (non-health products)
|
|
|
|
| 561 |
"required": ["policy_ids"],
|
| 562 |
},
|
| 563 |
},
|
| 564 |
+
{
|
| 565 |
+
"name": "get_policy_facts",
|
| 566 |
+
"description": (
|
| 567 |
+
"Fetch AUTHORITATIVE claim-settlement ratio, 3-year average "
|
| 568 |
+
"CSR, complaints per 10k policies, claim denials/rejections, "
|
| 569 |
+
"incurred-claim ratio, scorecard grade, insurer reputation, "
|
| 570 |
+
"and key coverage facts for one or more policy_ids. Use this "
|
| 571 |
+
"for ANY follow-up about claims, claim settlement, denials, "
|
| 572 |
+
"rejections, complaints, insurer track record/reputation, or "
|
| 573 |
+
"to COMPARE policies the user already saw. This data IS "
|
| 574 |
+
"available (IRDAI + scorecard) β you must NEVER say you lack "
|
| 575 |
+
"claim/denial/complaint information without calling this tool "
|
| 576 |
+
"first. retrieve_policies returns policy WORDING only and does "
|
| 577 |
+
"NOT contain claim metrics. Resolve '#1/#2/the HDFC one' to "
|
| 578 |
+
"policy_ids via the ACTIVE SHORTLIST in the system prompt; if "
|
| 579 |
+
"policy_ids is omitted the whole current shortlist is used."
|
| 580 |
+
),
|
| 581 |
+
"parameters": {
|
| 582 |
+
"type": "OBJECT",
|
| 583 |
+
"properties": {
|
| 584 |
+
"policy_ids": {
|
| 585 |
+
"type": "ARRAY",
|
| 586 |
+
"items": {"type": "STRING"},
|
| 587 |
+
"description": (
|
| 588 |
+
"policy_ids to fetch facts for. Empty = use the "
|
| 589 |
+
"entire active shortlist (last recommended set)."
|
| 590 |
+
),
|
| 591 |
+
},
|
| 592 |
+
},
|
| 593 |
+
"required": [],
|
| 594 |
+
},
|
| 595 |
+
},
|
| 596 |
]
|
| 597 |
|
| 598 |
|
|
|
|
| 656 |
return out
|
| 657 |
|
| 658 |
|
| 659 |
+
def _system_instruction(
|
| 660 |
+
profile, is_returning_user: bool = False, shortlist_block: str = ""
|
| 661 |
+
) -> dict:
|
| 662 |
"""Bake the profile snapshot into the system prompt so each turn the
|
| 663 |
LLM knows what's already captured. Returned in Gemini's expected
|
| 664 |
`systemInstruction` shape.
|
|
|
|
| 694 |
"say 'Welcome back'):\n"
|
| 695 |
+ json.dumps(snapshot, ensure_ascii=False, sort_keys=True)
|
| 696 |
)
|
| 697 |
+
text = SYSTEM_PROMPT + extra + (shortlist_block or "")
|
| 698 |
return {"parts": [{"text": text}]}
|
| 699 |
|
| 700 |
|
|
|
|
| 1604 |
policy_ids=args.get("policy_ids") or [],
|
| 1605 |
is_final=bool(args.get("is_final") or False),
|
| 1606 |
)
|
| 1607 |
+
if name == "get_policy_facts":
|
| 1608 |
+
return brain_tools.get_policy_facts(
|
| 1609 |
+
session,
|
| 1610 |
+
policy_ids=args.get("policy_ids") or None,
|
| 1611 |
+
)
|
| 1612 |
return {"ok": False, "error": f"unknown_tool:{name}"}
|
| 1613 |
except Exception as e: # noqa: BLE001 β never crash the loop
|
| 1614 |
_log.warning(
|
|
|
|
| 1677 |
if not api_key:
|
| 1678 |
raise SingleBrainError("GOOGLE_API_KEY not set")
|
| 1679 |
|
| 1680 |
+
# ACTIVE SHORTLIST β the policies recommended on a prior turn. RULE 7 /
|
| 1681 |
+
# RULE 3.5 / RULE 5 reference session.last_recommendation_ids, but the
|
| 1682 |
+
# model was never actually SHOWN it (root cause, 2026-05-18): without
|
| 1683 |
+
# this block "compare #1 and #2" / "claim ratio of the HDFC one" could
|
| 1684 |
+
# not resolve to policy_ids, so the model refused. Surface id + name +
|
| 1685 |
+
# insurer so the model can pass exact policy_ids to get_policy_facts /
|
| 1686 |
+
# retrieve_policies.
|
| 1687 |
+
_shortlist_block = ""
|
| 1688 |
+
try:
|
| 1689 |
+
_sl_ids = list(getattr(session, "last_recommendation_ids", []) or [])
|
| 1690 |
+
if _sl_ids:
|
| 1691 |
+
_snap = dict(
|
| 1692 |
+
getattr(session, "last_recommendation_snapshot", {}) or {}
|
| 1693 |
+
)
|
| 1694 |
+
_s2i = dict(getattr(session, "slug_to_insurer", {}) or {})
|
| 1695 |
+
_lines = []
|
| 1696 |
+
for _i, _pid in enumerate(_sl_ids, 1):
|
| 1697 |
+
_nm = _snap.get(_pid) or _pid
|
| 1698 |
+
_ins = _s2i.get(_pid) or ""
|
| 1699 |
+
_lines.append(
|
| 1700 |
+
f" #{_i} policy_id={_pid} | {_nm}"
|
| 1701 |
+
+ (f" ({_ins})" if _ins else "")
|
| 1702 |
+
)
|
| 1703 |
+
_shortlist_block = (
|
| 1704 |
+
"\n\nβββββββββββββββββββββββββββββββββββ\n"
|
| 1705 |
+
"ACTIVE SHORTLIST (policies you recommended this session β "
|
| 1706 |
+
"resolve \"#1/#2/the X one/the two you showed\" to THESE "
|
| 1707 |
+
"policy_ids and pass them to get_policy_facts / "
|
| 1708 |
+
"retrieve_policies):\n" + "\n".join(_lines)
|
| 1709 |
+
)
|
| 1710 |
+
except Exception: # noqa: BLE001 β bookkeeping must not break a turn
|
| 1711 |
+
_shortlist_block = ""
|
| 1712 |
+
|
| 1713 |
system_instruction = _system_instruction(
|
| 1714 |
+
session.profile,
|
| 1715 |
+
is_returning_user=is_returning_user,
|
| 1716 |
+
shortlist_block=_shortlist_block,
|
| 1717 |
)
|
| 1718 |
|
| 1719 |
# Bug #108 + #110 β if the user explicitly declines the pricing /
|
|
|
|
| 1788 |
# CASE A β no function calls: this is the final text reply.
|
| 1789 |
# Includes the "Gemini just chats on turn 1" path the spec
|
| 1790 |
# called out β completely valid, return immediately.
|
| 1791 |
+
#
|
| 1792 |
+
# BUGFIX (2026-05-18) β same destructive-overwrite class as the
|
| 1793 |
+
# CASE-B site below. When the FINAL iteration carries no function
|
| 1794 |
+
# calls AND an empty text part (the documented near-zero "LLM
|
| 1795 |
+
# returned nothing" tail referenced at the reply_text fallback
|
| 1796 |
+
# comment), an unconditional `last_text = text` here wiped prose
|
| 1797 |
+
# captured in a PRIOR tool-call iteration β reply_text fell through
|
| 1798 |
+
# to _HONEST_EMPTY_REPLY β main.py skipped TTS (bot went SILENT
|
| 1799 |
+
# after profile completion / policy presentation). Only adopt this
|
| 1800 |
+
# iteration's text when it actually produced prose; an empty final
|
| 1801 |
+
# text now falls back to the earlier spoken prose instead of
|
| 1802 |
+
# destroying it. A non-empty final text still replaces it (the
|
| 1803 |
+
# normal "model's last word wins" path is unchanged).
|
| 1804 |
if not function_calls:
|
| 1805 |
+
if text:
|
| 1806 |
+
last_text = text
|
| 1807 |
_log.info(
|
| 1808 |
"single_brain iter=%d gemini=%.2fs tools=%.2fs "
|
| 1809 |
"tool_calls=[] final_text=True",
|
|
|
|
| 1884 |
contents.append({"role": "user", "parts": response_parts})
|
| 1885 |
# And loop β Gemini gets another shot to either call more
|
| 1886 |
# tools or emit a final text reply.
|
| 1887 |
+
#
|
| 1888 |
+
# BUGFIX (2026-05-18) β only update last_text when THIS iteration
|
| 1889 |
+
# actually produced prose. An unconditional `last_text = text` here
|
| 1890 |
+
# erased prose captured in a PRIOR iteration whenever a later
|
| 1891 |
+
# iteration returned only function calls (text == ""): e.g. iter 1
|
| 1892 |
+
# "Great, your profile is complete! β¦" + save_profile_field, then
|
| 1893 |
+
# iter 2 retrieve_policies + mark_recommendation with NO text β
|
| 1894 |
+
# last_text became "" β reply_text fell through to
|
| 1895 |
+
# _HONEST_EMPTY_REPLY β main.py skipped TTS (bot went SILENT right
|
| 1896 |
+
# after profile completion / policy presentation). The original
|
| 1897 |
+
# intent β keep the latest prose so a MAX_ITERATIONS exit still has
|
| 1898 |
+
# a non-empty reply β is preserved: a non-empty text on any
|
| 1899 |
+
# iteration still updates last_text; an empty one is now a no-op
|
| 1900 |
+
# instead of a destructive overwrite.
|
| 1901 |
+
if text:
|
| 1902 |
+
last_text = text
|
| 1903 |
else:
|
| 1904 |
# Hit MAX_ITERATIONS without break β honest signal, not a
|
| 1905 |
# fabricated slot-question.
|
|
@@ -62,7 +62,7 @@ export default function Page() {
|
|
| 62 |
const [busy, setBusy] = useState(false);
|
| 63 |
// Voice-display fix β the composer <textarea> must grow as the live
|
| 64 |
// interim voice transcript accumulates so the user sees their FULL
|
| 65 |
-
// spoken sentence (not just the first line) while
|
| 66 |
// The textarea has resize-none + a small min-height, so without this
|
| 67 |
// it stays clamped to one line and the transcript visually truncates
|
| 68 |
// even though capture/submit are correct. We size height to scrollHeight
|
|
@@ -83,25 +83,18 @@ export default function Page() {
|
|
| 83 |
const [returnAudio] = useState(true);
|
| 84 |
const [ttsLang] = useState<"en-IN" | "hi-IN">("en-IN");
|
| 85 |
// KI-257 β master Voice toggle. When OFF, the chat input shows only
|
| 86 |
-
// textarea + Send. When ON, reveals Live (BETA) option
|
| 87 |
-
//
|
| 88 |
-
// (no separate toggle) so the user can just press space whenever the
|
| 89 |
-
// textarea isn't focused. Persisted via localStorage.
|
| 90 |
const [voiceMasterOn, setVoiceMasterOn] = useState(false);
|
| 91 |
-
//
|
| 92 |
-
// "
|
| 93 |
-
const [spaceHoldActive, setSpaceHoldActive] = useState(false);
|
| 94 |
-
// #3 mobile β touch devices have no SPACE key, so SPACE-centric voice
|
| 95 |
-
// copy reads as "voice is broken" on a phone (tap-to-talk DOES work via
|
| 96 |
-
// the button's onClick + VAD auto-stop). Shared SSR-safe hook.
|
| 97 |
const isTouch = useIsTouch();
|
| 98 |
// Live (BETA) risk-confirmation gate. Opening Live always-on must surface
|
| 99 |
// a clear, styled WARNING modal listing the real failure modes EVERY time
|
| 100 |
// (no localStorage "seen once" bypass β the old window.confirm gate let
|
| 101 |
// production users skip the warning entirely after one ack, or whenever
|
| 102 |
// the browser suppressed the native dialog). The live session only starts
|
| 103 |
-
// on explicit Confirm; Cancel reverts the toggle. PTT
|
| 104 |
-
// never gated.
|
| 105 |
const [showLiveGate, setShowLiveGate] = useState(false);
|
| 106 |
// Visual UI language β same source as ttsLang so the toggle controls both
|
| 107 |
const uiLang: UILang = ttsLang === "hi-IN" ? "hi" : "en";
|
|
@@ -485,7 +478,7 @@ export default function Page() {
|
|
| 485 |
useEffect(() => {
|
| 486 |
const ta = composerRef.current;
|
| 487 |
if (!ta) return;
|
| 488 |
-
// While capturing voice (PTT click
|
| 489 |
// far more room so the entire accumulated interim transcript is on
|
| 490 |
// screen. Idle/typed flow keeps a calmer cap. Both are well above one
|
| 491 |
// line β the previous max-h-32 (128px) was the perceived "truncation".
|
|
@@ -494,7 +487,7 @@ export default function Page() {
|
|
| 494 |
// "couldn't see the whole transcript even though it was all captured".
|
| 495 |
// While capturing, grow up to ~half the viewport so the full utterance
|
| 496 |
// is visible; only the genuinely huge tail still scrolls.
|
| 497 |
-
const isCapturing = recording ||
|
| 498 |
const vh = typeof window !== "undefined" ? window.innerHeight : 800;
|
| 499 |
const maxH = isCapturing ? Math.min(Math.round(vh * 0.5), 520) : 160;
|
| 500 |
// Collapse first so shrinking text (word-erase / send-clear) recomputes
|
|
@@ -512,7 +505,7 @@ export default function Page() {
|
|
| 512 |
} else {
|
| 513 |
ta.style.overflowY = "hidden";
|
| 514 |
}
|
| 515 |
-
}, [input, recording,
|
| 516 |
|
| 517 |
// Voice-display fix β keep the PTT interim strip pinned to its newest
|
| 518 |
// text. The strip now wraps + caps its height + scrolls internally, so
|
|
@@ -1306,178 +1299,6 @@ export default function Page() {
|
|
| 1306 |
}
|
| 1307 |
function stopRecording() { mediaRecorderRef.current?.stop(); }
|
| 1308 |
|
| 1309 |
-
// #53 (head-clip) / #54 (PTT start latency) β the SPACE-hold path now
|
| 1310 |
-
// DELEGATES to useStreamingVoice's warm-stream + pre-roll API instead of
|
| 1311 |
-
// cold-starting its own getUserMedia + MediaRecorder per press. The hook
|
| 1312 |
-
// keeps the OS mic hot and a rolling 800ms pre-roll, so the first word
|
| 1313 |
-
// ("Sir." that previously transcribed as "S A R") is always at the head of
|
| 1314 |
-
// the blob and there is no multi-second per-press start delay.
|
| 1315 |
-
//
|
| 1316 |
-
// Why delegation (not "prepend pre-roll blobs to page.tsx's recorder"):
|
| 1317 |
-
// splicing slices from two independent MediaRecorder streams produces a
|
| 1318 |
-
// corrupt webm container. The hook owns the single recorder that captured
|
| 1319 |
-
// BOTH the pre-roll and the held utterance, so only it can assemble a valid
|
| 1320 |
-
// blob. `endPushToTalk()` already runs the exact Sarvam submit+retry path
|
| 1321 |
-
// and, on success, delivers the transcript via the hook's onFinalTranscript
|
| 1322 |
-
// callback β which page.tsx wires (see useStreamingVoice config above) to
|
| 1323 |
-
// `voiceSubmitRef.current` β `send()`, i.e. the IDENTICAL downstream path a
|
| 1324 |
-
// successful /api/transcribe result used in recorder.onstop. We therefore
|
| 1325 |
-
// MUST NOT re-submit the returned string here (that would double-fire); the
|
| 1326 |
-
// returned value is used only to distinguish a deliberate hold from a
|
| 1327 |
-
// sub-threshold tap (null) for clean state reset.
|
| 1328 |
-
const spaceHoldPttInFlightRef = useRef<boolean>(false);
|
| 1329 |
-
async function startSpaceHoldPTT() {
|
| 1330 |
-
// Re-entrancy guard: a second SPACE keydown while a delegated PTT capture
|
| 1331 |
-
// (or its in-flight transcription) is still resolving must be ignored,
|
| 1332 |
-
// mirroring the original recordingRef/busyRef "don't start twice" intent.
|
| 1333 |
-
if (spaceHoldPttInFlightRef.current) return;
|
| 1334 |
-
spaceHoldPttInFlightRef.current = true;
|
| 1335 |
-
// Preserve recorder.onstop / startRecording semantics: silence any prior
|
| 1336 |
-
// bot TTS the instant the user starts talking (KI-222 FIX 1 / V3 FIX 2).
|
| 1337 |
-
try { interruptBotAudio("ptt-start"); } catch { /* ignore */ }
|
| 1338 |
-
// STT-in-flight UX: the original path flipped voicePhase to "transcribing"
|
| 1339 |
-
// while Sarvam ran. endPushToTalk() runs that same Sarvam call internally,
|
| 1340 |
-
// so set the phase here. NOTE: we deliberately do NOT setBusy(true) β the
|
| 1341 |
-
// hook's onFinalTranscript β voiceSubmitRef β send() owns busy, and send()
|
| 1342 |
-
// early-returns if busy is already true (would silently drop the turn).
|
| 1343 |
-
setVoicePhase("transcribing"); // KI-038 β STT in flight on PTT
|
| 1344 |
-
try {
|
| 1345 |
-
streamingVoice.beginPushToTalk();
|
| 1346 |
-
} catch (e) {
|
| 1347 |
-
// beginPushToTalk itself is non-throwing by contract, but stay defensive
|
| 1348 |
-
// and route any unexpected failure to the same red banner the cold path
|
| 1349 |
-
// used. Warm-stream / permission failures surface via the hook's
|
| 1350 |
-
// onVoiceError β setVoiceErrorBanner (mic_permission_denied) already.
|
| 1351 |
-
console.error(e);
|
| 1352 |
-
spaceHoldPttInFlightRef.current = false;
|
| 1353 |
-
setVoicePhase(null);
|
| 1354 |
-
setSpaceHoldActive(false);
|
| 1355 |
-
setVoiceErrorBanner({ type: "mic_permission_denied", ts: Date.now() });
|
| 1356 |
-
}
|
| 1357 |
-
}
|
| 1358 |
-
async function stopSpaceHoldPTT() {
|
| 1359 |
-
if (!spaceHoldPttInFlightRef.current) return;
|
| 1360 |
-
// KI-028 β resume Live ONLY if the user's persistent preference is still
|
| 1361 |
-
// "on" (matches the original recorder.onstop maybeResumeLive semantics).
|
| 1362 |
-
const maybeResumeLive = () => { if (userPrefersLive) live.setLive(true); };
|
| 1363 |
-
try {
|
| 1364 |
-
// endPushToTalk(): on a deliberate hold it transcribes (pre-roll + held
|
| 1365 |
-
// utterance) AND delivers via onFinalTranscript β voiceSubmitRef β
|
| 1366 |
-
// send() β the EXACT downstream path the old recorder.onstop success
|
| 1367 |
-
// branch used. On a sub-threshold tap / empty capture it resolves to
|
| 1368 |
-
// null and submits nothing. All transport / Sarvam failures surface via
|
| 1369 |
-
// the hook's onVoiceError (transcribe_failed banner) β never silent.
|
| 1370 |
-
const text = await streamingVoice.endPushToTalk();
|
| 1371 |
-
if (text === null) {
|
| 1372 |
-
// Sub-threshold tap or nothing captured: clean no-op. No empty submit;
|
| 1373 |
-
// just clear the cosmetic "transcribing" phase we set on keydown.
|
| 1374 |
-
setVoicePhase(null);
|
| 1375 |
-
maybeResumeLive();
|
| 1376 |
-
} else {
|
| 1377 |
-
// Deliberate hold: the hook has ALREADY pushed `text` through
|
| 1378 |
-
// onFinalTranscript β send(). send() owns busy + flips voicePhase to
|
| 1379 |
-
// "thinking" and clears both in its own finally, so we must NOT reset
|
| 1380 |
-
// voicePhase here (that would stomp send()'s "thinking") and must NOT
|
| 1381 |
-
// re-submit. Just resume Live per the user's preference.
|
| 1382 |
-
maybeResumeLive();
|
| 1383 |
-
}
|
| 1384 |
-
} catch (e) {
|
| 1385 |
-
// endPushToTalk's internal Sarvam path swallows its own errors and
|
| 1386 |
-
// surfaces them via onVoiceError; reaching here means an unexpected
|
| 1387 |
-
// throw. Reset cosmetic state so the UI doesn't stick in "transcribing".
|
| 1388 |
-
console.error(e);
|
| 1389 |
-
setVoicePhase(null);
|
| 1390 |
-
maybeResumeLive();
|
| 1391 |
-
} finally {
|
| 1392 |
-
spaceHoldPttInFlightRef.current = false;
|
| 1393 |
-
}
|
| 1394 |
-
}
|
| 1395 |
-
|
| 1396 |
-
// KI-258 β Hold-SPACE-to-talk. Fixes from KI-257 first ship:
|
| 1397 |
-
// (a) textarea ALWAYS had focus β isInputFocused() was always true β
|
| 1398 |
-
// SPACE never fired. Fix: allow SPACE-hold when the textarea is
|
| 1399 |
-
// focused-AND-empty; only block when it has user-typed text.
|
| 1400 |
-
// (b) `recording`/`spaceHoldActive` in the effect deps recreated
|
| 1401 |
-
// handlers mid-press, splitting keydown/keyup across closures
|
| 1402 |
-
// with stale values. Fix: read all state via refs; deps reduced
|
| 1403 |
-
// to [voiceMasterOn] so handlers bind once.
|
| 1404 |
-
// #53/#54 β these refs now point at the DELEGATED SPACE-hold handlers
|
| 1405 |
-
// (startSpaceHoldPTT / stopSpaceHoldPTT), which route through the hook's
|
| 1406 |
-
// warm-stream + pre-roll API. The on-screen Push-to-talk *button* still
|
| 1407 |
-
// uses startRecording/stopRecording directly (separate onClick handler,
|
| 1408 |
-
// intentionally untouched β it does not share this code path), so the
|
| 1409 |
-
// legacy recorder path is preserved for that control.
|
| 1410 |
-
const startRecordingRef = useRef<(() => Promise<void>) | null>(null);
|
| 1411 |
-
const stopRecordingRef = useRef<(() => Promise<void>) | null>(null);
|
| 1412 |
-
const recordingRef = useRef<boolean>(recording);
|
| 1413 |
-
const busyRef = useRef<boolean>(busy);
|
| 1414 |
-
const spaceHoldOwnsRecRef = useRef<boolean>(false);
|
| 1415 |
-
useEffect(() => {
|
| 1416 |
-
startRecordingRef.current = startSpaceHoldPTT;
|
| 1417 |
-
stopRecordingRef.current = stopSpaceHoldPTT;
|
| 1418 |
-
recordingRef.current = recording;
|
| 1419 |
-
busyRef.current = busy;
|
| 1420 |
-
});
|
| 1421 |
-
useEffect(() => {
|
| 1422 |
-
if (!voiceMasterOn) return;
|
| 1423 |
-
if (typeof window === "undefined") return;
|
| 1424 |
-
// SPACE-hold is suppressed only when the user is mid-edit in an
|
| 1425 |
-
// input/textarea WITH content. An EMPTY textarea (the common case
|
| 1426 |
-
// for a fresh chat with focus on the composer) still triggers
|
| 1427 |
-
// hold-to-talk; preventDefault stops a stray space from typing.
|
| 1428 |
-
const shouldSuppressSpace = () => {
|
| 1429 |
-
const ae = document.activeElement as HTMLElement | null;
|
| 1430 |
-
if (!ae) return false;
|
| 1431 |
-
const tag = ae.tagName;
|
| 1432 |
-
if (tag === "INPUT") {
|
| 1433 |
-
const ip = ae as HTMLInputElement;
|
| 1434 |
-
return (ip.value || "").length > 0;
|
| 1435 |
-
}
|
| 1436 |
-
if (tag === "TEXTAREA") {
|
| 1437 |
-
const ta = ae as HTMLTextAreaElement;
|
| 1438 |
-
return (ta.value || "").length > 0;
|
| 1439 |
-
}
|
| 1440 |
-
if (ae.isContentEditable) return (ae.textContent || "").length > 0;
|
| 1441 |
-
return false;
|
| 1442 |
-
};
|
| 1443 |
-
const onKeyDown = (e: KeyboardEvent) => {
|
| 1444 |
-
if (e.key !== " " && e.code !== "Space") return;
|
| 1445 |
-
if (e.repeat) return;
|
| 1446 |
-
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
|
| 1447 |
-
if (shouldSuppressSpace()) return;
|
| 1448 |
-
e.preventDefault();
|
| 1449 |
-
if (recordingRef.current || busyRef.current) return;
|
| 1450 |
-
spaceHoldOwnsRecRef.current = true;
|
| 1451 |
-
setSpaceHoldActive(true);
|
| 1452 |
-
const sr = startRecordingRef.current;
|
| 1453 |
-
if (sr) void sr();
|
| 1454 |
-
};
|
| 1455 |
-
const onKeyUp = (e: KeyboardEvent) => {
|
| 1456 |
-
if (e.key !== " " && e.code !== "Space") return;
|
| 1457 |
-
// Only react if THIS keydown started the recording; otherwise the
|
| 1458 |
-
// textarea may have been the legitimate target and we'd nuke it.
|
| 1459 |
-
if (!spaceHoldOwnsRecRef.current) return;
|
| 1460 |
-
e.preventDefault();
|
| 1461 |
-
spaceHoldOwnsRecRef.current = false;
|
| 1462 |
-
setSpaceHoldActive(false);
|
| 1463 |
-
const sp = stopRecordingRef.current;
|
| 1464 |
-
// Original guard was `recordingRef.current` (the legacy `recording`
|
| 1465 |
-
// state). The delegated path doesn't drive `recording` (the hook owns
|
| 1466 |
-
// capture state), so gate on the delegated in-flight flag instead β the
|
| 1467 |
-
// exact equivalent of "a capture this keydown started is still active".
|
| 1468 |
-
// Still resolve a deliberate hold even on a sub-threshold tap:
|
| 1469 |
-
// stopSpaceHoldPTT is a clean no-op when nothing is in flight.
|
| 1470 |
-
if (sp && spaceHoldPttInFlightRef.current) void sp();
|
| 1471 |
-
};
|
| 1472 |
-
window.addEventListener("keydown", onKeyDown);
|
| 1473 |
-
window.addEventListener("keyup", onKeyUp);
|
| 1474 |
-
return () => {
|
| 1475 |
-
window.removeEventListener("keydown", onKeyDown);
|
| 1476 |
-
window.removeEventListener("keyup", onKeyUp);
|
| 1477 |
-
};
|
| 1478 |
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
| 1479 |
-
}, [voiceMasterOn]);
|
| 1480 |
-
|
| 1481 |
async function handleFile(ev: React.ChangeEvent<HTMLInputElement>) {
|
| 1482 |
const f = ev.target.files?.[0];
|
| 1483 |
if (!f) return;
|
|
@@ -1998,7 +1819,7 @@ export default function Page() {
|
|
| 1998 |
</span>
|
| 1999 |
)}
|
| 2000 |
|
| 2001 |
-
{/* Push-to-talk button
|
| 2002 |
<button
|
| 2003 |
type="button"
|
| 2004 |
onClick={recording ? stopRecording : startRecording}
|
|
@@ -2006,32 +1827,27 @@ export default function Page() {
|
|
| 2006 |
className={`h-9 px-3 rounded-full flex items-center gap-1.5 text-xs font-medium transition-all ${
|
| 2007 |
recording
|
| 2008 |
? "bg-[var(--error)] text-white animate-record-pulse"
|
| 2009 |
-
:
|
| 2010 |
-
? "bg-emerald-700 text-white ring-2 ring-emerald-300"
|
| 2011 |
-
: "bg-emerald-600 hover:bg-emerald-700 text-white shadow-md ring-2 ring-emerald-300 dark:ring-emerald-700"
|
| 2012 |
} disabled:opacity-40`}
|
| 2013 |
title={recording
|
| 2014 |
? (isTouch
|
| 2015 |
? "Recording⦠tap to stop and send"
|
| 2016 |
-
: "Recording⦠click to stop and submit
|
| 2017 |
: (isTouch
|
| 2018 |
? "Tap to talk; tap again to stop. A pause auto-sends."
|
| 2019 |
-
: "Push-to-talk: click to start, click again to stop.
|
| 2020 |
>
|
| 2021 |
{recording ? <StopIcon /> : <MicIcon />}
|
| 2022 |
<span>{recording ? "Stop & send" : "Push-to-talk"}</span>
|
| 2023 |
</button>
|
| 2024 |
|
| 2025 |
-
{/*
|
| 2026 |
-
user holds SPACE without yet recording. */}
|
| 2027 |
<span className="text-xs text-[var(--muted-foreground)] italic">
|
| 2028 |
-
{recording
|
| 2029 |
-
? "Listeningβ¦
|
| 2030 |
-
:
|
| 2031 |
-
|
| 2032 |
-
|
| 2033 |
-
? "Tap Push-to-talk, then pause β it sends itself"
|
| 2034 |
-
: "or hold SPACE to talk Β· release to submit")}
|
| 2035 |
</span>
|
| 2036 |
</div>
|
| 2037 |
)}
|
|
@@ -3011,9 +2827,6 @@ function EmptyState({
|
|
| 3011 |
}) {
|
| 3012 |
const isHi = uiLang === "hi";
|
| 3013 |
const L = (en: string, hi: string) => (isHi ? hi : en);
|
| 3014 |
-
// #3 mobile β drop the SPACE-only mode on touch; the Push-to-talk tile
|
| 3015 |
-
// already gives phone users the correct ("tap the green mic") path.
|
| 3016 |
-
const isTouch = useIsTouch();
|
| 3017 |
|
| 3018 |
// Coverage facts, rendered as one-line bullets (never a wrapping blob).
|
| 3019 |
const policyCount = coverage ? coverage.total_policies : 169;
|
|
@@ -3142,13 +2955,6 @@ function EmptyState({
|
|
| 3142 |
title={L("Push-to-talk", "Push-to-talk")}
|
| 3143 |
body={L("Tap the green mic for one turn", "ΰ€Ήΰ€°ΰ₯ mic ΰ€ͺΰ€° tap ΰ€ΰ€°ΰ₯ΰ€")}
|
| 3144 |
/>
|
| 3145 |
-
{!isTouch && (
|
| 3146 |
-
<ModeRow
|
| 3147 |
-
icon="space"
|
| 3148 |
-
title={L("Hold SPACE", "SPACE ΰ€¦ΰ€¬ΰ€Ύΰ€ΰ€")}
|
| 3149 |
-
body={L("Hold to talk, release to send", "ΰ€¦ΰ€¬ΰ€Ύΰ€ΰ€° ΰ€¬ΰ₯ΰ€²ΰ₯ΰ€, ΰ€ΰ₯ΰ€‘ΰ€Όΰ€¨ΰ₯ ΰ€ͺΰ€° send")}
|
| 3150 |
-
/>
|
| 3151 |
-
)}
|
| 3152 |
<ModeRow
|
| 3153 |
icon="wave"
|
| 3154 |
title={L("Live (BETA)", "Live (BETA)")}
|
|
@@ -3347,7 +3153,7 @@ function ModeRow({
|
|
| 3347 |
title,
|
| 3348 |
body,
|
| 3349 |
}: {
|
| 3350 |
-
icon: "keyboard" | "mic" | "
|
| 3351 |
title: string;
|
| 3352 |
body: string;
|
| 3353 |
}) {
|
|
@@ -3459,7 +3265,7 @@ function SectionIcon({ kind }: { kind: "lightbulb" | "mic" | "shield" }) {
|
|
| 3459 |
}
|
| 3460 |
|
| 3461 |
// ModeIcon β small icons next to each input mode.
|
| 3462 |
-
function ModeIcon({ kind }: { kind: "keyboard" | "mic" | "
|
| 3463 |
const common = {
|
| 3464 |
width: 18,
|
| 3465 |
height: 18,
|
|
@@ -3487,14 +3293,6 @@ function ModeIcon({ kind }: { kind: "keyboard" | "mic" | "space" | "wave" }) {
|
|
| 3487 |
</svg>
|
| 3488 |
);
|
| 3489 |
}
|
| 3490 |
-
if (kind === "space") {
|
| 3491 |
-
return (
|
| 3492 |
-
<svg {...common}>
|
| 3493 |
-
<rect x="3" y="8" width="18" height="9" rx="2" />
|
| 3494 |
-
<path d="M7 13h10" />
|
| 3495 |
-
</svg>
|
| 3496 |
-
);
|
| 3497 |
-
}
|
| 3498 |
// wave
|
| 3499 |
return (
|
| 3500 |
<svg {...common}>
|
|
@@ -3987,6 +3785,9 @@ function CitedPolicyCards({
|
|
| 3987 |
onOpenMarketplace?: () => void;
|
| 3988 |
}) {
|
| 3989 |
const [cards, setCards] = useState<Record<string, ScorecardResponse | null>>({});
|
|
|
|
|
|
|
|
|
|
| 3990 |
const [compareOpen, setCompareOpen] = useState(false);
|
| 3991 |
|
| 3992 |
// Build a policy_id β MarketplacePolicy lookup so the modal can render the
|
|
@@ -4095,6 +3896,20 @@ function CitedPolicyCards({
|
|
| 4095 |
// eslint-disable-next-line react-hooks/exhaustive-deps
|
| 4096 |
}, [citations.map((c) => c.policy_id).join("|")]);
|
| 4097 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4098 |
if (topPolicies.length === 0) return null;
|
| 4099 |
|
| 4100 |
return (
|
|
@@ -4164,6 +3979,42 @@ function CitedPolicyCards({
|
|
| 4164 |
</div>
|
| 4165 |
);
|
| 4166 |
})()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4167 |
</div>
|
| 4168 |
{sc && (
|
| 4169 |
<div
|
|
@@ -5462,7 +5313,6 @@ function LiveBetaGateModal({
|
|
| 5462 |
onCancel: () => void;
|
| 5463 |
}) {
|
| 5464 |
const L = (en: string, hi: string) => (hindi ? hi : en);
|
| 5465 |
-
const isTouch = useIsTouch();
|
| 5466 |
const dialogRef = useRef<HTMLDivElement | null>(null);
|
| 5467 |
|
| 5468 |
// Escape cancels (treated as "did not confirm"); move focus into the
|
|
@@ -5614,15 +5464,10 @@ function LiveBetaGateModal({
|
|
| 5614 |
</ul>
|
| 5615 |
|
| 5616 |
<p className="mt-4 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">
|
| 5617 |
-
{
|
| 5618 |
-
|
| 5619 |
-
|
| 5620 |
-
|
| 5621 |
-
)
|
| 5622 |
-
: L(
|
| 5623 |
-
"Prefer Push-to-talk or hold-SPACE β both are stable and use Sarvam STT (handles Hindi / Indic correctly).",
|
| 5624 |
-
"Push-to-talk ΰ€―ΰ€Ύ SPACE ΰ€¦ΰ€¬ΰ€Ύΰ€ΰ€° ΰ€¬ΰ₯ΰ€²ΰ€¨ΰ€Ύ ΰ€¬ΰ₯ΰ€Ήΰ€€ΰ€° ΰ€Ήΰ₯ β ΰ€¦ΰ₯ΰ€¨ΰ₯ΰ€ ΰ€Έΰ₯ΰ€₯ΰ€Ώΰ€° ΰ€Ήΰ₯ΰ€ ΰ€ΰ€° Sarvam STT ΰ€΅ΰ€Ύΰ€ͺΰ€°ΰ€€ΰ₯ ΰ€Ήΰ₯ΰ€ (ΰ€Ήΰ€Ώΰ€¨ΰ₯ΰ€¦ΰ₯ / Indic ΰ€Έΰ€Ήΰ₯ ΰ€Έΰ€ΰ€ΰ€Ύΰ€²ΰ€€ΰ€Ύ ΰ€Ήΰ₯)ΰ₯€"
|
| 5625 |
-
)}
|
| 5626 |
</p>
|
| 5627 |
|
| 5628 |
{/* Confirm / Cancel. Cancel is the safe default (autofocused). */}
|
|
|
|
| 62 |
const [busy, setBusy] = useState(false);
|
| 63 |
// Voice-display fix β the composer <textarea> must grow as the live
|
| 64 |
// interim voice transcript accumulates so the user sees their FULL
|
| 65 |
+
// spoken sentence (not just the first line) while using Push-to-talk.
|
| 66 |
// The textarea has resize-none + a small min-height, so without this
|
| 67 |
// it stays clamped to one line and the transcript visually truncates
|
| 68 |
// even though capture/submit are correct. We size height to scrollHeight
|
|
|
|
| 83 |
const [returnAudio] = useState(true);
|
| 84 |
const [ttsLang] = useState<"en-IN" | "hi-IN">("en-IN");
|
| 85 |
// KI-257 β master Voice toggle. When OFF, the chat input shows only
|
| 86 |
+
// textarea + Send. When ON, reveals the Live (BETA) option and the
|
| 87 |
+
// Push-to-talk button. Persisted via localStorage.
|
|
|
|
|
|
|
| 88 |
const [voiceMasterOn, setVoiceMasterOn] = useState(false);
|
| 89 |
+
// #3 mobile β touch vs pointer changes the voice copy ("tap" vs
|
| 90 |
+
// "click" the mic). Shared SSR-safe hook.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
const isTouch = useIsTouch();
|
| 92 |
// Live (BETA) risk-confirmation gate. Opening Live always-on must surface
|
| 93 |
// a clear, styled WARNING modal listing the real failure modes EVERY time
|
| 94 |
// (no localStorage "seen once" bypass β the old window.confirm gate let
|
| 95 |
// production users skip the warning entirely after one ack, or whenever
|
| 96 |
// the browser suppressed the native dialog). The live session only starts
|
| 97 |
+
// on explicit Confirm; Cancel reverts the toggle. PTT is never gated.
|
|
|
|
| 98 |
const [showLiveGate, setShowLiveGate] = useState(false);
|
| 99 |
// Visual UI language β same source as ttsLang so the toggle controls both
|
| 100 |
const uiLang: UILang = ttsLang === "hi-IN" ? "hi" : "en";
|
|
|
|
| 478 |
useEffect(() => {
|
| 479 |
const ta = composerRef.current;
|
| 480 |
if (!ta) return;
|
| 481 |
+
// While capturing voice (PTT click or Live), give the box
|
| 482 |
// far more room so the entire accumulated interim transcript is on
|
| 483 |
// screen. Idle/typed flow keeps a calmer cap. Both are well above one
|
| 484 |
// line β the previous max-h-32 (128px) was the perceived "truncation".
|
|
|
|
| 487 |
// "couldn't see the whole transcript even though it was all captured".
|
| 488 |
// While capturing, grow up to ~half the viewport so the full utterance
|
| 489 |
// is visible; only the genuinely huge tail still scrolls.
|
| 490 |
+
const isCapturing = recording || live.recording;
|
| 491 |
const vh = typeof window !== "undefined" ? window.innerHeight : 800;
|
| 492 |
const maxH = isCapturing ? Math.min(Math.round(vh * 0.5), 520) : 160;
|
| 493 |
// Collapse first so shrinking text (word-erase / send-clear) recomputes
|
|
|
|
| 505 |
} else {
|
| 506 |
ta.style.overflowY = "hidden";
|
| 507 |
}
|
| 508 |
+
}, [input, recording, live.recording]);
|
| 509 |
|
| 510 |
// Voice-display fix β keep the PTT interim strip pinned to its newest
|
| 511 |
// text. The strip now wraps + caps its height + scrolls internally, so
|
|
|
|
| 1299 |
}
|
| 1300 |
function stopRecording() { mediaRecorderRef.current?.stop(); }
|
| 1301 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1302 |
async function handleFile(ev: React.ChangeEvent<HTMLInputElement>) {
|
| 1303 |
const f = ev.target.files?.[0];
|
| 1304 |
if (!f) return;
|
|
|
|
| 1819 |
</span>
|
| 1820 |
)}
|
| 1821 |
|
| 1822 |
+
{/* Push-to-talk button */}
|
| 1823 |
<button
|
| 1824 |
type="button"
|
| 1825 |
onClick={recording ? stopRecording : startRecording}
|
|
|
|
| 1827 |
className={`h-9 px-3 rounded-full flex items-center gap-1.5 text-xs font-medium transition-all ${
|
| 1828 |
recording
|
| 1829 |
? "bg-[var(--error)] text-white animate-record-pulse"
|
| 1830 |
+
: "bg-emerald-600 hover:bg-emerald-700 text-white shadow-md ring-2 ring-emerald-300 dark:ring-emerald-700"
|
|
|
|
|
|
|
| 1831 |
} disabled:opacity-40`}
|
| 1832 |
title={recording
|
| 1833 |
? (isTouch
|
| 1834 |
? "Recording⦠tap to stop and send"
|
| 1835 |
+
: "Recording⦠click to stop and submit")
|
| 1836 |
: (isTouch
|
| 1837 |
? "Tap to talk; tap again to stop. A pause auto-sends."
|
| 1838 |
+
: "Push-to-talk: click to start, click again to stop.")}
|
| 1839 |
>
|
| 1840 |
{recording ? <StopIcon /> : <MicIcon />}
|
| 1841 |
<span>{recording ? "Stop & send" : "Push-to-talk"}</span>
|
| 1842 |
</button>
|
| 1843 |
|
| 1844 |
+
{/* PTT status hint. */}
|
|
|
|
| 1845 |
<span className="text-xs text-[var(--muted-foreground)] italic">
|
| 1846 |
+
{recording
|
| 1847 |
+
? (isTouch ? "Listening⦠tap Stop to send" : "Listening⦠click Stop to submit")
|
| 1848 |
+
: (isTouch
|
| 1849 |
+
? "Tap Push-to-talk, then pause β it sends itself"
|
| 1850 |
+
: "Click Push-to-talk, then pause β it sends itself")}
|
|
|
|
|
|
|
| 1851 |
</span>
|
| 1852 |
</div>
|
| 1853 |
)}
|
|
|
|
| 2827 |
}) {
|
| 2828 |
const isHi = uiLang === "hi";
|
| 2829 |
const L = (en: string, hi: string) => (isHi ? hi : en);
|
|
|
|
|
|
|
|
|
|
| 2830 |
|
| 2831 |
// Coverage facts, rendered as one-line bullets (never a wrapping blob).
|
| 2832 |
const policyCount = coverage ? coverage.total_policies : 169;
|
|
|
|
| 2955 |
title={L("Push-to-talk", "Push-to-talk")}
|
| 2956 |
body={L("Tap the green mic for one turn", "ΰ€Ήΰ€°ΰ₯ mic ΰ€ͺΰ€° tap ΰ€ΰ€°ΰ₯ΰ€")}
|
| 2957 |
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2958 |
<ModeRow
|
| 2959 |
icon="wave"
|
| 2960 |
title={L("Live (BETA)", "Live (BETA)")}
|
|
|
|
| 3153 |
title,
|
| 3154 |
body,
|
| 3155 |
}: {
|
| 3156 |
+
icon: "keyboard" | "mic" | "wave";
|
| 3157 |
title: string;
|
| 3158 |
body: string;
|
| 3159 |
}) {
|
|
|
|
| 3265 |
}
|
| 3266 |
|
| 3267 |
// ModeIcon β small icons next to each input mode.
|
| 3268 |
+
function ModeIcon({ kind }: { kind: "keyboard" | "mic" | "wave" }) {
|
| 3269 |
const common = {
|
| 3270 |
width: 18,
|
| 3271 |
height: 18,
|
|
|
|
| 3293 |
</svg>
|
| 3294 |
);
|
| 3295 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3296 |
// wave
|
| 3297 |
return (
|
| 3298 |
<svg {...common}>
|
|
|
|
| 3785 |
onOpenMarketplace?: () => void;
|
| 3786 |
}) {
|
| 3787 |
const [cards, setCards] = useState<Record<string, ScorecardResponse | null>>({});
|
| 3788 |
+
// Keyed by insurer_slug (reviews are per-insurer, not per-policy) so
|
| 3789 |
+
// several cited policies from the same insurer share one fetch/result.
|
| 3790 |
+
const [reviews, setReviews] = useState<Record<string, InsurerReviews | null>>({});
|
| 3791 |
const [compareOpen, setCompareOpen] = useState(false);
|
| 3792 |
|
| 3793 |
// Build a policy_id β MarketplacePolicy lookup so the modal can render the
|
|
|
|
| 3896 |
// eslint-disable-next-line react-hooks/exhaustive-deps
|
| 3897 |
}, [citations.map((c) => c.policy_id).join("|")]);
|
| 3898 |
|
| 3899 |
+
// Insurer reputation / reviews. The full detail modal shows a reviews
|
| 3900 |
+
// section; the inline cited cards omitted it (user-flagged β same class
|
| 3901 |
+
// as #65's claim-experience gap). Fetch once per DISTINCT insurer_slug.
|
| 3902 |
+
useEffect(() => {
|
| 3903 |
+
const slugs = Array.from(new Set(topPolicies.map((c) => c.insurer_slug)));
|
| 3904 |
+
for (const slug of slugs) {
|
| 3905 |
+
if (!slug || reviews[slug] !== undefined) continue;
|
| 3906 |
+
getInsurerReviews(slug)
|
| 3907 |
+
.then((r) => setReviews((p) => ({ ...p, [slug]: r })))
|
| 3908 |
+
.catch(() => setReviews((p) => ({ ...p, [slug]: null })));
|
| 3909 |
+
}
|
| 3910 |
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
| 3911 |
+
}, [topPolicies.map((c) => c.insurer_slug).join("|")]);
|
| 3912 |
+
|
| 3913 |
if (topPolicies.length === 0) return null;
|
| 3914 |
|
| 3915 |
return (
|
|
|
|
| 3979 |
</div>
|
| 3980 |
);
|
| 3981 |
})()}
|
| 3982 |
+
{/* Reviews β the full detail modal renders an insurer
|
| 3983 |
+
reputation/reviews section; these inline cards
|
| 3984 |
+
omitted it (user-flagged). Mirrors the #65
|
| 3985 |
+
claim-experience pattern + the #76 rule: ALWAYS
|
| 3986 |
+
render the labelled line, never silently vanish
|
| 3987 |
+
when the fetch is slow / null. */}
|
| 3988 |
+
{(() => {
|
| 3989 |
+
const rv = reviews[c.insurer_slug];
|
| 3990 |
+
const lbl = (
|
| 3991 |
+
<span className="font-semibold text-[var(--foreground)]">
|
| 3992 |
+
Reviews:
|
| 3993 |
+
</span>
|
| 3994 |
+
);
|
| 3995 |
+
if (rv) {
|
| 3996 |
+
const s = rv.aggregate_score || {};
|
| 3997 |
+
const csr = rv.claim_metrics?.claim_settlement_ratio_pct;
|
| 3998 |
+
const bits: string[] = [];
|
| 3999 |
+
if (s.letter_grade) bits.push(s.letter_grade);
|
| 4000 |
+
if (s.value_0_100 != null) bits.push(`${s.value_0_100}/100`);
|
| 4001 |
+
if (csr != null) bits.push(`${csr}% claims settled`);
|
| 4002 |
+
return (
|
| 4003 |
+
<div className="text-[10.5px] text-[var(--muted-foreground)] mt-1 line-clamp-2">
|
| 4004 |
+
{lbl} {bits.join(" Β· ")}
|
| 4005 |
+
{s.headline ? ` β ${s.headline}` : ""}
|
| 4006 |
+
</div>
|
| 4007 |
+
);
|
| 4008 |
+
}
|
| 4009 |
+
return (
|
| 4010 |
+
<div className="text-[10.5px] text-[var(--muted-foreground)] italic mt-1">
|
| 4011 |
+
{lbl}{" "}
|
| 4012 |
+
{rv === null
|
| 4013 |
+
? "reputation data being compiled"
|
| 4014 |
+
: "loading reputationβ¦"}
|
| 4015 |
+
</div>
|
| 4016 |
+
);
|
| 4017 |
+
})()}
|
| 4018 |
</div>
|
| 4019 |
{sc && (
|
| 4020 |
<div
|
|
|
|
| 5313 |
onCancel: () => void;
|
| 5314 |
}) {
|
| 5315 |
const L = (en: string, hi: string) => (hindi ? hi : en);
|
|
|
|
| 5316 |
const dialogRef = useRef<HTMLDivElement | null>(null);
|
| 5317 |
|
| 5318 |
// Escape cancels (treated as "did not confirm"); move focus into the
|
|
|
|
| 5464 |
</ul>
|
| 5465 |
|
| 5466 |
<p className="mt-4 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">
|
| 5467 |
+
{L(
|
| 5468 |
+
"Prefer Push-to-talk β it's stable and uses Sarvam STT (handles Hindi / Indic correctly).",
|
| 5469 |
+
"Push-to-talk ΰ€¬ΰ₯ΰ€Ήΰ€€ΰ€° ΰ€Ήΰ₯ β ΰ€―ΰ€Ή ΰ€Έΰ₯ΰ€₯ΰ€Ώΰ€° ΰ€Ήΰ₯ ΰ€ΰ€° Sarvam STT ΰ€΅ΰ€Ύΰ€ͺΰ€°ΰ€€ΰ€Ύ ΰ€Ήΰ₯ (ΰ€Ήΰ€Ώΰ€¨ΰ₯ΰ€¦ΰ₯ / Indic ΰ€Έΰ€Ήΰ₯ ΰ€Έΰ€ΰ€ΰ€Ύΰ€²ΰ€€ΰ€Ύ ΰ€Ήΰ₯)ΰ₯€"
|
| 5470 |
+
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5471 |
</p>
|
| 5472 |
|
| 5473 |
{/* Confirm / Cancel. Cancel is the safe default (autofocused). */}
|
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regression test for the Bug 4/5 fix (2026-05-18).
|
| 2 |
+
|
| 3 |
+
Symptom: after cards were shown, the brain answered "I don't have enough
|
| 4 |
+
information" for claim-settlement ratio / denials / complaints and would
|
| 5 |
+
not compare two policies β because it had NO tool to reach claim/review
|
| 6 |
+
data (retrieve_policies returns policy WORDING only) and was never shown
|
| 7 |
+
its own shortlist.
|
| 8 |
+
|
| 9 |
+
Fix: a `get_policy_facts` tool that returns the authoritative claim /
|
| 10 |
+
reputation / scorecard / coverage data (the same `40-data/reviews/<slug>`
|
| 11 |
+
+ scorecard the detail-modal uses), plus ACTIVE-SHORTLIST injection so the
|
| 12 |
+
model can resolve "#1/#2/the HDFC one" to policy_ids.
|
| 13 |
+
|
| 14 |
+
These tests are deterministic (no live LLM): they pin the tool wiring and
|
| 15 |
+
that get_policy_facts actually returns the real claim-settlement numbers.
|
| 16 |
+
"""
|
| 17 |
+
import json
|
| 18 |
+
import glob
|
| 19 |
+
import os
|
| 20 |
+
from types import SimpleNamespace
|
| 21 |
+
|
| 22 |
+
import pytest
|
| 23 |
+
|
| 24 |
+
from backend import brain_tools, single_brain
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _a_slug_with_reviews():
|
| 28 |
+
"""Pick a real insurer slug that has a reviews JSON with a numeric
|
| 29 |
+
claim_settlement_ratio_pct (so the assertion is data-driven, not
|
| 30 |
+
hardcoded)."""
|
| 31 |
+
for fp in sorted(glob.glob("40-data/reviews/*.json")):
|
| 32 |
+
try:
|
| 33 |
+
d = json.loads(open(fp).read())
|
| 34 |
+
except Exception:
|
| 35 |
+
continue
|
| 36 |
+
csr = (d.get("claim_metrics") or {}).get("claim_settlement_ratio_pct")
|
| 37 |
+
if isinstance(csr, (int, float)):
|
| 38 |
+
return d["insurer_slug"], float(csr), d
|
| 39 |
+
pytest.skip("no reviews JSON with a numeric claim_settlement_ratio_pct")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_tool_is_registered_and_wired():
|
| 43 |
+
names = [t["name"] for t in single_brain.TOOL_SCHEMAS]
|
| 44 |
+
assert "get_policy_facts" in names, names
|
| 45 |
+
# wired in the dispatcher (string presence is a cheap structural pin)
|
| 46 |
+
import inspect
|
| 47 |
+
src = inspect.getsource(single_brain._execute_tool)
|
| 48 |
+
assert 'name == "get_policy_facts"' in src
|
| 49 |
+
assert "brain_tools.get_policy_facts(" in src
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_get_policy_facts_returns_real_claim_metrics():
|
| 53 |
+
slug, csr, raw = _a_slug_with_reviews()
|
| 54 |
+
pid = f"test::{slug}::policy"
|
| 55 |
+
session = SimpleNamespace(
|
| 56 |
+
last_recommendation_ids=[pid],
|
| 57 |
+
last_recommendation_snapshot={pid: "Test Policy"},
|
| 58 |
+
slug_to_insurer={pid: slug},
|
| 59 |
+
last_retrieved_chunks=[
|
| 60 |
+
{"policy_id": pid, "policy_name": "Test Policy",
|
| 61 |
+
"insurer_slug": slug}
|
| 62 |
+
],
|
| 63 |
+
)
|
| 64 |
+
res = brain_tools.get_policy_facts(session, policy_ids=[pid])
|
| 65 |
+
assert res.get("ok") is True, res
|
| 66 |
+
assert res["count"] == 1
|
| 67 |
+
p = res["policies"][0]
|
| 68 |
+
# The exact IRDAI claim-settlement ratio the modal shows β the brain
|
| 69 |
+
# can now cite this instead of refusing.
|
| 70 |
+
assert p["claim_settlement_ratio_pct"] == csr, (p, csr)
|
| 71 |
+
assert p["insurer_slug"] == slug
|
| 72 |
+
assert p["reviews_available"] is True
|
| 73 |
+
# complaints/source surfaced for the "how often do they deny" answer.
|
| 74 |
+
assert "complaints_per_10k_policies" in p
|
| 75 |
+
assert "claim_data_source_url" in p
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_empty_policy_ids_falls_back_to_active_shortlist():
|
| 79 |
+
slug, csr, _ = _a_slug_with_reviews()
|
| 80 |
+
pid = f"test::{slug}::policy"
|
| 81 |
+
session = SimpleNamespace(
|
| 82 |
+
last_recommendation_ids=[pid],
|
| 83 |
+
last_recommendation_snapshot={pid: "Test Policy"},
|
| 84 |
+
slug_to_insurer={pid: slug},
|
| 85 |
+
last_retrieved_chunks=[
|
| 86 |
+
{"policy_id": pid, "policy_name": "Test Policy",
|
| 87 |
+
"insurer_slug": slug}
|
| 88 |
+
],
|
| 89 |
+
)
|
| 90 |
+
# No explicit ids β must use session.last_recommendation_ids so
|
| 91 |
+
# "compare the ones you showed" works.
|
| 92 |
+
res = brain_tools.get_policy_facts(session, policy_ids=None)
|
| 93 |
+
assert res.get("ok") is True
|
| 94 |
+
assert [p["policy_id"] for p in res["policies"]] == [pid]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_no_shortlist_returns_clean_error_not_crash():
|
| 98 |
+
session = SimpleNamespace(
|
| 99 |
+
last_recommendation_ids=[],
|
| 100 |
+
last_recommendation_snapshot={},
|
| 101 |
+
slug_to_insurer={},
|
| 102 |
+
last_retrieved_chunks=[],
|
| 103 |
+
)
|
| 104 |
+
res = brain_tools.get_policy_facts(session, policy_ids=None)
|
| 105 |
+
assert res.get("ok") is False
|
| 106 |
+
assert "no_policy_ids" in res.get("error", "")
|
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regression test (2026-05-18) β spoken prose emitted in an EARLY
|
| 2 |
+
tool-call iteration must NOT be erased by a LATER iteration that returns
|
| 3 |
+
only function calls and no text.
|
| 4 |
+
|
| 5 |
+
THE BUG (user-reported live symptom):
|
| 6 |
+
"did not speak any of the words after just saying profile now; did not
|
| 7 |
+
present the policies β in speech form."
|
| 8 |
+
|
| 9 |
+
After the profile completes the model often emits, on ONE iteration, a
|
| 10 |
+
text part ("Great, your profile is complete!") TOGETHER with a tool
|
| 11 |
+
call (save_profile_field). The next iteration is pure tool calls
|
| 12 |
+
(retrieve_policies + mark_recommendation) with NO text part. If the
|
| 13 |
+
conversation then ends without a further free-text iteration, the final
|
| 14 |
+
reply must still be the prose captured earlier.
|
| 15 |
+
|
| 16 |
+
ROOT CAUSE:
|
| 17 |
+
single_brain.handle_turn's tool-call loop ended every CASE-B iteration
|
| 18 |
+
with an UNCONDITIONAL `last_text = text`. `text` is "" on a pure
|
| 19 |
+
tool-call iteration, so iteration 2 overwrote the iteration-1 prose with
|
| 20 |
+
"". `reply_text = last_text or _HONEST_EMPTY_REPLY` then surfaced the
|
| 21 |
+
honest-empty fallback (or nothing), and main.py skips TTS when
|
| 22 |
+
reply_text is empty/fallback β the bot went SILENT right after profile
|
| 23 |
+
completion / policy presentation.
|
| 24 |
+
|
| 25 |
+
THE CONTRACT THIS PINS:
|
| 26 |
+
An iteration that produces NO text part must not destroy prose captured
|
| 27 |
+
in a PRIOR iteration. A non-empty text on any iteration still updates
|
| 28 |
+
last_text (so the MAX_ITERATIONS-with-text safety the original comment
|
| 29 |
+
referred to is preserved); an empty one is a no-op.
|
| 30 |
+
|
| 31 |
+
Run:
|
| 32 |
+
cd /Users/rohitsar/Developer/Insurance\\ Sales\\ Bot
|
| 33 |
+
PYTHONPATH=$PWD .venv/bin/python -m pytest -q \\
|
| 34 |
+
tests/test_last_text_preserved_across_tool_iters.py
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
from __future__ import annotations
|
| 38 |
+
|
| 39 |
+
import asyncio
|
| 40 |
+
import os
|
| 41 |
+
import sys
|
| 42 |
+
import unittest
|
| 43 |
+
import uuid
|
| 44 |
+
from pathlib import Path
|
| 45 |
+
from unittest import mock
|
| 46 |
+
|
| 47 |
+
_REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 48 |
+
if str(_REPO_ROOT) not in sys.path:
|
| 49 |
+
sys.path.insert(0, str(_REPO_ROOT))
|
| 50 |
+
|
| 51 |
+
from backend import brain_tools, single_brain # noqa: E402
|
| 52 |
+
from backend.single_brain import _HONEST_EMPTY_REPLY # noqa: E402
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _run(coro):
|
| 56 |
+
return asyncio.new_event_loop().run_until_complete(coro)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _fc_part(name, args):
|
| 60 |
+
return {"functionCall": {"name": name, "args": args}}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _text_and_fc_payload(text, parts):
|
| 64 |
+
"""A single model turn that carries BOTH a text part AND function-call
|
| 65 |
+
parts β the realistic 'Great, your profile is complete!' + a tool call
|
| 66 |
+
shape that triggers the bug."""
|
| 67 |
+
return {"candidates": [{"content": {"parts": [{"text": text}] + parts}}]}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _tool_payload(parts):
|
| 71 |
+
return {"candidates": [{"content": {"parts": parts}}]}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _text_payload(text):
|
| 75 |
+
return {"candidates": [{"content": {"parts": [{"text": text}]}}]}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _enriched(pid, name, slug, score, cid, *, grade="A", overall=85):
|
| 79 |
+
return {
|
| 80 |
+
"chunk_id": cid, "policy_id": pid, "policy_name": name,
|
| 81 |
+
"insurer_slug": slug, "doc_type": "policy",
|
| 82 |
+
"source_url": f"https://example.com/{pid}.pdf", "score": score,
|
| 83 |
+
"_grade": grade, "_overall_score": overall,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class _Harness(unittest.TestCase):
|
| 88 |
+
"""Drives single_brain.handle_turn for real; only the Gemini and vector
|
| 89 |
+
seams are stubbed (same pattern as test_recommendation_transparency)."""
|
| 90 |
+
|
| 91 |
+
def setUp(self):
|
| 92 |
+
self._env = mock.patch.dict(os.environ,
|
| 93 |
+
{"GOOGLE_API_KEY": "test-key"})
|
| 94 |
+
self._env.start()
|
| 95 |
+
self._gemini_script: list = []
|
| 96 |
+
self._retrieve_chunks: list = []
|
| 97 |
+
|
| 98 |
+
async def _fake_gemini(*_a, **_k):
|
| 99 |
+
if not self._gemini_script:
|
| 100 |
+
return _text_payload("(no more scripted turns)")
|
| 101 |
+
return self._gemini_script.pop(0)
|
| 102 |
+
|
| 103 |
+
async def _fake_retrieve(*_a, **_k):
|
| 104 |
+
chunks = list(self._retrieve_chunks)
|
| 105 |
+
sess = _k.get("session")
|
| 106 |
+
if sess is not None:
|
| 107 |
+
sess.last_retrieved_chunks = list(chunks)
|
| 108 |
+
sess.slug_to_insurer = {
|
| 109 |
+
c["policy_id"]: c["insurer_slug"] for c in chunks
|
| 110 |
+
}
|
| 111 |
+
return {"chunks": chunks, "count": len(chunks)}
|
| 112 |
+
|
| 113 |
+
self._gp = mock.patch.object(single_brain, "_gemini_call",
|
| 114 |
+
_fake_gemini)
|
| 115 |
+
self._rp = mock.patch.object(brain_tools, "retrieve_policies",
|
| 116 |
+
_fake_retrieve)
|
| 117 |
+
self._gp.start()
|
| 118 |
+
self._rp.start()
|
| 119 |
+
|
| 120 |
+
def tearDown(self):
|
| 121 |
+
self._rp.stop()
|
| 122 |
+
self._gp.stop()
|
| 123 |
+
self._env.stop()
|
| 124 |
+
|
| 125 |
+
def _ready_session(self):
|
| 126 |
+
from backend.session_state import SessionState
|
| 127 |
+
sess = SessionState(session_id=f"t_{uuid.uuid4().hex[:8]}")
|
| 128 |
+
sess.profile.name = "Asha"
|
| 129 |
+
sess.profile.age = 35
|
| 130 |
+
sess.profile.dependents = "self+spouse"
|
| 131 |
+
sess.profile.location_tier = "metro"
|
| 132 |
+
sess.profile.income_band = "10L-25L"
|
| 133 |
+
sess.profile.primary_goal = "first_buy"
|
| 134 |
+
sess.profile.health_conditions = ["none"]
|
| 135 |
+
sess.pricing_bundle_skipped = True
|
| 136 |
+
return sess
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class TestEarlyProseSurvivesLaterPureToolIters(_Harness):
|
| 140 |
+
def test_profile_complete_prose_then_pure_tool_iters_is_spoken(self):
|
| 141 |
+
"""User's exact symptom: prose comes WITH a tool call in iter 1;
|
| 142 |
+
iters 2-3 are pure tool calls with NO text; the turn then ends.
|
| 143 |
+
reply_text MUST still be the iter-1 prose, NOT _HONEST_EMPTY_REPLY
|
| 144 |
+
(which makes main.py skip TTS β the bot goes silent)."""
|
| 145 |
+
sess = self._ready_session()
|
| 146 |
+
self._retrieve_chunks = [
|
| 147 |
+
_enriched("hdfc-ergo__optima-secure", "my:Optima Secure",
|
| 148 |
+
"hdfc-ergo", 0.81, "c1"),
|
| 149 |
+
_enriched("niva-bupa__reassure-3", "ReAssure 3.0",
|
| 150 |
+
"niva-bupa", 0.74, "c2"),
|
| 151 |
+
]
|
| 152 |
+
spoken = (
|
| 153 |
+
"Great, your profile is complete! Based on it, here are two "
|
| 154 |
+
"strong options: 1. my:Optima Secure (HDFC ERGO) "
|
| 155 |
+
"2. ReAssure 3.0 (Niva Bupa). Want me to compare them?"
|
| 156 |
+
)
|
| 157 |
+
self._gemini_script = [
|
| 158 |
+
# iter 1 β TEXT (the spoken prose) + a tool call in the SAME turn.
|
| 159 |
+
_text_and_fc_payload(
|
| 160 |
+
spoken,
|
| 161 |
+
[_fc_part("save_profile_field",
|
| 162 |
+
{"field": "smoker", "value": "no"})]),
|
| 163 |
+
# iter 2 β PURE tool calls, NO text part.
|
| 164 |
+
_tool_payload([_fc_part("retrieve_policies",
|
| 165 |
+
{"query": "metro family comprehensive"})]),
|
| 166 |
+
# iter 3 β PURE tool calls, NO text part. Loop ends here (CASE A
|
| 167 |
+
# is never reached because the model keeps tool-calling and the
|
| 168 |
+
# script then yields no further text turn before the loop's
|
| 169 |
+
# natural termination on the empty-script sentinel below).
|
| 170 |
+
_tool_payload([_fc_part("mark_recommendation", {
|
| 171 |
+
"policy_ids": ["hdfc-ergo__optima-secure",
|
| 172 |
+
"niva-bupa__reassure-3"]})]),
|
| 173 |
+
# iter 4 β model emits NO text (empty text part). This is the
|
| 174 |
+
# documented near-zero "LLM returned nothing" tail; the correct
|
| 175 |
+
# behaviour is to fall back to the EARLIER spoken prose, not to
|
| 176 |
+
# _HONEST_EMPTY_REPLY.
|
| 177 |
+
_text_payload(""),
|
| 178 |
+
]
|
| 179 |
+
|
| 180 |
+
r = _run(single_brain.handle_turn(sess, "I don't smoke"))
|
| 181 |
+
|
| 182 |
+
self.assertNotEqual(
|
| 183 |
+
r.reply_text, _HONEST_EMPTY_REPLY,
|
| 184 |
+
"BUG: an empty later tool-call/empty-text iteration erased the "
|
| 185 |
+
"iter-1 spoken prose, so reply_text became the honest-empty "
|
| 186 |
+
"fallback and main.py would skip TTS (bot goes silent).")
|
| 187 |
+
self.assertNotEqual(
|
| 188 |
+
r.reply_text.strip(), "",
|
| 189 |
+
"reply_text must not be empty β main.py skips TTS on empty text.")
|
| 190 |
+
self.assertIn(
|
| 191 |
+
"your profile is complete", r.reply_text,
|
| 192 |
+
"the spoken prose captured in iter 1 must survive to reply_text "
|
| 193 |
+
"so it is read aloud (TTS).")
|
| 194 |
+
self.assertIn("my:Optima Secure", r.reply_text,
|
| 195 |
+
"the presented policies must be in the spoken reply.")
|
| 196 |
+
|
| 197 |
+
def test_nonempty_later_text_still_wins(self):
|
| 198 |
+
"""Guard the original intent: if a LATER iteration DOES emit fresh
|
| 199 |
+
prose, that newer prose is what gets spoken (the fix must not pin
|
| 200 |
+
stale text)."""
|
| 201 |
+
sess = self._ready_session()
|
| 202 |
+
self._retrieve_chunks = [
|
| 203 |
+
_enriched("hdfc-ergo__optima-secure", "my:Optima Secure",
|
| 204 |
+
"hdfc-ergo", 0.81, "c1"),
|
| 205 |
+
]
|
| 206 |
+
self._gemini_script = [
|
| 207 |
+
_text_and_fc_payload(
|
| 208 |
+
"One moment while I pull plans for you...",
|
| 209 |
+
[_fc_part("retrieve_policies", {"query": "metro family"})]),
|
| 210 |
+
_tool_payload([_fc_part("mark_recommendation", {
|
| 211 |
+
"policy_ids": ["hdfc-ergo__optima-secure"]})]),
|
| 212 |
+
# Final free-text iteration β newer prose must replace the
|
| 213 |
+
# interim "one moment" line.
|
| 214 |
+
_text_payload(
|
| 215 |
+
"Here is my:Optima Secure (HDFC ERGO) β a strong "
|
| 216 |
+
"comprehensive plan for your family."),
|
| 217 |
+
]
|
| 218 |
+
r = _run(single_brain.handle_turn(sess, "show me options"))
|
| 219 |
+
self.assertIn("Here is my:Optima Secure", r.reply_text)
|
| 220 |
+
self.assertNotIn("One moment while I pull", r.reply_text,
|
| 221 |
+
"the fresher final prose must win over the interim "
|
| 222 |
+
"holding line.")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
if __name__ == "__main__":
|
| 226 |
+
unittest.main(verbosity=2)
|
|
@@ -1,29 +1,25 @@
|
|
| 1 |
-
"""Regression test for #53 (
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
----
|
| 6 |
-
page.tsx
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
delay before recording starts (#54).
|
| 18 |
-
|
| 19 |
-
FIX (frontend/src/lib/useStreamingVoice.ts)
|
| 20 |
-----------------------------------------------------------------------------
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
live capture, so the FIRST WORD always survives.
|
| 27 |
|
| 28 |
WHAT THIS TEST PINS
|
| 29 |
-----------------------------------------------------------------------------
|
|
|
|
| 1 |
+
"""Regression test for #53 (head-clipping) + #54 (capture start latency)
|
| 2 |
+
β 2026-05-18.
|
| 3 |
+
|
| 4 |
+
NOTE (2026-05-18): the SPACE hold-to-talk path was removed entirely; the
|
| 5 |
+
only voice-capture control is now the on-screen Push-to-talk button. This
|
| 6 |
+
test no longer pins any page.tsx SPACE wiring. It still pins the two
|
| 7 |
+
contracts that remain live and valuable:
|
| 8 |
+
|
| 9 |
+
1. The warm-stream PreRollRing + evaluateHoldGate exported from
|
| 10 |
+
frontend/src/lib/useStreamingVoice.ts (a rolling ~PRE_ROLL_MS pre-roll
|
| 11 |
+
buffer + a deliberate-hold gate that ignores sub-threshold taps).
|
| 12 |
+
2. The backend STT chunking path: the pre-roll head word survives
|
| 13 |
+
transcription and long audio is chunked, not truncated β this guards
|
| 14 |
+
the /api/transcribe behavior the Push-to-talk button still relies on.
|
| 15 |
+
|
| 16 |
+
ORIGINAL ROOT CAUSE (kept for context)
|
|
|
|
|
|
|
|
|
|
| 17 |
-----------------------------------------------------------------------------
|
| 18 |
+
A cold-started mic loses every word spoken between capture-request and
|
| 19 |
+
recorder.start() (getUserMedia is 200-700ms). Real repro: user said
|
| 20 |
+
"Sir. My age is 29 ..." -> transcribed "S A R. My age is 29 ..." (#53);
|
| 21 |
+
the same cold-start is the multi-second start delay (#54). The warm-stream
|
| 22 |
+
PreRollRing keeps the first word at the head of the blob.
|
|
|
|
| 23 |
|
| 24 |
WHAT THIS TEST PINS
|
| 25 |
-----------------------------------------------------------------------------
|
|
@@ -1,239 +0,0 @@
|
|
| 1 |
-
"""Regression test for #53 (PTT head-clip) + #54 (PTT start latency) β
|
| 2 |
-
the page.tsx SPACE-hold DELEGATION wiring β 2026-05-18.
|
| 3 |
-
|
| 4 |
-
WHY A SEPARATE TEST FROM test_ptt_preroll_warm_stream.py
|
| 5 |
-
-----------------------------------------------------------------------------
|
| 6 |
-
test_ptt_preroll_warm_stream.py pins the *hook's* pure pre-roll + hold-gate
|
| 7 |
-
logic (PreRollRing / evaluateHoldGate in useStreamingVoice.ts) and the
|
| 8 |
-
backend STT head-survival contract. It does NOT pin the remaining surface:
|
| 9 |
-
that page.tsx's SPACE-hold path actually DELEGATES to that hook instead of
|
| 10 |
-
cold-starting its own getUserMedia + MediaRecorder per press. Naive prepending
|
| 11 |
-
of the hook's pre-roll blobs onto page.tsx's *separate* recorder chunks would
|
| 12 |
-
produce a corrupt webm (two independent MediaRecorder streams); the only
|
| 13 |
-
correct fix is delegation. This file pins that delegation + every
|
| 14 |
-
non-negotiable semantic it must preserve.
|
| 15 |
-
|
| 16 |
-
WHY A SOURCE-ASSERTION TEST (no JS runner)
|
| 17 |
-
-----------------------------------------------------------------------------
|
| 18 |
-
This repo has NO JS/React test harness β frontend/package.json has no `test`
|
| 19 |
-
script, no jest/vitest, and `tests/` is a pure pytest (Python) suite. The
|
| 20 |
-
SPACE-hold delegation is browser DOM event wiring inside a React client
|
| 21 |
-
component; it cannot be exercised from Python, and standing up a
|
| 22 |
-
jest/RTL/jsdom toolchain would be a large out-of-scope change to shared
|
| 23 |
-
frontend tooling. The existing sibling test (test_ptt_preroll_warm_stream.py)
|
| 24 |
-
explicitly acknowledges this same constraint ("There is no JS test runner in
|
| 25 |
-
this repo, so the two contracts are pinned at the layers a Python test can
|
| 26 |
-
reach honestly") and pins frontend contracts via source assertions. This file
|
| 27 |
-
follows that established repo idiom: it asserts the structural wiring
|
| 28 |
-
contract in the SHIPPED page.tsx so a future refactor that silently
|
| 29 |
-
re-introduces the per-press cold start (or drops a preserved semantic) fails
|
| 30 |
-
CI loudly.
|
| 31 |
-
|
| 32 |
-
Run:
|
| 33 |
-
cd /Users/rohitsar/Developer/Insurance\\ Sales\\ Bot
|
| 34 |
-
PYTHONPATH=$PWD .venv/bin/python -m pytest \
|
| 35 |
-
tests/test_space_hold_ptt_delegation.py -v
|
| 36 |
-
"""
|
| 37 |
-
|
| 38 |
-
from __future__ import annotations
|
| 39 |
-
|
| 40 |
-
import re
|
| 41 |
-
from pathlib import Path
|
| 42 |
-
|
| 43 |
-
import pytest
|
| 44 |
-
|
| 45 |
-
REPO = Path(__file__).resolve().parents[1]
|
| 46 |
-
PAGE = REPO / "frontend" / "src" / "app" / "page.tsx"
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
@pytest.fixture(scope="module")
|
| 50 |
-
def src() -> str:
|
| 51 |
-
return PAGE.read_text()
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def _strip_comments(code: str) -> str:
|
| 55 |
-
"""Drop // line-comment content (and blank-after-strip lines) so negative
|
| 56 |
-
assertions ("must NOT call send()/setBusy(true)") match only real CODE,
|
| 57 |
-
not the explanatory comments that legitimately *name* the avoided trap."""
|
| 58 |
-
out = []
|
| 59 |
-
for line in code.splitlines():
|
| 60 |
-
# Remove an inline/standalone // comment. No string literal in the
|
| 61 |
-
# delegated handlers contains "//", so a plain split is safe here.
|
| 62 |
-
if "//" in line:
|
| 63 |
-
line = line[: line.index("//")]
|
| 64 |
-
if line.strip():
|
| 65 |
-
out.append(line)
|
| 66 |
-
return "\n".join(out)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def _slice(src: str, start_marker: str, end_marker: str) -> str:
|
| 70 |
-
"""Return the source between (and including) two anchor substrings.
|
| 71 |
-
Asserts both anchors exist exactly once so the test fails loudly if the
|
| 72 |
-
region is renamed rather than silently asserting against the wrong code.
|
| 73 |
-
"""
|
| 74 |
-
assert src.count(start_marker) == 1, f"anchor not unique: {start_marker!r}"
|
| 75 |
-
assert src.count(end_marker) == 1, f"anchor not unique: {end_marker!r}"
|
| 76 |
-
i = src.index(start_marker)
|
| 77 |
-
j = src.index(end_marker, i) + len(end_marker)
|
| 78 |
-
assert j > i, f"end anchor precedes start anchor: {end_marker!r}"
|
| 79 |
-
return src[i:j]
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def test_space_handler_refs_point_at_delegated_funcs(src: str):
|
| 83 |
-
"""The SPACE keydown/keyup refs must be wired to the DELEGATED handlers
|
| 84 |
-
(startSpaceHoldPTT / stopSpaceHoldPTT), NOT the legacy per-press
|
| 85 |
-
cold-start startRecording/stopRecording. This is the core #53/#54 fix."""
|
| 86 |
-
assert "startRecordingRef.current = startSpaceHoldPTT;" in src, (
|
| 87 |
-
"SPACE keydown ref no longer points at the delegated handler β the "
|
| 88 |
-
"per-press getUserMedia cold start (head-clip #53 + latency #54) may "
|
| 89 |
-
"have been re-introduced."
|
| 90 |
-
)
|
| 91 |
-
assert "stopRecordingRef.current = stopSpaceHoldPTT;" in src
|
| 92 |
-
# The legacy refs must NOT be re-bound to the cold-start path.
|
| 93 |
-
assert "startRecordingRef.current = startRecording;" not in src
|
| 94 |
-
assert "stopRecordingRef.current = stopRecording;" not in src
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def test_delegated_start_calls_hook_beginPushToTalk(src: str):
|
| 98 |
-
"""startSpaceHoldPTT must engage the hook's warm-stream PTT, never spin
|
| 99 |
-
its own getUserMedia / MediaRecorder."""
|
| 100 |
-
fn = _slice(
|
| 101 |
-
src,
|
| 102 |
-
"async function startSpaceHoldPTT() {",
|
| 103 |
-
"async function stopSpaceHoldPTT() {",
|
| 104 |
-
)
|
| 105 |
-
assert "streamingVoice.beginPushToTalk()" in fn, (
|
| 106 |
-
"startSpaceHoldPTT does not delegate to the hook's beginPushToTalk"
|
| 107 |
-
)
|
| 108 |
-
# No independent capture device may be opened on the delegated path.
|
| 109 |
-
assert "getUserMedia" not in fn, "delegated start must not cold-start a mic"
|
| 110 |
-
assert "new MediaRecorder" not in fn, (
|
| 111 |
-
"delegated start must not create its own recorder (corrupt-webm trap)"
|
| 112 |
-
)
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
def test_delegated_stop_calls_hook_endPushToTalk_and_does_not_resubmit(src: str):
|
| 116 |
-
"""stopSpaceHoldPTT must finalize via the hook's endPushToTalk().
|
| 117 |
-
|
| 118 |
-
The hook ALREADY delivers a deliberate-hold transcript via
|
| 119 |
-
onFinalTranscript -> voiceSubmitRef -> send() (the exact downstream path
|
| 120 |
-
the old recorder.onstop success branch used). Re-feeding the returned
|
| 121 |
-
string into send() here would double-submit, so the delegated stop must
|
| 122 |
-
NOT call send()/voiceSubmitRef itself."""
|
| 123 |
-
fn = _slice(
|
| 124 |
-
src,
|
| 125 |
-
"async function stopSpaceHoldPTT() {",
|
| 126 |
-
" // #53/#54 β these refs now point at the DELEGATED SPACE-hold",
|
| 127 |
-
)
|
| 128 |
-
assert "await streamingVoice.endPushToTalk()" in fn
|
| 129 |
-
# No re-submission on the delegated stop path (hook already submitted).
|
| 130 |
-
# Check against CODE only β the comments legitimately name send() while
|
| 131 |
-
# explaining WHY we must not call it.
|
| 132 |
-
code = _strip_comments(fn)
|
| 133 |
-
assert "send(" not in code, (
|
| 134 |
-
"delegated stop re-submits the transcript β double-fire; the hook's "
|
| 135 |
-
"onFinalTranscript already routed it through send()"
|
| 136 |
-
)
|
| 137 |
-
assert "voiceSubmitRef" not in code
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
def test_sub_threshold_tap_is_clean_noop(src: str):
|
| 141 |
-
"""endPushToTalk() resolves null on a sub-threshold tap / empty capture.
|
| 142 |
-
The delegated stop must treat null as a clean no-op (no empty submit,
|
| 143 |
-
cosmetic state reset) β a non-negotiable semantic."""
|
| 144 |
-
fn = _slice(
|
| 145 |
-
src,
|
| 146 |
-
"async function stopSpaceHoldPTT() {",
|
| 147 |
-
" // #53/#54 β these refs now point at the DELEGATED SPACE-hold",
|
| 148 |
-
)
|
| 149 |
-
assert "text === null" in fn, (
|
| 150 |
-
"delegated stop does not branch on the null (tap) result β a "
|
| 151 |
-
"sub-threshold tap may submit empty / leave state stuck"
|
| 152 |
-
)
|
| 153 |
-
# On the null branch the cosmetic phase set on keydown is cleared.
|
| 154 |
-
assert "setVoicePhase(null)" in fn
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
def test_preserved_semantics_present_on_delegated_path(src: str):
|
| 158 |
-
"""Enumerate the non-negotiable semantics the original SPACE path had and
|
| 159 |
-
assert each survives on the delegated path."""
|
| 160 |
-
start = _slice(
|
| 161 |
-
src,
|
| 162 |
-
"async function startSpaceHoldPTT() {",
|
| 163 |
-
"async function stopSpaceHoldPTT() {",
|
| 164 |
-
)
|
| 165 |
-
stop = _slice(
|
| 166 |
-
src,
|
| 167 |
-
"async function stopSpaceHoldPTT() {",
|
| 168 |
-
" // #53/#54 β these refs now point at the DELEGATED SPACE-hold",
|
| 169 |
-
)
|
| 170 |
-
|
| 171 |
-
# interruptBotAudio("ptt-start") β silence prior bot TTS the instant the
|
| 172 |
-
# user starts talking (was startRecording's first action).
|
| 173 |
-
assert 'interruptBotAudio("ptt-start")' in start
|
| 174 |
-
|
| 175 |
-
# voicePhase "transcribing" UX while STT is in flight (was recorder.onstop).
|
| 176 |
-
assert 'setVoicePhase("transcribing")' in start
|
| 177 |
-
|
| 178 |
-
# busy is NOT force-set true before delegating β send() (invoked by the
|
| 179 |
-
# hook) owns busy and early-returns if busy is already true. Setting it
|
| 180 |
-
# here would silently drop the turn. Pin that this trap is avoided
|
| 181 |
-
# (CODE only; the comment legitimately names setBusy(true)).
|
| 182 |
-
assert "setBusy(true)" not in _strip_comments(start), (
|
| 183 |
-
"delegated start sets busy=true before send() runs β send() will "
|
| 184 |
-
"early-return on `busy` and the spoken turn is silently dropped"
|
| 185 |
-
)
|
| 186 |
-
|
| 187 |
-
# maybeResumeLive with the userPrefersLive gate (KI-028) survives.
|
| 188 |
-
assert "userPrefersLive" in stop and "live.setLive(true)" in stop
|
| 189 |
-
|
| 190 |
-
# mic_permission_denied banner surfacing is still reachable on the
|
| 191 |
-
# delegated start (defensive path) β matches the cold path's catch.
|
| 192 |
-
assert 'setVoiceErrorBanner({ type: "mic_permission_denied"' in start
|
| 193 |
-
|
| 194 |
-
# Re-entrancy guard equivalent to the old recordingRef/busyRef
|
| 195 |
-
# "don't start twice" intent.
|
| 196 |
-
assert "spaceHoldPttInFlightRef" in start
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
def test_keydown_keyup_guards_unchanged(src: str):
|
| 200 |
-
"""e.repeat / modifier guards, shouldSuppressSpace(), spaceHoldOwnsRecRef
|
| 201 |
-
ownership tracking, setSpaceHoldActive, and preventDefault must all remain
|
| 202 |
-
on the SPACE handlers (non-negotiable: a refactor must not nuke a
|
| 203 |
-
legitimately-typed space in the textarea)."""
|
| 204 |
-
handlers = _slice(
|
| 205 |
-
src,
|
| 206 |
-
"const onKeyDown = (e: KeyboardEvent) => {",
|
| 207 |
-
"window.addEventListener(\"keydown\", onKeyDown);",
|
| 208 |
-
)
|
| 209 |
-
# e.repeat + all modifier guards.
|
| 210 |
-
assert "if (e.repeat) return;" in handlers
|
| 211 |
-
assert "e.metaKey || e.ctrlKey || e.altKey || e.shiftKey" in handlers
|
| 212 |
-
# textarea guard still gates SPACE-hold.
|
| 213 |
-
assert "if (shouldSuppressSpace()) return;" in handlers
|
| 214 |
-
# ownership tracking + visual state both directions.
|
| 215 |
-
assert "spaceHoldOwnsRecRef.current = true;" in handlers
|
| 216 |
-
assert "spaceHoldOwnsRecRef.current = false;" in handlers
|
| 217 |
-
assert "setSpaceHoldActive(true);" in handlers
|
| 218 |
-
assert "setSpaceHoldActive(false);" in handlers
|
| 219 |
-
# the "did THIS keydown own the press" guard before stopping.
|
| 220 |
-
assert "if (!spaceHoldOwnsRecRef.current) return;" in handlers
|
| 221 |
-
# preventDefault on both keydown + keyup (stop a stray typed space).
|
| 222 |
-
assert handlers.count("e.preventDefault();") >= 2
|
| 223 |
-
# busy still blocks a fresh SPACE-hold start (turn in flight) and the
|
| 224 |
-
# delegated in-flight flag gates the stop call.
|
| 225 |
-
assert "if (recordingRef.current || busyRef.current) return;" in handlers
|
| 226 |
-
assert "spaceHoldPttInFlightRef.current) void sp();" in handlers
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
def test_onscreen_button_path_left_intact(src: str):
|
| 230 |
-
"""The on-screen Push-to-talk *button* uses a separate onClick handler
|
| 231 |
-
(startRecording/stopRecording) and does NOT share the SPACE code path, so
|
| 232 |
-
per the task it must be left untouched. Assert the legacy recorder
|
| 233 |
-
functions still exist and the button still uses them."""
|
| 234 |
-
assert "async function startRecording() {" in src
|
| 235 |
-
assert "function stopRecording() {" in src
|
| 236 |
-
# Button onClick still toggles the legacy recorder path.
|
| 237 |
-
assert re.search(
|
| 238 |
-
r"onClick=\{recording \? stopRecording : startRecording\}", src
|
| 239 |
-
), "on-screen Push-to-talk button onClick wiring changed unexpectedly"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|