""" Manual Test Runner using Async Browser Controller. Manual flow: human operator sends messages, AI evaluator scores bot responses. """ from __future__ import annotations import asyncio import json import re import time from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional from uuid import UUID, uuid4 from rich.console import Console from src.api.session_runner import session_event_bus from src.core.ai_client import get_ai_client_from_env from src.core.browser_controller_async import BrowserControllerAsync from src.core.turn_evaluator import TurnEvaluator from src.core.knowledge_boundary import fetch_duolly_boundary from src.core.knowledge_memory import knowledge_memory_service from src.core.response_usefulness import is_response_useful_for_continuation from src.core.source_evidence import SourceEvidenceFetcher, normalize_cited_links from src.db import BotRepository, SessionRepository, get_db from src.models import SessionStatus, TestResult from src.utils.env import env_bool, env_int console = Console() MANUAL_SCENARIO_ID = UUID("00000000-0000-0000-0000-000000000101") MANUAL_PERSONA_ID = UUID("00000000-0000-0000-0000-000000000102") URL_RE = re.compile(r"https?://[^\s)>\]]+", re.IGNORECASE) def _now_iso() -> str: return datetime.now().isoformat() class ManualTestRunnerAsync: """Async runner for manual interactive tests.""" def __init__(self): self.active_sessions: Dict[str, Dict[str, Any]] = {} self._evaluator: Optional[TurnEvaluator] = None # Live judging gating. LIVE_JUDGE_ENABLED (post-session branch) vince # se settato; altrimenti fallback retro-compat su ENABLE_TURN_EVALUATOR. import os as _os _live_raw = _os.getenv("LIVE_JUDGE_ENABLED") if _live_raw is not None: self._runtime_eval_enabled = _live_raw.strip().lower() in {"1", "true", "yes", "on"} else: self._runtime_eval_enabled = env_bool("ENABLE_TURN_EVALUATOR", True) self._screenshot_intervals: Dict[str, bool] = {} self._start_errors: Dict[str, str] = {} @property def evaluator(self) -> TurnEvaluator: if self._evaluator is None: from src.core.ai_client import get_evaluator_client_from_env self._evaluator = TurnEvaluator(get_evaluator_client_from_env()) return self._evaluator async def start(self, session_id: str, headless: bool = False) -> bool: """Start a manual test session with async browser.""" if session_id in self.active_sessions: self._start_errors[session_id] = "Manual session already running." return False db = get_db() with db.get_session() as session: repo = SessionRepository(session) bot_repo = BotRepository(session) test_session = repo.get_session(UUID(session_id)) if not test_session: self._start_errors[session_id] = f"Session {session_id} not found" console.print(f"[red]Session {session_id} not found[/red]") return False bot = bot_repo.get_by_id(test_session.bot_id) if not bot: self._start_errors[session_id] = "AI Agent not found" console.print("[red]Bot not found[/red]") return False output_dir = Path("./output") / session_id output_dir.mkdir(parents=True, exist_ok=True) browser = BrowserControllerAsync( selectors=bot.selectors.model_dump(), output_dir=str(output_dir), headless=headless, ) if not await browser.start(str(bot.url)): browser_err = str(getattr(browser, "last_error", "") or "").strip() self._start_errors[session_id] = ( f"Failed to start browser: {browser_err}" if browser_err else "Failed to start browser" ) console.print("[red]Failed to start browser[/red]") return False auto_click_new_chat = bool(getattr(bot, "auto_click_new_chat", False)) if auto_click_new_chat: clicked_new_chat = await browser.click_new_chat() self._emit( session_id, { "type": "log", "level": "info" if clicked_new_chat else "warning", "message": ( "Auto New Chat triggered from AI Agent configuration." if clicked_new_chat else "Auto New Chat enabled, but button was not found." ), }, ) if clicked_new_chat: await asyncio.sleep(0.5) initial_screenshot = await browser.capture_screenshot("manual_initial") knowledge_boundary = self._load_knowledge_boundary(bot) self.active_sessions[session_id] = { "browser": browser, "session": test_session, "bot": bot, "output_dir": output_dir, "interactions": [], "turns": [], "metrics": [], "start_time": datetime.now(), "stop_requested": False, "processing": False, "input_enabled": True, "messages_sent": 0, "last_message_count": 0, "knowledge_boundary": knowledge_boundary, "screenshot_urls": [initial_screenshot] if initial_screenshot else [], "auto_click_new_chat": auto_click_new_chat, } asyncio.create_task(self._screenshot_loop(session_id)) self._emit( session_id, { "type": "status", "status": "running", "message": "Manual test session started", "headless": bool(headless), }, ) self._emit( session_id, { "type": "log", "level": "success", "message": "Operator mode active: send messages from the input bar.", }, ) if not self._runtime_eval_enabled: self._emit( session_id, { "type": "log", "level": "info", "message": "TurnEvaluator disabled: responses are checked only for conversational usefulness.", }, ) if initial_screenshot: self._emit(session_id, {"type": "screenshot", "path": initial_screenshot}) self._set_manual_input(session_id, True, "Ready to send first message.") self._start_errors.pop(session_id, None) console.print(f"[green]Manual test started: {session_id}[/green]") return True def get_start_error(self, session_id: str) -> str: return str(self._start_errors.get(session_id, "") or "").strip() async def stop(self, session_id: str) -> bool: """Stop manual test session and persist report-friendly results.""" session_data = self.active_sessions.get(session_id) if not session_data: return False session_data["stop_requested"] = True self._set_manual_input(session_id, False, "Stopping session...") if session_id in self._screenshot_intervals: self._screenshot_intervals[session_id] = False browser = session_data.get("browser") final_screenshot = None if browser: final_screenshot = await browser.capture_screenshot("manual_final") if final_screenshot: session_data["screenshot_urls"].append(final_screenshot) persistence = await self._persist_session_result(session_id) final_status = persistence.get("status", SessionStatus.MANUAL_COMPLETED.value) final_message = persistence.get("message", "Manual session completed") if browser: await browser.cleanup() self._emit( session_id, { "type": "status", "status": final_status, "message": final_message, "interactions_count": len(session_data.get("interactions", [])), "turns_count": len(session_data.get("turns", [])), }, ) del self.active_sessions[session_id] console.print(f"[green]Manual test stopped: {session_id} ({final_status})[/green]") return True async def trigger_new_chat(self, session_id: str) -> Dict[str, Any]: """Trigger a manual new-chat reset in the active browser.""" session_data = self.active_sessions.get(session_id) if not session_data: return {"ok": False, "error": "Manual session is not running"} if session_data.get("stop_requested"): return {"ok": False, "error": "Session is stopping"} if session_data.get("processing"): return {"ok": False, "error": "Wait for current evaluation to finish"} browser: Optional[BrowserControllerAsync] = session_data.get("browser") if not browser: return {"ok": False, "error": "Browser is not available"} self._set_manual_input(session_id, False, "Opening a new chat...") self._emit( session_id, { "type": "phase", "phase": "act", "message": "Triggering New Chat in browser...", }, ) clicked = await browser.click_new_chat() if not clicked: err = ( str(getattr(browser, "last_error", "") or "").strip() or "New chat button not found" ) self._emit( session_id, {"type": "error", "message": f"Failed to trigger New Chat: {err}"} ) self._set_manual_input(session_id, True, "New Chat failed. You can continue typing.") return {"ok": False, "error": err} # Reset interaction context to avoid cross-chat contamination in evaluator history. session_data["interactions"] = [] session_data["last_message_count"] = 0 await asyncio.sleep(0.4) shot = await browser.capture_screenshot("manual_new_chat") if shot: session_data["screenshot_urls"].append(shot) self._emit(session_id, {"type": "screenshot", "path": shot}) self._emit( session_id, { "type": "log", "level": "success", "message": "New Chat triggered. Conversation context reset for next turn.", }, ) self._set_manual_input(session_id, True, "New Chat ready. Send your next message.") return {"ok": True} async def send_user_message(self, session_id: str, content: str) -> Dict[str, Any]: """Send operator message, wait for bot reply, evaluate, then unlock input.""" session_data = self.active_sessions.get(session_id) if not session_data: return {"ok": False, "error": "Manual session is not running"} text = str(content or "").strip() if not text: return {"ok": False, "error": "Message cannot be empty"} if session_data.get("stop_requested"): return {"ok": False, "error": "Session is stopping"} if session_data.get("processing"): return {"ok": False, "error": "Wait for current evaluation to finish"} browser: Optional[BrowserControllerAsync] = session_data.get("browser") if not browser: return {"ok": False, "error": "Browser is not available"} session_data["processing"] = True self._set_manual_input(session_id, False, "Waiting for bot response and evaluation...") turn_number = len(session_data.get("turns", [])) + 1 try: self._emit( session_id, { "type": "phase", "phase": "act", "message": "Sending operator message to AI Agent...", "turn": turn_number, }, ) snapshot_timeout = max(env_int("MANUAL_MESSAGES_SNAPSHOT_TIMEOUT", 6), 2) try: before_messages = await asyncio.wait_for( browser.get_chat_messages(), timeout=float(snapshot_timeout) ) except Exception: before_messages = [] before_count = len(before_messages or []) sent_ok = await browser.send_message(text, human_like=True) if not sent_ok: browser_err = str(getattr(browser, "last_error", "") or "").strip() msg = "Failed to send message in browser" if browser_err: msg = f"{msg}: {browser_err}" self._emit(session_id, {"type": "error", "message": msg}) return {"ok": False, "error": msg} session_data["messages_sent"] = int(session_data.get("messages_sent", 0)) + 1 self._append_interaction(session_data, "user", text, emit_chat=True) self._emit( session_id, { "type": "phase", "phase": "wait", "message": "Waiting for AI Agent response...", "turn": turn_number, "timeout": env_int("RESPONSE_TIMEOUT", 30), }, ) wait_started = time.monotonic() waited_candidate = await browser.wait_for_bot_response( timeout=env_int("RESPONSE_TIMEOUT", 30), stop_requested=lambda: bool(session_data.get("stop_requested")), ) response_time_ms = int((time.monotonic() - wait_started) * 1000) try: after_messages = await asyncio.wait_for( browser.get_chat_messages(), timeout=float(snapshot_timeout) ) except Exception: after_messages = [] session_data["last_message_count"] = len(after_messages or []) bot_response = self._select_bot_response( after_messages or [], operator_message=text, fallback_candidate=waited_candidate, previous_count=before_count, ) if not bot_response: self._emit( session_id, { "type": "error", "message": "No new bot response detected before timeout", }, ) return {"ok": False, "error": "No bot response detected"} self._emit( session_id, { "type": "phase", "phase": "comprehend", "message": "Analyzing and evaluating bot response...", "turn": turn_number, }, ) self._emit( session_id, { "type": "ai_reasoning", "reasoning": "Processing bot response, extracting evidence, and computing AIS attribution.", "decision": "evaluate_response", "confidence": 0.96, }, ) turn_payload = await self._evaluate_and_store_turn( session_id=session_id, user_message=text, bot_response=bot_response, response_time_ms=response_time_ms, ) self._emit( session_id, { "type": "status", "status": "running", "message": "Turn evaluated. You can send the next message.", "turn": turn_number, }, ) return {"ok": True, "turn": turn_payload.get("turn"), "message": "Turn completed"} except Exception as exc: error_msg = str(exc)[:300] self._emit(session_id, {"type": "error", "message": error_msg}) return {"ok": False, "error": error_msg} finally: session_data["processing"] = False if not session_data.get("stop_requested"): self._set_manual_input(session_id, True, "Evaluation completed. Send next message.") async def record_interaction( self, session_id: str, interaction_type: str, content: str ) -> bool: """Legacy compatibility endpoint: records interaction without browser send.""" session_data = self.active_sessions.get(session_id) if not session_data: return False text = str(content or "").strip() if not text: return False role = "bot" if str(interaction_type).strip().lower() == "bot" else "user" self._append_interaction(session_data, role, text, emit_chat=True) if role == "bot": last_user = "" for item in reversed(session_data.get("interactions", [])): if item.get("type") == "user": last_user = str(item.get("content") or "") break if last_user: await self._evaluate_and_store_turn( session_id=session_id, user_message=last_user, bot_response=text, response_time_ms=None, ) return True async def get_messages(self, session_id: str) -> List[Dict[str, Any]]: """Get current chat messages from browser (legacy polling support).""" session_data = self.active_sessions.get(session_id) if not session_data: return [] browser: Optional[BrowserControllerAsync] = session_data.get("browser") if not browser: return [] try: messages = await browser.get_chat_messages() return messages if messages else [] except Exception as exc: console.print(f"[yellow]Error getting messages: {exc}[/yellow]") return [] async def capture_screenshot(self, session_id: str) -> Optional[str]: """Capture screenshot of browser.""" session_data = self.active_sessions.get(session_id) if not session_data: return None browser: Optional[BrowserControllerAsync] = session_data.get("browser") if not browser: return None try: return await browser.capture_screenshot("manual_test") except Exception as exc: console.print(f"[yellow]Screenshot error: {exc}[/yellow]") return None async def _evaluate_and_store_turn( self, session_id: str, user_message: str, bot_response: str, response_time_ms: Optional[int], ) -> Dict[str, Any]: session_data = self.active_sessions[session_id] turn_number = len(session_data.get("turns", [])) + 1 browser: Optional[BrowserControllerAsync] = session_data.get("browser") sidebar_links: List[Dict[str, str]] = [] if browser: try: sidebar_links = await browser.extract_sidebar_source_links() except Exception: sidebar_links = [] source_evidence = self._collect_source_evidence(bot_response, sidebar_links) factuality_sources = self._build_factuality_sources(session_data, source_evidence) knowledge_boundary = session_data.get("knowledge_boundary") bot = session_data.get("bot") memory_hits: List[Dict[str, Any]] = [] workspace_id = getattr(session_data.get("session"), "workspace_id", None) if bot and workspace_id: try: memory_hits = knowledge_memory_service.retrieve( workspace_id=workspace_id, bot_id=bot.id, query=user_message, top_k=max(env_int("KNOWLEDGE_RETRIEVE_TOP_K", 5), 1), source_scope="active", ) except Exception: memory_hits = [] self._emit( session_id, { "type": "log", "level": "info", "message": ( f"Factuality link candidates detected: {len(sidebar_links)}" if sidebar_links else "Factuality link candidates detected: 0 (no cited links found in response/aside)" ), }, ) evaluation_dict: Optional[Dict[str, Any]] = None if self._runtime_eval_enabled: try: boundary_text = ( getattr(knowledge_boundary, "content_raw", "") if knowledge_boundary else "" ) or "" fallbacks = list(getattr(bot, "deterministic_fallbacks", None) or []) if bot else [] evaluation = self.evaluator.evaluate( user_query=user_message, bot_response=bot_response, agent_description=(bot.description or "") if bot else "", knowledge_boundary_text=boundary_text, deterministic_fallbacks=fallbacks, retrieved_sources=factuality_sources, subscenario_goal=None, ) evaluation_dict = evaluation.to_dict() self._emit( session_id, { "type": "turn_evaluation", "evaluation": evaluation_dict, "turn": turn_number, }, ) except Exception as exc: self._emit( session_id, { "type": "log", "level": "warning", "message": f"TurnEvaluator fallback: {str(exc)[:220]}", }, ) turn_screenshot = None if browser: turn_screenshot = await browser.capture_screenshot(f"manual_turn_{turn_number}") if turn_screenshot: session_data["screenshot_urls"].append(turn_screenshot) self._emit( session_id, {"type": "screenshot", "path": turn_screenshot, "turn": turn_number} ) turn_payload: Dict[str, Any] = { "turn": turn_number, "scenario_id": "manual_scenario", "scenario_name": "Manual Conversation", "step_id": f"manual_turn_{turn_number}", "user_message": user_message, "bot_response": bot_response, "response_time_ms": response_time_ms, "timestamp": _now_iso(), "screenshot": turn_screenshot, "source_evidence": source_evidence, "memory_hits": memory_hits, "turn_evaluation": evaluation_dict, "correctness_label": (evaluation_dict or {}).get("ais_label"), "intent_label": (evaluation_dict or {}).get("intent_label"), "success": self._is_turn_success(evaluation_dict, bot_response), } self._append_interaction(session_data, "bot", bot_response, emit_chat=True) session_data["turns"].append(turn_payload) session_data["metrics"].append( { "turn": turn_number, "user_message": user_message, "bot_response": bot_response, "evaluation": evaluation_dict or {}, "timestamp": _now_iso(), } ) self._emit( session_id, { "type": "bot_response_received", "response_length": len(bot_response), "response_preview": bot_response[:200], "turn": turn_number, }, ) return turn_payload async def _persist_session_result(self, session_id: str) -> Dict[str, Any]: """Persist manual run as a regular TestResult so session report works unchanged.""" session_data = self.active_sessions.get(session_id) if not session_data: return {"status": SessionStatus.MANUAL_COMPLETED.value, "message": "Session not active"} turns: List[Dict[str, Any]] = list(session_data.get("turns", [])) start_time: datetime = session_data.get("start_time") or datetime.now() completed_at = datetime.now() duration_ms = int(max((completed_at - start_time).total_seconds(), 0) * 1000) if not turns: db = get_db() with db.get_session() as db_session: repo = SessionRepository(db_session) repo.update_session( UUID(session_id), { "status": SessionStatus.CANCELLED.value, "completed_at": completed_at, "total_tests": 1, "passed": 0, "failed": 0, "messages_sent": int(session_data.get("messages_sent", 0)), "avg_response_time_ms": None, "rag_faithfulness_avg": None, "tone_match_avg": None, "error_message": "Manual session stopped before first complete turn.", }, ) db_session.commit() return { "status": SessionStatus.CANCELLED.value, "message": "Manual session cancelled: no evaluated turn recorded.", } # AIS-aware aggregation. A turn is considered "good" if the AIS # label is attributable, partial, or appropriate_*. We delegate the # statistical verdict to compute_session_verdict but for the local # short narrative we use simple counts. avg_response_ms = None response_times = [ t.get("response_time_ms") for t in turns if isinstance(t.get("response_time_ms"), int) ] if response_times: avg_response_ms = int(sum(response_times) / len(response_times)) avg_factuality = None # legacy field, kept for schema compat passed_turns = sum(1 for t in turns if t.get("success") is True) failed_turns = sum(1 for t in turns if t.get("success") is False) if turns and failed_turns == 0 and passed_turns < len(turns): failed_turns = len(turns) - passed_turns boundary_violations_total = 0 # superseded by AIS labels if self._runtime_eval_enabled: scenario_pass = bool(turns) and passed_turns == len(turns) scenario_reason = ( "All operator turns received an acceptable AIS label." if scenario_pass else ( "No evaluated bot responses captured." if not turns else "One or more turns received an unacceptable AIS label." ) ) else: scenario_pass = bool(turns) and passed_turns == len(turns) scenario_reason = ( "All operator turns produced useful responses for conversation continuation." if scenario_pass else "One or more turns produced low-value responses for continuation." ) outcome_type = "in_scope_pass" if scenario_pass else "in_scope_fail" status_value = ( SessionStatus.COMPLETED_IN_SCOPE_PASS.value if scenario_pass else SessionStatus.COMPLETED_IN_SCOPE_FAIL.value ) result_status = "passed" if scenario_pass else ("failed" if turns else "error") scenario_turns = [] for turn in turns: evaluation = turn.get("turn_evaluation") or {} scenario_turns.append( { "turn": turn.get("turn"), "user_message": turn.get("user_message"), "bot_response": turn.get("bot_response"), "timestamp": turn.get("timestamp"), "screenshot": turn.get("screenshot"), "response_time_ms": turn.get("response_time_ms"), "source_evidence": turn.get("source_evidence") or [], "memory_hits": turn.get("memory_hits") or [], "turn_evaluation": evaluation, "correctness_label": evaluation.get("ais_label"), "intent_label": evaluation.get("intent_label"), "success": bool(turn.get("success")), } ) scenario_results = { "manual_scenario": { "name": "Manual Conversation", "turns": scenario_turns, "status": "completed" if turns else "empty", "completed": bool(scenario_pass), "expected_scope": "in_scope", "outcome_type": outcome_type, "completion_reason": scenario_reason, "fallback_detected": False, "fallback_required": False, "boundary_violations_count": boundary_violations_total, "attempts": 1, } } steps_results = [] for turn in turns: evaluation = turn.get("turn_evaluation") if isinstance(turn.get("turn_evaluation"), dict) else {} steps_results.append( { "step_id": turn.get("step_id") or f"manual_turn_{turn.get('turn')}", "expected_intent": "Manual Conversation", "content": turn.get("user_message"), "bot_response": turn.get("bot_response"), "success": bool(turn.get("success")), "response_time_ms": turn.get("response_time_ms"), "screenshot": turn.get("screenshot"), "source_evidence": turn.get("source_evidence") or [], "memory_hits": turn.get("memory_hits") or [], "turn_evaluation": evaluation, "ais_label": evaluation.get("ais_label"), "intent_label": evaluation.get("intent_label"), } ) conversation_log = json.dumps(scenario_turns, ensure_ascii=False, default=str) screenshot_urls = [] for shot in session_data.get("screenshot_urls", []): if shot and shot not in screenshot_urls: screenshot_urls.append(shot) db = get_db() with db.get_session() as db_session: repo = SessionRepository(db_session) session_uuid = UUID(session_id) existing = repo.get_result_by_session_and_scenario( session_uuid, MANUAL_SCENARIO_ID, MANUAL_PERSONA_ID ) payload = { "workspace_id": getattr(session_data.get("session"), "workspace_id", None), "session_id": session_uuid, "scenario_id": MANUAL_SCENARIO_ID, "persona_id": MANUAL_PERSONA_ID, "steps_results": steps_results, "status": result_status, "total_steps": len(steps_results), "passed_steps": passed_turns, "failed_steps": max(failed_turns, 0), "total_duration_ms": duration_ms, "avg_response_time_ms": avg_response_ms, "rag_faithfulness_avg": (avg_factuality / 3.0) if avg_factuality else None, "tone_match_avg": None, "error_message": None if turns else "No evaluated turns recorded", "failure_reason": None if scenario_pass else scenario_reason, "screenshot_urls": screenshot_urls, "conversation_log": conversation_log, "scenario_results": scenario_results, "started_at": start_time, "completed_at": completed_at, } if existing: repo.update_result(existing.id, payload) else: repo.add_result(TestResult(**payload)) # Auto-trigger del post-session AIS judge: marca pending qui, # schedula il job in background subito dopo il commit. Idempotente: # il job skippa turni già valutati salvo force=True. current_judge_status = getattr( repo.get_session(session_uuid), "judge_status", "idle" ) should_trigger_judge = ( not self._runtime_eval_enabled and current_judge_status not in {"running", "pending"} ) session_updates: Dict[str, Any] = { "status": status_value, "completed_at": completed_at, "total_tests": 1, "passed": 1 if scenario_pass else 0, "failed": 0 if scenario_pass else 1, "messages_sent": int(session_data.get("messages_sent", 0)), "avg_response_time_ms": avg_response_ms, "rag_faithfulness_avg": (avg_factuality / 3.0) if avg_factuality else None, "tone_match_avg": None, "error_message": None, } if should_trigger_judge: session_updates["judge_status"] = "pending" session_updates["judge_error"] = None repo.update_session(session_uuid, session_updates) db_session.commit() if should_trigger_judge: # Fire-and-forget: il judge gira lato server, anche se il client # si disconnette. Usiamo asyncio.to_thread perché il job è # sincrono e fa IO bloccante (DB + LLM). from src.api.routes.sessions import _run_session_judge_sync async def _trigger_judge_bg() -> None: try: await asyncio.to_thread( _run_session_judge_sync, session_uuid, force=False, triggered_by="auto", ) except Exception as exc: # pragma: no cover console.print(f"[yellow]Post-session judge failed: {exc}[/yellow]") asyncio.create_task(_trigger_judge_bg()) human_status = status_value return { "status": human_status, "message": "Manual test completed and saved.", } async def _screenshot_loop(self, session_id: str) -> None: """Auto-capture screenshots for live preview while running.""" self._screenshot_intervals[session_id] = True interval_ms = max(env_int("LIVE_SCREENSHOT_INTERVAL_MS", 1000), 500) interval = interval_ms / 1000.0 while self._screenshot_intervals.get(session_id, False): session_data = self.active_sessions.get(session_id) if not session_data or session_data.get("stop_requested"): break try: path = await self.capture_screenshot(session_id) if path: self._emit(session_id, {"type": "screenshot", "path": path, "live": True}) except Exception as exc: console.print(f"[dim]Screenshot loop error: {exc}[/dim]") await asyncio.sleep(interval) def _build_conversation_history(self, session_data: Dict[str, Any]) -> List[Dict[str, str]]: history = [] for item in session_data.get("interactions", [])[-10:]: role = "assistant" if item.get("type") == "bot" else "user" history.append({"sender": role, "text": str(item.get("content") or "")}) return history def _collect_source_evidence( self, bot_response: str, sidebar_links: Optional[List[Dict[str, str]]] = None, ) -> List[Dict[str, Any]]: urls = [m.group(0) for m in URL_RE.finditer(str(bot_response or ""))] sidebar_urls = [] for item in sidebar_links or []: if not isinstance(item, dict): continue href = str(item.get("url") or "").strip() if href: sidebar_urls.append(href) all_urls = list(dict.fromkeys(urls + sidebar_urls)) if not all_urls: return [] titled_entries = [] sidebar_lookup = { str(item.get("url") or "").strip(): str(item.get("title") or "").strip() for item in (sidebar_links or []) if isinstance(item, dict) } for url in all_urls: titled_entries.append({"url": url, "title": sidebar_lookup.get(url) or url}) link_entries = normalize_cited_links(titled_entries) if not link_entries: return [] fetcher = SourceEvidenceFetcher( max_sources_per_turn=max(env_int("SOURCE_EVIDENCE_MAX_PER_TURN", 3), 1), per_source_timeout_seconds=float(max(env_int("SOURCE_EVIDENCE_TIMEOUT_SECONDS", 4), 1)), total_budget_seconds=float(max(env_int("SOURCE_EVIDENCE_TOTAL_BUDGET_SECONDS", 12), 2)), max_excerpt_chars=max(env_int("SOURCE_EVIDENCE_MAX_CHARS", 400), 150), ) return fetcher.collect_from_links(link_entries) def _build_factuality_sources( self, session_data: Dict[str, Any], source_evidence: List[Dict[str, Any]], ) -> List[Dict[str, Any]]: sources: List[Dict[str, Any]] = [] kb = session_data.get("knowledge_boundary") if kb: try: raw = (getattr(kb, "content_raw", "") or "").strip() if raw: sources.append( { "source_id": "KB-1", "source_type": "knowledge_boundary", "title": "Knowledge boundary", "url": getattr(kb, "source_url", None), "content": raw[:4000], } ) except Exception: pass for idx, item in enumerate(source_evidence or [], start=1): excerpt = str(item.get("excerpt") or "").strip() status = str(item.get("status") or "unknown") if not excerpt: excerpt = ( f"[SOURCE_UNAVAILABLE] status={status} error={item.get('error') or ''}".strip() ) sources.append( { "source_id": f"C{idx}", "source_type": "cited_source", "title": item.get("title") or item.get("url") or f"Source {idx}", "url": item.get("url"), "fetch_status": status, "content": excerpt[:1800], } ) return sources def _load_knowledge_boundary(self, bot: Any) -> Any: boundary_url = getattr(bot, "knowledge_boundary_url", None) if not boundary_url: return None try: return fetch_duolly_boundary(str(boundary_url)) except Exception as exc: console.print(f"[yellow]Knowledge boundary load failed: {exc}[/yellow]") return None def _append_interaction( self, session_data: Dict[str, Any], role: str, content: str, emit_chat: bool = False, ) -> None: item = { "id": str(uuid4()), "type": role, "content": content, "timestamp": _now_iso(), } session_data.setdefault("interactions", []).append(item) if emit_chat: self._emit( str(session_data["session"].id), {"type": "chat", "sender": role, "text": content, "timestamp": item["timestamp"]}, ) @staticmethod def _select_bot_response( messages: List[Dict[str, Any]], operator_message: str, fallback_candidate: Optional[str], previous_count: int, ) -> Optional[str]: if messages and len(messages) > previous_count: operator_text = str(operator_message or "").strip().lower() for msg in reversed(messages): text = str(msg.get("text") or "").strip() if not text: continue sender = str(msg.get("sender") or "").strip().lower() if sender == "user" and text.lower() == operator_text: continue if sender in {"bot", "assistant", "unknown", ""}: return text candidate = str(fallback_candidate or "").strip() if candidate: return candidate return None def _is_turn_success(self, evaluation: Optional[Dict[str, Any]], bot_response: str) -> bool: """A turn is "successful" if AIS gives it any acceptable label. Acceptable: attributable, partial, appropriate_refusal, appropriate_clarification. Failure: not_attributable, inappropriate_fallback. When the evaluator has not run, fall back to the conversational-usefulness heuristic so old behavior is preserved for un-evaluated turns. """ if self._runtime_eval_enabled and isinstance(evaluation, dict): label = str(evaluation.get("ais_label") or "").lower() return label in { "attributable", "partial", "appropriate_refusal", "appropriate_clarification", } return is_response_useful_for_continuation(bot_response) def _set_manual_input(self, session_id: str, enabled: bool, message: str) -> None: session_data = self.active_sessions.get(session_id) if session_data is not None: session_data["input_enabled"] = bool(enabled) self._emit( session_id, { "type": "manual_input", "enabled": bool(enabled), "message": message, }, ) def _emit(self, session_id: str, event: Dict[str, Any]) -> None: try: payload = dict(event or {}) payload.setdefault("ts", int(time.time() * 1000)) payload.setdefault("session_id", str(session_id)) session_event_bus.publish(str(session_id), payload) except Exception as exc: console.print(f"[yellow]Emit error: {exc}[/yellow]") # Global instance manual_test_runner_async = ManualTestRunnerAsync()