Spaces:
Runtime error
Runtime error
Download src/core/test_engine.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 148 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/test_engine.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/core/test_engine.py
-
curl -L -o test_engine.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/test_engine.py
148 kB
"""
Test Engine V3 - Realistic conversation flow, no contamination.
"""
import json
import random
import time
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from rich.console import Console
from rich.panel import Panel
from ..models import ActionType, Bot, Persona, Scenario, TestResult, TestSession
from ..utils.env import env_float, env_int
from ..utils.logging import get_logger
from .ai_client import AIClient
from .browser_controller import BrowserController
from .knowledge_boundary import fetch_duolly_boundary
from .knowledge_memory import knowledge_memory_service
from .question_planner import QuestionPlanner
from .rag_evaluator import RAGEvaluator
from .response_usefulness import is_response_useful_for_continuation
from .source_evidence import SourceEvidenceFetcher
from .tone_evaluator import ToneEvaluator
from .turn_evaluator import TurnEvaluator
from .turn_watchdog import TurnWatchdog
logger = get_logger(__name__)
console = Console()
@dataclass
class BotResponse:
"""Risposta del bot con contenuti testuali e non testuali."""
text: str = ""
has_map: bool = False
has_image: bool = False
has_link: bool = False
has_button: bool = False
has_list: bool = False
has_table: bool = False
links: List[Any] = field(default_factory=list)
buttons: List[str] = field(default_factory=list)
raw_html: str = ""
def has_rich_content(self) -> bool:
"""Verifica se la risposta contiene contenuti non testuali."""
return (
self.has_map
or self.has_image
or self.has_link
or self.has_button
or self.has_list
or self.has_table
)
def to_text(self) -> str:
"""Restituisce il testo completo per backward compatibility."""
parts = [self.text]
if self.has_map:
parts.append("[Mappa fornita]")
if self.has_image:
parts.append("[Immagine fornita]")
if self.links:
rendered_links = []
for link in self.links:
if isinstance(link, dict):
title = str(link.get("title") or "").strip()
url = str(link.get("url") or "").strip()
rendered_links.append(f"{title} ({url})" if title else url)
else:
rendered_links.append(str(link))
parts.append(f"[Links: {', '.join(rendered_links)}]")
if self.buttons:
parts.append(f"[Bottoni: {', '.join(self.buttons)}]")
return " ".join(parts)
class TestEngine:
"""Test engine with realistic conversation flow."""
def __init__(
self,
ai_client: AIClient,
rag_evaluator: RAGEvaluator,
tone_evaluator: ToneEvaluator,
turn_evaluator: Optional[TurnEvaluator] = None,
output_dir: str = "./output",
event_handler: Optional[Callable[[Dict[str, Any]], None]] = None,
stop_requested: Optional[Callable[[], bool]] = None,
save_callback: Optional[Callable[[TestResult], None]] = None,
max_messages: Optional[int] = None,
persona_system_prompt_override: Optional[str] = None,
):
self.ai_client = ai_client
self.rag_eval = rag_evaluator
self.tone_eval = tone_evaluator
self.turn_eval = turn_evaluator
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.event_handler = event_handler
self.stop_requested = stop_requested
self.save_callback = save_callback # Callback to save intermediate results
self.max_messages = max_messages # Maximum messages allowed for this session
self.persona_system_prompt_override = (
str(persona_system_prompt_override).strip() if persona_system_prompt_override else None
)
self._knowledge_boundary = None
source_timeout_seconds = max(
env_float("SOURCE_EVIDENCE_TIMEOUT_SECONDS", 8.0),
8.0,
)
source_total_budget_seconds = max(
env_float("SOURCE_EVIDENCE_TOTAL_BUDGET_SECONDS", 24.0),
source_timeout_seconds * 2,
)
self._source_fetcher = SourceEvidenceFetcher(
max_sources_per_turn=max(env_int("SOURCE_EVIDENCE_MAX_PER_TURN", 3), 0),
per_source_timeout_seconds=source_timeout_seconds,
total_budget_seconds=source_total_budget_seconds,
max_excerpt_chars=max(env_int("SOURCE_EVIDENCE_MAX_CHARS", 1800), 400),
)
self.browser: Optional[BrowserController] = None
self.current_session: Optional[TestSession] = None
self.interaction_history: List[Dict[str, Any]] = []
self.conversation_log: List[Dict[str, Any]] = []
self.last_bot_message: Optional[str] = None
self.scenario_results: Dict[str, Any] = {}
self._current_result: Optional[TestResult] = None # Track current result for saving
self._followup_topics: Dict[str, List[str]] = (
{}
) # Track topics already followed up per scenario
self._max_followups_per_step = 1 # Max 1 follow-up per step to stay on track
self.messages_sent_count = 0
self._limit_stop_emitted = False
self._reserved_messages_for_future_scenarios = 0
self._agent_deterministic_fallbacks: List[str] = []
self.question_planner = QuestionPlanner(ai_client=ai_client)
self._session_min_turns = 1
# 8 (era 5): un singolo retrieval su query brevi e generiche tornava
# solo 5 chunk, alcuni dei quali "boilerplate" del portale (header,
# menu di navigazione). Con 8 abbiamo abbastanza copertura per i
# claim multi-fatto (es. lista di monumenti con date e nomi).
self._memory_top_k = max(env_int("KNOWLEDGE_RETRIEVE_TOP_K", 8), 1)
def _emit(self, event: Dict[str, Any]) -> None:
if self.event_handler:
self.event_handler(event)
def _emit_log(
self,
level: str,
category: str,
message: str,
**meta: Any,
) -> None:
"""Emit a structured log event with category for easier debugging.
Categories in use: browser | api | parse | engine | retrieval | evaluator.
"""
payload: Dict[str, Any] = {
"type": "log",
"level": level,
"category": category,
"message": message,
}
if meta:
payload.update(meta)
self._emit(payload)
def _arm_turn_watchdog(self, scenario_id: str, step_id: Optional[str]) -> None:
"""Start a one-shot timer that flags the turn as aborted on expiry.
Disabled when WATCHDOG_TURN_TIMEOUT_SEC<=0. Disarm via
_disarm_turn_watchdog() to cancel before the timer fires.
"""
# Cancel any leftover watchdog from a prior turn (defensive — shouldn't
# happen if the caller pairs arm/disarm correctly).
prev = getattr(self, "_active_watchdog", None)
if prev is not None:
try:
prev.__exit__(None, None, None)
except Exception:
pass
self._turn_aborted = False
timeout = env_int("WATCHDOG_TURN_TIMEOUT_SEC", 180)
def _on_timeout() -> None:
self._turn_aborted = True
try:
self._emit_log(
"warning",
"watchdog",
f"Turn watchdog fired after {timeout}s",
scenario_id=scenario_id,
step_id=step_id,
)
except Exception:
pass
try:
logger.warning(
"watchdog_fired",
extra={
"scenario_id": scenario_id,
"step_id": step_id,
"timeout_sec": timeout,
},
)
except Exception:
pass
wd = TurnWatchdog(timeout, _on_timeout)
wd.__enter__()
self._active_watchdog = wd
def _disarm_turn_watchdog(self) -> bool:
"""Cancel the active watchdog and return whether it had fired.
Returns True if the turn was aborted by the watchdog (caller should
downgrade the turn outcome to a transient failure).
"""
wd = getattr(self, "_active_watchdog", None)
if wd is not None:
try:
wd.__exit__(None, None, None)
except Exception:
pass
self._active_watchdog = None
aborted = bool(getattr(self, "_turn_aborted", False))
self._turn_aborted = False
return aborted
def _trim_screenshot_urls(self, result: "TestResult") -> None:
"""Keep only the most recent N screenshot URLs in memory.
On 100+ turn sessions the list would otherwise grow unbounded and
bloat both the in-memory result and the DB blob on each save. The
underlying files on Supabase Storage are not deleted — only the
in-memory pointer list is trimmed. Default 200, 0 disables.
"""
keep_last = max(0, env_int("SCREENSHOT_MEMORY_KEEP_LAST", 200))
if keep_last <= 0:
return
urls = getattr(result, "screenshot_urls", None)
if not urls:
return
if len(urls) > keep_last:
del urls[: len(urls) - keep_last]
def _is_stop_requested(self) -> bool:
if not self.stop_requested:
return False
try:
return bool(self.stop_requested())
except Exception:
return False
def _has_reached_message_limit(self) -> bool:
return bool(self.max_messages and self.messages_sent_count >= self.max_messages)
def _remaining_message_budget(self) -> Optional[int]:
if not self.max_messages:
return None
return max(self.max_messages - self.messages_sent_count, 0)
def _should_rotate_to_next_scenario(
self,
*,
remaining_scenarios_to_cover: int,
current_scenario_covered: bool,
) -> bool:
"""Preserve budget so all selected scenarios are at least exercised."""
budget = self._remaining_message_budget()
if budget is None:
return False
if remaining_scenarios_to_cover <= 0:
return False
# Once current scenario has at least one turn, keep at least one message
# for each remaining scenario.
return current_scenario_covered and budget <= remaining_scenarios_to_cover
def _stop_for_message_limit(self, result: TestResult) -> None:
if not self.max_messages:
return
message = f"Maximum messages limit ({self.max_messages}) reached"
if not self._limit_stop_emitted:
console.print(f"\n[yellow]⚠️ {message}. Stopping session.[/yellow]")
self._emit(
{
"type": "status",
"status": "stopped",
"message": message,
"messages_sent": self.messages_sent_count,
"max_messages": self.max_messages,
}
)
self._limit_stop_emitted = True
result.status = "stopped"
result.error_message = message
result.completed_at = datetime.now()
def run_multi_scenario_test(
self,
bot: Bot,
scenarios: List[Scenario],
persona: Persona,
session: TestSession,
headless: bool = False,
) -> TestResult:
"""Run multiple scenarios with retry logic (max 3 attempts per scenario)."""
self.current_session = session
# 2026-05-17: tieni il bot accessibile come attributo così
# `_effective_fallbacks_for(step)` può costruire la lista bot+
# scenario+sub+session con il helper centralizzato. Senza questo
# avevamo solo `self._agent_deterministic_fallbacks` (bot-only),
# ignorando i marker scenario/sub/session-level (BUG #1 audit).
self._current_bot = bot
# 2026-05-17 (no_sources_mode): se il bot non ha knowledge sources
# assegnate, il judge non può verificare claim. In quel caso
# tutte le risposte sostantive saranno marcate
# `insufficient_sources` e l'unico verdict positivo possibile è
# il match con i deterministic_fallbacks configurati a mano.
# Calcoliamo il flag una volta a session-start; tutti i turni
# usano lo stesso valore.
self._no_sources_mode: bool = False
try:
from src.db.database import get_db as _get_db
from src.db.repositories import KnowledgeRepository
workspace_id = getattr(session, "workspace_id", None) or getattr(bot, "workspace_id", None)
if workspace_id and getattr(bot, "id", None):
_db = _get_db()
with _db.get_session() as _s:
_repo = KnowledgeRepository(_s)
_bindings = _repo.list_active_source_versions_for_bot(
workspace_id, bot.id, include_workspace_fallback=False,
)
self._no_sources_mode = not bool(_bindings)
except Exception:
# Best-effort: in caso di errore manteniamo False (logica
# standard del judge), evitiamo di degradare l'evaluation.
self._no_sources_mode = False
session_max_turns = getattr(session, "max_turns", None) or getattr(
session, "max_messages", None
)
if session_max_turns is not None:
self.max_messages = int(session_max_turns)
self._session_min_turns = max(int(getattr(session, "min_turns", 1) or 1), 0)
self.interaction_history = []
self.conversation_log = []
self.last_bot_message = None
self.scenario_results = {}
self._followup_topics = {} # Reset follow-up tracking
# Track sub-scenarios already covered with a satisfactory turn
# (intent_label in {satisfied, partial}). Used to skip them on retry
# attempts so we don't replay every step from scratch when only one
# failed.
self._covered_subscenarios: Dict[str, set] = {}
self.messages_sent_count = 0
self._limit_stop_emitted = False
self._knowledge_boundary = self._load_knowledge_boundary(bot)
self._agent_deterministic_fallbacks = [
str(item).strip().lower()
for item in (getattr(bot, "deterministic_fallbacks", []) or [])
if str(item).strip()
]
# Track scenario attempts and completions
scenario_attempts = {} # scenario_id -> attempt_count
scenario_completed = {} # scenario_id -> bool
max_attempts_per_scenario = 3
# Use session.id as scenario_id for multi-scenario tests (UUID compatible)
result = TestResult(
workspace_id=getattr(session, "workspace_id", None),
session_id=session.id,
scenario_id=session.id, # Use session ID as scenario ID for multi tests
persona_id=persona.id,
status="pending",
started_at=datetime.now(),
)
self._current_result = result
limit_info = f" | Max messages: {self.max_messages}" if self.max_messages else ""
console.print(
Panel.fit(
f"[bold blue]Multi-Scenario Test[/bold blue]\n"
f"Bot: {bot.name} | Persona: {persona.name}\n"
f"Scenarios: {len(scenarios)} | Max attempts: {max_attempts_per_scenario}{limit_info}",
title="AI Test Engine V3",
)
)
try:
# 1. Initialize browser once for all scenarios.
# Retry only on LAUNCH failures (Chromium missing, driver crash).
# URL/navigation failures (Page.goto timeouts, net::ERR_*) are not
# retryable: relaunching a fresh browser won't make a slow/unreachable
# host respond. Spawning two Playwright processes back-to-back also
# gives the visual impression of "multiple instances opening".
def _is_launch_failure(detail: Optional[str]) -> bool:
msg = (detail or "").lower()
url_related = (
"page.goto" in msg
or "net::err" in msg
or "err_aborted" in msg
or "err_name_not_resolved" in msg
or "err_connection" in msg
or "err_timed_out" in msg
or "frame was detached" in msg
)
return bool(msg) and not url_related
browser_ok = False
browser_detail: Optional[str] = None
for attempt in range(1, 3): # 2 tentativi massimi
if self._init_browser(bot, headless):
browser_ok = True
break
browser_detail = (
getattr(self.browser, "last_error", None) if self.browser else None
) or browser_detail
self._emit_log(
"warning",
"browser",
f"Browser startup failed (attempt {attempt}): {browser_detail or 'unknown error'}",
attempt=attempt,
)
# BrowserController.start() already cleans up on failure, but
# defensively drop any lingering reference so the next attempt
# starts from a clean slate.
self.browser = None
if not _is_launch_failure(browser_detail):
# Not worth retrying: it's a URL/navigation issue. Fail fast.
self._emit_log(
"warning",
"browser",
"Skipping retry: failure is URL/navigation related, not a browser launch error.",
)
break
if attempt < 2:
time.sleep(1.0 * attempt) # small backoff between launch retries
if not browser_ok:
result.status = "error"
result.error_message = (
f"Failed to start browser: {browser_detail}"
if browser_detail
else "Failed to start browser"
)
self._emit_log(
"error",
"browser",
result.error_message,
fatal=True,
)
return result
# 2. Execute all scenarios with retry logic
# Track whether each scenario has been at least exercised with one user turn.
scenario_coverage: Dict[str, bool] = {str(s.id): False for s in scenarios}
def remaining_uncovered_after(index: int) -> int:
return sum(
1
for future in scenarios[index + 1 :]
if not scenario_coverage.get(str(future.id), False)
)
for scenario_index, scenario in enumerate(scenarios):
scenario_id = str(scenario.id)
scenario_name = scenario.name
scenario_rotated_for_budget = False
# Initialize tracking for this scenario
if scenario_id not in scenario_attempts:
scenario_attempts[scenario_id] = 0
scenario_completed[scenario_id] = False
# Try up to max_attempts_per_scenario times to complete this scenario
while (
scenario_attempts[scenario_id] < max_attempts_per_scenario
and not scenario_completed[scenario_id]
and not self._is_stop_requested()
):
remaining_to_cover = remaining_uncovered_after(scenario_index)
self._reserved_messages_for_future_scenarios = remaining_to_cover
if self._should_rotate_to_next_scenario(
remaining_scenarios_to_cover=remaining_to_cover,
current_scenario_covered=scenario_coverage.get(scenario_id, False),
):
scenario_rotated_for_budget = True
budget = self._remaining_message_budget()
message = (
f"Rotating to next scenario to preserve coverage "
f"(remaining budget={budget}, scenarios left={remaining_to_cover})"
)
console.print(f"[yellow]⚖️ {message}[/yellow]")
self._emit({"type": "log", "level": "warning", "message": message})
break
# Check max messages limit: if budget is globally exhausted but there
# are other scenarios still uncovered, break out of this scenario loop
# so the outer loop can exercise the remaining ones.
if self._has_reached_message_limit():
if remaining_uncovered_after(scenario_index) > 0:
scenario_rotated_for_budget = True
self._emit_log(
"warning",
"engine",
"Global message limit reached; skipping remaining attempts for this scenario to keep coverage.",
scenario_id=scenario_id,
)
break
self._stop_for_message_limit(result)
return result
scenario_attempts[scenario_id] += 1
attempt_num = scenario_attempts[scenario_id]
console.print(
f"\n[bold cyan]Scenario: {scenario_name}[/bold cyan] "
f"(Attempt {attempt_num}/{max_attempts_per_scenario})"
)
# Emit scenario status
self._emit(
{
"type": "scenario_status",
"scenario_id": scenario_id,
"scenario_name": scenario_name,
"status": "in_progress",
"attempt": attempt_num,
"max_attempts": max_attempts_per_scenario,
}
)
# Get steps for this scenario
steps = scenario.steps if scenario.steps else []
if not steps:
steps = self._auto_generate_steps_for_scenario(scenario)
# Tag each step with scenario info
subscenario_lookup: Dict[str, Any] = {
str(getattr(sub, "id")): sub
for sub in (getattr(scenario, "subscenarios", []) or [])
if getattr(sub, "id", None)
}
for step in steps:
step.scenario_id = str(scenario.id)
step.scenario_name = scenario.name
step.attempt = attempt_num
subscenario_id = str(getattr(step, "subscenario_id", "") or "").strip()
subscenario = subscenario_lookup.get(subscenario_id)
# 2026-05-17: attach scenario/subscenario refs ai
# step così downstream `_effective_fallbacks_for`
# può estrarre `success_criteria.fallback_markers`
# dai due livelli. Prima esistevano solo
# `step.scenario_id`/`scenario_name` (string),
# insufficiente per leggere i markers.
step._scenario_obj = scenario # type: ignore[attr-defined]
step._subscenario_obj = subscenario # type: ignore[attr-defined]
if subscenario and not getattr(step, "subscenario_name", None):
step.subscenario_name = str(
getattr(subscenario, "name", "") or scenario.name
).strip()
if subscenario and not getattr(step, "subscenario_goal", None):
step.subscenario_goal = str(
getattr(subscenario, "goal", "")
or scenario.description
or scenario.name
).strip()
criteria_for_scope = (
getattr(subscenario, "success_criteria", None) if subscenario else None
) or getattr(scenario, "success_criteria", None)
step.expected_scope = self._infer_scope_expectation_for_components(
success_criteria=criteria_for_scope,
category=(getattr(scenario, "category", "") or ""),
name=(
str(getattr(subscenario, "name", "")).strip()
if subscenario
else (scenario.name or "")
),
description=(
str(getattr(subscenario, "goal", "")).strip()
if subscenario
else (scenario.description or "")
),
tags=list(getattr(scenario, "tags", []) or []),
)
effective_followup_policy = getattr(step, "followup_policy", None)
if not effective_followup_policy:
effective_followup_policy = (
getattr(subscenario, "followup_policy", None)
if subscenario
else None
) or getattr(scenario, "followup_policy", "limited")
step.followup_policy = self._normalize_followup_policy(
effective_followup_policy
)
effective_followup_max_turns = getattr(step, "followup_max_turns", None)
if effective_followup_max_turns is None:
effective_followup_max_turns = (
getattr(subscenario, "followup_max_turns", None)
if subscenario
else None
)
if effective_followup_max_turns is None:
effective_followup_max_turns = getattr(
scenario,
"followup_max_turns",
self._max_followups_per_step,
)
step.followup_max_turns = int(
effective_followup_max_turns or self._max_followups_per_step
)
# Execute steps for this attempt
attempt_success = True
for step_idx, step in enumerate(steps):
# Retry skip: on attempts > 1, skip sub-scenarios that
# already produced a satisfactory turn in a previous
# attempt. Without this the runner replays every step
# from scratch and burns ~2x the turns on repeated
# intents (see plan: Issue 3).
step_subscenario_id = str(
getattr(step, "subscenario_id", "") or ""
).strip()
if (
attempt_num > 1
and step_subscenario_id
and step_subscenario_id
in self._covered_subscenarios.get(scenario_id, set())
):
sub_label = (
str(getattr(step, "subscenario_name", "") or "").strip()
or step_subscenario_id[:8]
)
self._emit(
{
"type": "log",
"level": "info",
"message": (
f"Sub-scenario '{sub_label[:40]}' già coperto, "
f"skip su attempt {attempt_num}"
),
"scenario_id": scenario_id,
"step_id": getattr(step, "step_id", None),
}
)
continue
remaining_to_cover = remaining_uncovered_after(scenario_index)
self._reserved_messages_for_future_scenarios = remaining_to_cover
if self._should_rotate_to_next_scenario(
remaining_scenarios_to_cover=remaining_to_cover,
current_scenario_covered=scenario_coverage.get(scenario_id, False),
):
scenario_rotated_for_budget = True
attempt_success = False
budget = self._remaining_message_budget()
message = (
f"Pausing scenario '{scenario_name}' to preserve "
f"{remaining_to_cover} message slot(s) for remaining scenarios "
f"(budget={budget})."
)
console.print(f"[yellow]⚖️ {message}[/yellow]")
self._emit({"type": "log", "level": "warning", "message": message})
break
if self._has_reached_message_limit():
if remaining_uncovered_after(scenario_index) > 0:
scenario_rotated_for_budget = True
attempt_success = False
self._emit_log(
"warning",
"engine",
"Message limit reached mid-step; moving to next scenario for coverage.",
scenario_id=scenario_id,
step_id=getattr(step, "step_id", None),
)
break
self._stop_for_message_limit(result)
return result
if self._is_stop_requested():
result.status = "stopped"
result.error_message = "Stopped manually"
break
console.print(
f"\n[bold]Step {step_idx + 1}/{len(steps)}:[/bold] {step.step_id}"
)
before_messages = self.messages_sent_count
success = self._execute_conversation_turn(bot, persona, step, result)
if self._disarm_turn_watchdog():
# Watchdog fired during this turn: treat as transient
# failure, do NOT count it as a sent message, and let
# the scenario continue at the next step.
success = False
if self.messages_sent_count > before_messages:
self.messages_sent_count = before_messages
self._emit_log(
"warning",
"engine",
"Turn aborted by watchdog; continuing scenario.",
scenario_id=scenario_id,
step_id=getattr(step, "step_id", None),
)
if self.messages_sent_count > before_messages:
scenario_coverage[scenario_id] = True
if result.status == "stopped":
# If we hit the limit while there are still uncovered scenarios,
# continue with next scenario instead of ending the whole run.
if (
self._has_reached_message_limit()
and remaining_uncovered_after(scenario_index) > 0
and scenario_coverage.get(scenario_id, False)
):
scenario_rotated_for_budget = True
attempt_success = False
result.status = "pending"
result.error_message = None
self._emit(
{
"type": "log",
"level": "warning",
"message": "Message limit reached for current scenario; moving to next scenario for coverage.",
}
)
break
if (
self._has_reached_message_limit()
and scenario_id in self.scenario_results
):
scenario_info = self.scenario_results[scenario_id]
expected_scope = scenario_info.get(
"expected_scope"
) or self._infer_scope_expectation(scenario)
scenario_info["status"] = "failed"
scenario_info["completed"] = False
if not scenario_info.get("outcome_type"):
scenario_info["outcome_type"] = (
"out_of_scope_fallback_fail"
if expected_scope == "out_of_scope"
else "in_scope_fail"
)
scenario_info["completion_reason"] = (
"Message budget exhausted before scenario completion"
)
# If there are remaining uncovered scenarios, don't abort
# the whole run — break out to let them try.
if remaining_uncovered_after(scenario_index) > 0:
scenario_rotated_for_budget = True
attempt_success = False
result.status = "pending"
result.error_message = None
break
return result
if not success:
console.print(f"[yellow]Step {step.step_id} had issues[/yellow]")
attempt_success = False
# Mid-session browser crash recovery: if the
# underlying Chromium died, try restarting it so
# the run can continue instead of failing the
# whole session. Capped by BROWSER_RECOVERY_MAX.
try:
if self.browser is not None and not self.browser.is_alive():
self._try_recover_browser(bot, headless, result)
except Exception as recovery_exc:
self._emit_log(
"error",
"browser",
f"Browser recovery check failed: {recovery_exc}",
)
# Pause between turns
time.sleep(random.uniform(1.5, 3.0))
self._reserved_messages_for_future_scenarios = 0
# Evaluate scenario outcome (in-scope / out-of-scope + fallback behavior)
scenario_outcome = self._evaluate_scenario_outcome(scenario, attempt_success)
if scenario_rotated_for_budget and not scenario_outcome.get("passed", False):
budget_reason = "Message budget preserved to ensure all selected scenarios are exercised"
existing_reason = str(scenario_outcome.get("reason") or "").strip()
if existing_reason and budget_reason.lower() not in existing_reason.lower():
scenario_outcome["reason"] = f"{budget_reason}. {existing_reason}"
else:
scenario_outcome["reason"] = budget_reason
is_completed = scenario_outcome.get("passed", False)
scenario_completed[scenario_id] = is_completed
if scenario_id in self.scenario_results:
self.scenario_results[scenario_id]["status"] = (
"completed" if is_completed else "failed"
)
self.scenario_results[scenario_id]["completed"] = bool(is_completed)
self.scenario_results[scenario_id]["attempts"] = attempt_num
self.scenario_results[scenario_id]["outcome_type"] = scenario_outcome.get(
"outcome_type"
)
self.scenario_results[scenario_id]["completion_reason"] = (
scenario_outcome.get("reason")
)
self.scenario_results[scenario_id]["fallback_detected"] = (
scenario_outcome.get("fallback_detected", False)
)
self.scenario_results[scenario_id]["fallback_required"] = (
scenario_outcome.get("fallback_required", True)
)
self.scenario_results[scenario_id]["boundary_violations_count"] = (
scenario_outcome.get("boundary_violations_count", 0)
)
subscenario_outcomes = scenario_outcome.get("subscenario_outcomes") or {}
if subscenario_outcomes:
sub_map = self.scenario_results[scenario_id].setdefault(
"subscenarios", {}
)
for sub_id, sub_outcome in subscenario_outcomes.items():
entry = sub_map.setdefault(
str(sub_id),
{
"name": sub_outcome.get("name") or str(sub_id),
"goal": sub_outcome.get("goal") or "",
"turns": [],
},
)
entry["name"] = sub_outcome.get("name") or entry.get("name")
entry["goal"] = sub_outcome.get("goal") or entry.get("goal")
entry["status"] = (
"completed" if bool(sub_outcome.get("passed")) else "failed"
)
entry["completed"] = bool(sub_outcome.get("passed"))
entry["outcome_type"] = sub_outcome.get("outcome_type")
entry["completion_reason"] = sub_outcome.get("reason")
entry["fallback_detected"] = bool(
sub_outcome.get("fallback_detected", False)
)
entry["fallback_required"] = bool(
sub_outcome.get("fallback_required", True)
)
entry["boundary_violations_count"] = int(
sub_outcome.get("boundary_violations_count", 0) or 0
)
if is_completed:
console.print(
f"[bold green]✅ Scenario '{scenario_name}' COMPLETED on attempt {attempt_num}![/bold green]"
)
self._emit(
{
"type": "scenario_status",
"scenario_id": scenario_id,
"scenario_name": scenario_name,
"status": "completed",
"attempt": attempt_num,
"message": f"Scenario completed successfully on attempt {attempt_num}",
"outcome_type": scenario_outcome.get("outcome_type"),
"reason": scenario_outcome.get("reason"),
}
)
elif scenario_rotated_for_budget:
console.print(
f"[yellow]⚖️ Scenario '{scenario_name}' paused after attempt {attempt_num} to keep coverage for remaining scenarios[/yellow]"
)
elif attempt_num < max_attempts_per_scenario:
console.print(
f"[yellow]⚠️ Scenario '{scenario_name}' not completed. Retrying...[/yellow]"
)
self._emit(
{
"type": "scenario_status",
"scenario_id": scenario_id,
"scenario_name": scenario_name,
"status": "retrying",
"attempt": attempt_num,
"message": f"Attempt {attempt_num} failed, will retry...",
"outcome_type": scenario_outcome.get("outcome_type"),
"reason": scenario_outcome.get("reason"),
}
)
# Wait before retry
time.sleep(random.uniform(2.0, 4.0))
else:
console.print(
f"[bold red]❌ Scenario '{scenario_name}' FAILED after {max_attempts_per_scenario} attempts[/bold red]"
)
self._emit(
{
"type": "scenario_status",
"scenario_id": scenario_id,
"scenario_name": scenario_name,
"status": "failed",
"attempt": attempt_num,
"message": f"Scenario failed after {max_attempts_per_scenario} attempts",
"outcome_type": scenario_outcome.get("outcome_type"),
"reason": scenario_outcome.get("reason"),
}
)
# Save intermediate results after each attempt
self._save_intermediate_results(result)
# Move to next scenario when current one is paused for budget balancing.
if scenario_rotated_for_budget:
break
if self._is_stop_requested():
break
self._reserved_messages_for_future_scenarios = 0
if self._is_stop_requested():
break
# 4. Finalize
# Determine status based on scenario completion
completed_count = sum(1 for v in scenario_completed.values() if v)
total_turns = len(self.conversation_log)
if self._is_stop_requested():
result.status = "stopped"
result.termination_reason = "manual_stop"
elif self._has_reached_message_limit():
result.status = "failed"
result.termination_reason = "max_turns"
elif completed_count == len(scenarios) and total_turns >= self._session_min_turns:
result.status = "passed" # All scenarios completed
result.termination_reason = "goal_reached"
elif completed_count == len(scenarios) and total_turns < self._session_min_turns:
result.status = "failed"
result.termination_reason = "min_turns_not_met"
else:
result.status = "failed" # Any missing scenario completion counts as failed
result.termination_reason = "goal_not_reached"
result.completed_at = datetime.now()
result.conversation_log = json.dumps(
self.conversation_log, ensure_ascii=False, default=str
)
result.scenario_results = self.scenario_results
# Calculate final stats
completed_count = sum(1 for v in scenario_completed.values() if v)
total_scenarios = len(scenarios)
console.print("\n[bold]=== Session Summary ===[/bold]")
console.print(f"Scenarios completed: {completed_count}/{total_scenarios}")
console.print(f"Total conversation turns: {total_turns}")
self._emit(
{
"type": "session_summary",
"scenarios_completed": completed_count,
"scenarios_total": total_scenarios,
"total_turns": total_turns,
"termination_reason": result.termination_reason,
}
)
except Exception as e:
console.print(f"[red]Test error: {e}[/red]")
result.status = "error"
result.error_message = str(e)
result.termination_reason = "error"
result.completed_at = datetime.now()
# Still save what we have
result.conversation_log = json.dumps(
self.conversation_log, ensure_ascii=False, default=str
)
result.scenario_results = self.scenario_results
finally:
# Persist a final screenshot (useful even for failed runs), then save results.
if self.browser:
try:
final_path = self.browser.capture_screenshot("final")
if final_path:
result.screenshot_urls.append(final_path)
self._trim_screenshot_urls(result)
except Exception:
pass
# Always save final results
self._save_intermediate_results(result)
if self.browser:
self.browser.cleanup()
self.browser = None
return result
def run_test(
self,
bot: Bot,
scenario: Scenario,
persona: Persona,
session: TestSession,
headless: bool = False,
) -> TestResult:
"""Run a single scenario test."""
return self.run_multi_scenario_test(bot, [scenario], persona, session, headless)
def _try_recover_browser(self, bot: Bot, headless: bool, result: TestResult) -> bool:
"""Attempt to recover from a mid-session browser crash.
Capped by BROWSER_RECOVERY_MAX per session (default 3, 0 disables).
On success the run continues from the next step; on failure the
caller stays in its normal failure path (status stays as-is).
Cookie/login state inside the bot is lost, which is acceptable for
the stateless chatbots this platform targets.
"""
max_recoveries = max(0, env_int("BROWSER_RECOVERY_MAX", 3))
if max_recoveries <= 0:
return False
attempts_used = int(getattr(self, "_browser_recovery_attempts", 0) or 0)
if attempts_used >= max_recoveries:
self._emit_log(
"error",
"browser",
f"Browser recovery budget exhausted ({attempts_used}/{max_recoveries}).",
)
return False
self._browser_recovery_attempts = attempts_used + 1
self._emit_log(
"warning",
"browser",
f"Detected dead browser mid-session — attempting recovery ({self._browser_recovery_attempts}/{max_recoveries}).",
)
try:
if self.browser is not None:
try:
self.browser.cleanup()
except Exception:
pass
self.browser = None
except Exception:
pass
if not self._init_browser(bot, headless):
self._emit_log(
"error",
"browser",
"Browser recovery failed: relaunch did not succeed.",
)
return False
self._emit(
{
"type": "browser_recovered",
"attempt": self._browser_recovery_attempts,
"max": max_recoveries,
"message": "Browser recovered mid-session; continuing.",
}
)
self._emit_log(
"info",
"browser",
f"Browser recovered (attempt {self._browser_recovery_attempts}/{max_recoveries}).",
)
try:
logger.info(
"browser_recovered",
extra={
"attempt": self._browser_recovery_attempts,
"max_recoveries": max_recoveries,
"session_id": str(getattr(result, "session_id", "")) or None,
},
)
except Exception:
pass
return True
def _init_browser(self, bot: Bot, headless: bool) -> bool:
"""Initialize and start browser."""
self.browser = BrowserController(
selectors=bot.selectors.model_dump(),
output_dir=str(self.output_dir),
headless=headless,
slow_mo=env_int("BROWSER_SLOW_MO", 0),
)
if not self.browser.start(str(bot.url)):
detail = getattr(self.browser, "last_error", None) or "Unknown error"
console.print(f"[red]Failed to start browser: {detail}[/red]")
# Surface the root cause to UI logs for production debugging.
self._emit({"type": "error", "message": f"Failed to start browser: {detail}"})
return False
# Emit a first screenshot as soon as the page is loaded, so production
# (headless) runs still provide visual confirmation immediately.
current_url = getattr(getattr(self.browser, "page", None), "url", None) or str(bot.url)
title = ""
try:
title = self.browser.page.title() if getattr(self.browser, "page", None) else ""
except Exception:
title = ""
self._emit(
{
"type": "log",
"level": "info",
"message": f"Browser ready (headless={headless}). URL: {current_url}{' | ' + title if title else ''}",
}
)
try:
# Live preview (overwrites a single file) + persisted evidence (unique file).
live_path = self.browser.capture_live_screenshot("live") if self.browser else None
if live_path:
self._emit(
{
"type": "screenshot",
"path": live_path,
"label": "browser_ready",
"live": True,
}
)
evidence_path = (
self.browser.capture_screenshot("browser_ready") if self.browser else None
)
if evidence_path and self._current_result:
self._current_result.screenshot_urls.append(evidence_path)
self._trim_screenshot_urls(self._current_result)
if not live_path and not evidence_path:
self._emit(
{
"type": "log",
"level": "warning",
"message": "Browser ready, but screenshot capture returned no file (headless viewer may stay blank).",
}
)
except Exception as e:
# Never fail the run due to screenshot/logging, but do surface the failure.
self._emit(
{
"type": "log",
"level": "warning",
"message": f"Browser ready, but screenshot capture failed: {e}",
}
)
# Click "New Chat" if configured
if bot.auto_click_new_chat:
clicked = self.browser.click_new_chat()
if clicked:
console.print("[dim]Clicked 'New Chat'[/dim]")
self.browser.wait(1.0)
return True
def _execute_conversation_turn(
self,
bot: Bot,
persona: Persona,
step,
result: TestResult,
) -> bool:
"""
Execute a single conversation turn with realistic flow:
1. Read/understand current state (including last bot response)
2. Think and decide what to say next
3. Type message with realistic delay
4. Wait for and read bot response
5. Evaluate and record
"""
scenario_id = str(getattr(step, "scenario_id", "unknown"))
scenario_name = getattr(step, "scenario_name", "Unknown")
# Backstop watchdog: a stuck LLM/Playwright/judge that ignores its own
# timeout would otherwise freeze the whole run. The watchdog sets a
# flag; the caller (run_multi_scenario_test) downgrades the turn to
# failed and continues the scenario. Armed here, disarmed by the
# caller via _disarm_turn_watchdog() right after the call returns.
self._arm_turn_watchdog(scenario_id, getattr(step, "step_id", None))
try:
# === PHASE 1: PERCEIVE (Read current state) ===
console.print("[dim]Phase 1: Reading conversation state...[/dim]")
# Emit phase start
self._emit(
{
"type": "phase",
"phase": "perceive",
"message": "Reading conversation state...",
"step_id": step.step_id,
}
)
context = self.browser.get_context()
# Build rich context including conversation history
conversation_summary = self._build_conversation_summary()
# Emit what the AI sees
self._emit(
{
"type": "ai_sees",
"context_preview": context[:200] if context else "No context",
"conversation_history": conversation_summary,
"last_bot_message": (
self.last_bot_message[:150] if self.last_bot_message else "None"
),
"step_id": step.step_id,
}
)
# === PHASE 2: THINK (Understand and decide) ===
console.print("[dim]Phase 2: Understanding and deciding action...[/dim]")
# Emit phase start
self._emit(
{
"type": "phase",
"phase": "think",
"message": "Understanding and deciding action...",
"step_id": step.step_id,
}
)
# Include scenario goal in reasoning
scenario_context = self._build_scenario_context(step)
# Emit persona and scenario info
self._emit(
{
"type": "ai_persona",
"persona_name": persona.name if persona else "Unknown",
"persona_mood": persona.mood if persona else "neutral",
"scenario_context": scenario_context,
"step_id": step.step_id,
}
)
action = self.ai_client.decide_action(
context=context,
history=self.interaction_history,
persona=persona,
last_bot_message=self.last_bot_message,
scenario_context=scenario_context,
system_prompt_override=self.persona_system_prompt_override,
)
original_action_type = action.action_type
console.print(
Panel(
f"[yellow]{action.reasoning}[/yellow]\n"
f"Action: [bold]{action.action_type.value}[/bold] | "
f"Content: '{action.content[:50]}...'",
title="AI Decision",
border_style="blue",
)
)
# Force step action type if specified
if action.action_type != step.action_type:
action.action_type = step.action_type
self._emit(
{
"type": "log",
"level": "warning",
"message": (
f"Action adjusted for step contract: {original_action_type.value} -> "
f"{action.action_type.value}"
),
"step_id": step.step_id,
}
)
# Emit detailed AI reasoning (after potential action normalization)
self._emit(
{
"type": "ai_reasoning",
"reasoning": action.reasoning,
"decision": action.action_type.value,
"content": action.content,
"confidence": action.confidence,
"step_id": step.step_id,
}
)
if "api failure" in (action.reasoning or "").lower():
self._emit(
{
"type": "log",
"level": "error",
"message": f"AI decision fallback triggered: {action.reasoning}",
"step_id": step.step_id,
}
)
# === PHASE 3: ACT (Type with realistic delay) ===
console.print("[dim]Phase 3: Typing message with realistic delay...[/dim]")
# Emit phase start
self._emit(
{
"type": "phase",
"phase": "act",
"message": f"Executing action: {action.action_type.value}",
"action_type": action.action_type.value,
"content": action.content,
"step_id": step.step_id,
}
)
if action.action_type in [ActionType.SEND_MESSAGE, ActionType.TYPE]:
if not action.content and step.content:
action.content = step.content
if self._has_reached_message_limit():
self._stop_for_message_limit(result)
return False
action_success = self._perform_action(action)
if not action_success:
console.print("[red]Action failed[/red]")
self._emit(
{
"type": "error",
"message": "Action failed",
"step_id": step.step_id,
}
)
return False
if action.action_type in [ActionType.SEND_MESSAGE, ActionType.TYPE]:
self.messages_sent_count += 1
# Emit action success
self._emit(
{
"type": "action_complete",
"action_type": action.action_type.value,
"content_sent": action.content,
"step_id": step.step_id,
}
)
# Record user message
self._emit(
{
"type": "chat",
"sender": "user",
"text": action.content,
"step_id": step.step_id,
"scenario_id": scenario_id,
}
)
# === PHASE 4: WAIT FOR RESPONSE ===
if step.wait_for_response and action.action_type == ActionType.SEND_MESSAGE:
console.print("[dim]Phase 4: Waiting for bot response...[/dim]")
# Emit phase start
self._emit(
{
"type": "phase",
"phase": "wait",
"message": "Waiting for bot response...",
"timeout": env_int("RESPONSE_TIMEOUT", 30),
"step_id": step.step_id,
}
)
# Add realistic reading time before expecting response
time.sleep(random.uniform(0.5, 1.5))
self._emit(
{
"type": "status",
"message": "Bot is typing...",
"step_id": step.step_id,
}
)
# Wait for response with a small retry loop: some bots take longer
# than the hardcoded timeout on the first turn (cold start, network
# wobble). Retry with exponential backoff before giving up.
bot_response = None
bot_response_truncated = False # default safe se loop non eseguito
base_timeout = env_int("RESPONSE_TIMEOUT", 30)
max_wait_attempts = max(env_int("RESPONSE_MAX_RETRIES", 2), 1)
wait_retry_count = 0
for wait_attempt in range(1, max_wait_attempts + 1):
if self._is_stop_requested():
break
bot_response = self.browser.wait_for_bot_response(
timeout=base_timeout,
stop_requested=self._is_stop_requested,
on_live_screenshot=lambda path: self._emit(
{"type": "screenshot", "path": path, "live": True}
),
)
# Leggi il flag emesso dal browser controller: True se
# la risposta è stata catturata in modo parziale per
# timeout. Lo salviamo nel log e nell'evidence_pack
# per il judge.
bot_response_truncated = bool(
getattr(self.browser, "last_response_was_truncated", False)
)
if bot_response and str(bot_response).strip():
break
wait_retry_count += 1
if wait_attempt < max_wait_attempts:
backoff = min(2 ** (wait_attempt - 1), 8)
self._emit_log(
"warning",
"api",
f"Empty/timeout bot response (attempt {wait_attempt}/{max_wait_attempts}); retrying in {backoff}s.",
step_id=getattr(step, "step_id", None),
attempt=wait_attempt,
)
time.sleep(backoff)
# Get rich content data (maps, images, links, buttons)
rich_content = {}
if bot_response and self.browser:
try:
response_with_rich = self.browser.get_last_bot_response_with_rich_content()
rich_content = response_with_rich.get("rich_content", {})
if (
rich_content.get("has_map")
or rich_content.get("has_image")
or rich_content.get("has_link")
):
console.print(
f"[dim]📎 Rich content detected: map={rich_content.get('has_map')}, image={rich_content.get('has_image')}, links={len(rich_content.get('links', []))}[/dim]"
)
except Exception as e:
console.print(f"[dim]Could not extract rich content: {e}[/dim]")
source_evidence: List[Dict[str, Any]] = []
factuality_sources: List[Dict[str, Any]] = []
memory_hits: List[Dict[str, Any]] = []
# Skip RAG retrieval triplo quando il judge inline è disattivato
# (ENABLE_TURN_EVALUATOR=false / LIVE_JUDGE_ENABLED=false). Il
# post-session judge `_run_session_judge_sync` re-esegue retrieval
# e source matching su ogni turno, quindi non perdiamo
# informazione: risparmiamo latenza e costo del retrieval ad
# ogni turno live.
if bot_response and self.turn_eval:
try:
# Triple retrieval per coprire tutti i fatti citati
# dal bot, anche quando il retrieve è lexical (token
# overlap) e non semantico:
# 1. Query user (topic generico)
# 2. Bot response (fatti specifici)
# 3. ENTITÀ ESTRATTE dalla bot response (nomi propri:
# "Monastero del Deserto", "Santa Maria delle Grazie")
# Senza il punto 3, query lunghe come "monumenti
# storici di Sant'Agata" recuperano chunks con tanti
# token comuni ("monumenti", "storici") ma mancano
# i chunks specifici sull'entità citata.
primary_hits = self._retrieve_memory_hits(
bot=bot, query=action.content
)
bot_query = (bot_response or "").strip()[:600]
secondary_hits = (
self._retrieve_memory_hits(bot=bot, query=bot_query)
if bot_query
else []
)
# Estrai sequenze di parole capitalizzate (proper
# nouns multi-token tipo "Cappella Sansevero",
# "Santa Maria delle Grazie", "Monastero del
# Deserto"). Connettori interni (di, del, della,
# delle, dei, degli, sui, e, ai) sono permessi
# in lowercase tra parole capitalizzate.
import re as _re_entities
entity_re = _re_entities.compile(
r"\b[A-ZÀ-Ý][\wÀ-ÿ]+(?:\s+(?:di|del|della|delle|dei|degli|sui|e|ai|al|d['’]|dell[oae]?'?)\s+|\s+)?(?:[A-ZÀ-Ý][\wÀ-ÿ']+(?:\s+(?:di|del|della|delle|dei|degli|sui|e|ai|al|d['’]|dell[oae]?'?)\s+)?){0,4}"
)
candidates = entity_re.findall(bot_response or "")
# Re-estraggo direttamente con finditer per ottenere
# match completi (findall su gruppi è instabile).
entities = []
for m in _re_entities.finditer(
r"(?:[A-ZÀ-Ý][\wÀ-ÿ']+(?:\s+(?:di|del|della|delle|dei|degli|sui|e|ai|al|d['’]|dell[oae]?'?))?\s+)*[A-ZÀ-Ý][\wÀ-ÿ']{2,}",
bot_response or "",
):
tok = m.group(0).strip()
# Filtra rumore: parole singole comuni, troppo corte.
if len(tok) < 6 or " " not in tok:
continue
entities.append(tok)
# Dedup mantenendo ordine, max 6 entità per turno.
seen_e: set = set()
unique_entities: List[str] = []
for e in entities:
k = e.lower()
if k in seen_e:
continue
seen_e.add(k)
unique_entities.append(e)
if len(unique_entities) >= 6:
break
entity_hits: List[Dict[str, Any]] = []
for ent in unique_entities:
try:
entity_hits.extend(
self._retrieve_memory_hits(bot=bot, query=ent) or []
)
except Exception:
continue
seen_keys = set()
memory_hits = []
for hit in (primary_hits or []) + (secondary_hits or []) + entity_hits:
key = (
str(hit.get("source_id") or hit.get("source_name") or ""),
(str(hit.get("snippet") or "")[:120]),
)
if key in seen_keys:
continue
seen_keys.add(key)
memory_hits.append(hit)
source_evidence = self._collect_source_evidence(rich_content)
factuality_sources = self._build_factuality_sources(
bot=bot,
source_evidence=source_evidence,
memory_hits=memory_hits,
)
except Exception as e:
console.print(f"[yellow]Source evidence collection error: {e}[/yellow]")
if bot_response:
console.print(
Panel(
bot_response[:300] + "..." if len(bot_response) > 300 else bot_response,
title="Bot Response",
border_style="green",
)
)
# Emit bot response received. `has_rich_html` segnala alla
# UI che il successivo evento `chat` includerà `text_html`
# (così la popup live può decidere se renderizzare HTML
# invece di plain text). Vedi `_sanitize_bot_html` in
# browser_controller.py.
_rich = rich_content if isinstance(rich_content, dict) else {}
self._emit(
{
"type": "bot_response_received",
"response_length": len(bot_response),
"response_preview": bot_response[:200],
"has_rich_html": bool(_rich.get("sanitized_html")),
"step_id": step.step_id,
}
)
# === PHASE 5: COMPREHEND AND RECORD ===
console.print("[dim]Phase 5: Processing response...[/dim]")
# Emit phase start
self._emit(
{
"type": "phase",
"phase": "comprehend",
"message": "Processing and evaluating response...",
"step_id": step.step_id,
}
)
# Screenshot during execution
screenshot_path = None
if self.browser:
screenshot_path = self.browser.capture_screenshot(
f"turn_{len(self.conversation_log) + 1}"
)
if screenshot_path:
self._emit(
{
"type": "screenshot",
"path": screenshot_path,
"turn": len(self.conversation_log) + 1,
}
)
# Dialogic turn evaluation (AIS + intent + refusal handling).
turn_eval_result = None
if self.turn_eval:
try:
console.print("[dim]Running TurnEvaluator pipeline...[/dim]")
# Determine subscenario goal/intent for this step.
sub_goal = (
str(getattr(step, "subscenario_goal", "") or "").strip()
or str(getattr(step, "scenario_name", "") or "").strip()
)
scenario_label = str(getattr(step, "scenario_name", "") or "").strip()
boundary_text = (
getattr(self._knowledge_boundary, "content_raw", "")
if self._knowledge_boundary
else ""
) or ""
# Effective fallbacks: bot + scenario + sub + session
# (fix 2026-05-17, audit pipeline fallback). Prima
# passava solo `_agent_deterministic_fallbacks`,
# ignorando i marker scenario-level configurati
# nello step 2 del wizard "Marcatori di fallback".
effective_fallbacks = self._effective_fallbacks_for(step=step)
turn_eval_result = self.turn_eval.evaluate(
user_query=action.content,
bot_response=bot_response,
agent_description=(bot.description or ""),
knowledge_boundary_text=boundary_text,
deterministic_fallbacks=effective_fallbacks,
retrieved_sources=factuality_sources,
subscenario_goal=sub_goal,
scenario_name=scenario_label,
no_sources_mode=getattr(self, "_no_sources_mode", False),
)
# Override AIS quando la cattura è stata troncata:
# non è giusto valutare claim su una risposta
# spezzata. Sostituiamo con `insufficient_sources`
# e una motivazione esplicita. L'intent_label
# resta quello del judge (può ancora esprimere
# un giudizio approssimato).
if bot_response_truncated and turn_eval_result is not None:
self._emit_log(
"warning",
"evaluator",
"Risposta del bot troncata in cattura: AIS forzato a 'insufficient_sources' (claim non valutati su testo parziale).",
step_id=getattr(step, "step_id", None),
)
turn_eval_result.ais_label = "insufficient_sources"
turn_eval_result.ais_reasoning = (
"Risposta catturata in modo PARZIALE (timeout di cattura su streaming bot). "
"I claim sul testo troncato non sono stati valutati per non penalizzare il bot. "
+ (turn_eval_result.ais_reasoning or "")
)
self._emit(
{
"type": "turn_evaluation",
"turn": len(self.conversation_log) + 1,
"scenario_id": scenario_id,
"step_id": step.step_id,
"ais_label": turn_eval_result.ais_label,
"ais_reasoning": turn_eval_result.ais_reasoning,
"intent_label": turn_eval_result.intent_label,
"response_type": turn_eval_result.response_type,
"expected_behavior": turn_eval_result.expected_behavior,
"actionability_label": turn_eval_result.actionability_label,
}
)
# Mark sub-scenario as covered when the evaluator
# confirmed the intent was at least partially met.
# This feeds the retry-skip logic above.
if turn_eval_result.intent_label in {"satisfied", "partial"}:
step_sub_id = str(
getattr(step, "subscenario_id", "") or ""
).strip()
if step_sub_id:
self._covered_subscenarios.setdefault(
scenario_id, set()
).add(step_sub_id)
console.print(
f"[dim]TurnEvaluator: ais={turn_eval_result.ais_label} intent={turn_eval_result.intent_label} "
f"resp={turn_eval_result.response_type} exp={turn_eval_result.expected_behavior}[/dim]"
)
except Exception as e:
console.print(f"[yellow]TurnEvaluator error: {e}[/yellow]")
self._emit_log(
"warning",
"evaluator",
f"TurnEvaluator failed for turn {len(self.conversation_log) + 1}: {e}",
step_id=step.step_id,
)
response_useful = is_response_useful_for_continuation(bot_response)
if not response_useful:
self._emit(
{
"type": "log",
"level": "warning",
"message": "Bot response is low-value for continuation; retry/follow-up may be needed.",
"step_id": step.step_id,
}
)
# Emit for UI. `text_html` viene dal sanitizer del
# browser_controller (`_sanitize_bot_html`) ed è una stringa
# HTML già pulita con whitelist tag/attr. Resta vuota se il
# widget chat è plain text — la popup live in tal caso usa
# `text` con whitespace-pre-wrap. Vedi sessions.html
# `addConversationMessage` e session_turns.html riga ~609.
bot_response_html_for_ui = ""
if isinstance(rich_content, dict):
bot_response_html_for_ui = (
rich_content.get("sanitized_html") or ""
)
self._emit(
{
"type": "chat",
"sender": "bot",
"text": bot_response,
"text_html": bot_response_html_for_ui,
"step_id": step.step_id,
"scenario_id": scenario_id,
}
)
# Use the new TurnEvaluator output for AIS / intent labelling.
if turn_eval_result is not None:
ais_label_value = turn_eval_result.ais_label
ais_reasoning_value = turn_eval_result.ais_reasoning
ais_claim_records = [c.to_dict() for c in turn_eval_result.claims]
intent_label_value = turn_eval_result.intent_label
intent_reasoning_value = turn_eval_result.intent_reasoning
response_type_value = turn_eval_result.response_type
expected_behavior_value = turn_eval_result.expected_behavior
fallback_similarity_value = turn_eval_result.fallback_similarity
matched_fallback_value = turn_eval_result.matched_fallback
actionability_label_value = turn_eval_result.actionability_label
actionability_reasoning_value = turn_eval_result.actionability_reasoning
evaluator_used = True
else:
ais_label_value = None
ais_reasoning_value = "Turn not evaluated: TurnEvaluator is disabled."
ais_claim_records = []
intent_label_value = None
intent_reasoning_value = "TurnEvaluator disabled."
response_type_value = None
expected_behavior_value = None
fallback_similarity_value = 0.0
matched_fallback_value = None
actionability_label_value = None
actionability_reasoning_value = ""
evaluator_used = False
evidence_pack = {
"source_evidence": source_evidence,
"memory_hits": memory_hits,
"cited_sources_total": len(source_evidence or []),
"memory_hits_total": len(memory_hits or []),
"evaluator_enabled": evaluator_used,
"evaluator_kind": "turn_evaluator" if evaluator_used else None,
}
# Log conversation
log_entry = {
"turn": len(self.conversation_log) + 1,
"scenario_id": scenario_id,
"scenario_name": scenario_name,
"subscenario_id": (
str(getattr(step, "subscenario_id", "")).strip() or None
),
"subscenario_name": (
str(getattr(step, "subscenario_name", "")).strip() or None
),
"step_id": step.step_id,
"question_source": (
(getattr(step, "metadata", {}) or {}).get("question_source")
or ("followup" if "_followup" in str(step.step_id) else "generated")
),
"dedup_retries": int(
(getattr(step, "metadata", {}) or {}).get("dedup_retries") or 0
),
"user_message": action.content,
"bot_response": bot_response,
"bot_response_data": rich_content, # Rich content: maps, images, links, buttons
"source_evidence": source_evidence,
"factuality_context": {
"agent_description_available": bool((bot.description or "").strip()),
"knowledge_boundary_available": bool(self._knowledge_boundary),
"cited_sources_total": len(source_evidence),
"cited_sources_ok": sum(
1 for item in source_evidence if item.get("status") == "ok"
),
},
"memory_hits": memory_hits,
"timestamp": datetime.now().isoformat(),
"goal_progress_delta": 1 if response_useful else 0,
"screenshot": screenshot_path,
"response_useful_for_continuation": response_useful,
# AIS verdict + new dialogic fields (response/expected/intent).
"correctness_label": ais_label_value,
"correctness_reasoning": ais_reasoning_value,
"claims_json": ais_claim_records,
"evidence_pack": evidence_pack,
"intent_label": intent_label_value,
"intent_reasoning": intent_reasoning_value,
"response_type": response_type_value,
"expected_behavior": expected_behavior_value,
"fallback_similarity": fallback_similarity_value,
"matched_fallback": matched_fallback_value,
"actionability_label": actionability_label_value,
"actionability_reasoning": actionability_reasoning_value,
# Flag ereditato dal browser_controller: True se la
# cattura del bot_response è terminata per timeout
"was_truncated_at_capture": bool(bot_response_truncated),
}
self.conversation_log.append(log_entry)
# Persist after every turn so the operator's UI reflects
# progress live (previously persistence was per-scenario,
# making long sessions look stuck for many minutes).
if self._current_result is not None:
try:
self._save_intermediate_results(self._current_result)
except Exception as save_exc: # pragma: no cover
self._emit_log(
"warning",
"engine",
f"Per-turn persistence failed (will retry next turn): {save_exc}",
step_id=step.step_id,
)
self._emit(
{
"type": "turn_verdict",
"turn": log_entry["turn"],
"scenario_id": scenario_id,
"step_id": step.step_id,
"correctness_label": ais_label_value,
"correctness_reasoning": ais_reasoning_value,
"intent_label": intent_label_value,
}
)
self._emit(
{
"type": "memory_hits",
"turn": log_entry["turn"],
"memory_hits": memory_hits,
"count": len(memory_hits),
}
)
# Update scenario tracking
if scenario_id not in self.scenario_results:
self.scenario_results[scenario_id] = {
"name": scenario_name,
"turns": [],
"subscenarios": {},
"status": "in_progress",
"completed": False,
"expected_scope": getattr(step, "expected_scope", "in_scope"),
"outcome_type": None,
"completion_reason": None,
"fallback_detected": False,
"fallback_required": True,
"boundary_violations_count": 0,
"attempts": 0,
}
self.scenario_results[scenario_id]["turns"].append(log_entry)
subscenario_id = str(log_entry.get("subscenario_id") or "").strip()
if subscenario_id:
sub_map = self.scenario_results[scenario_id].setdefault("subscenarios", {})
if subscenario_id not in sub_map:
sub_map[subscenario_id] = {
"name": log_entry.get("subscenario_name") or subscenario_id,
"goal": str(getattr(step, "subscenario_goal", "") or "").strip(),
"turns": [],
"status": "in_progress",
"completed": False,
"outcome_type": None,
"completion_reason": None,
}
sub_map[subscenario_id]["turns"].append(log_entry)
# Update history for next turn
self.last_bot_message = bot_response
self.interaction_history.append(
{
"step_id": step.step_id,
"scenario_id": scenario_id,
"action": action.content,
"response": bot_response,
}
)
# Keep history manageable (last 10 exchanges)
if len(self.interaction_history) > 10:
self.interaction_history = self.interaction_history[-10:]
# Check if bot asked a follow-up question
if self._should_continue_conversation(bot_response, step):
if self._has_reached_message_limit():
self._stop_for_message_limit(result)
return False
console.print(
"[dim]Bot asked a follow-up. Continuing conversation...[/dim]"
)
self._handle_follow_up(bot, persona, step, result)
return True
else:
console.print("[red]No bot response received[/red]")
return False
else:
# No wait needed
console.print("[dim]Skipping response wait[/dim]")
self.interaction_history.append(
{
"step_id": step.step_id,
"scenario_id": scenario_id,
"action": action.content,
"response": None,
}
)
return True
except Exception as e:
console.print(f"[red]Error in turn: {e}[/red]")
return False
def _build_conversation_summary(self) -> str:
"""Build summary of conversation so far."""
if not self.interaction_history:
return "Conversation just started."
lines = ["\n--- Conversation History ---"]
for i, h in enumerate(self.interaction_history[-5:], 1): # Last 5 exchanges
lines.append(f"{i}. User: {h['action'][:50]}...")
if h.get("response"):
lines.append(f" Bot: {h['response'][:50]}...")
lines.append("--- End History ---\n")
return "\n".join(lines)
def _build_scenario_context(self, step) -> str:
"""Build context about current scenario and goal.
CRITICAL INSTRUCTION: After answering a follow-up question,
ALWAYS return to the main scenario goal. Do NOT get lost in endless follow-ups.
"""
lines = []
scenario_id = str(getattr(step, "scenario_id", "unknown"))
is_followup = getattr(step, "is_followup", False)
if hasattr(step, "scenario_name"):
lines.append(f"Current Scenario: {step.scenario_name}")
if hasattr(step, "expected_intent") and step.expected_intent:
lines.append(f"Goal: {step.expected_intent}")
# Add critical instruction about follow-ups
lines.append("")
if is_followup:
# Special instructions for follow-up steps
lines.append("=== ⚠️ THIS IS A FOLLOW-UP RESPONSE ===")
lines.append("The bot asked a clarification question.")
lines.append("1. Answer directly to the question, keeping persona style.")
lines.append("2. DO NOT ask new questions or start new topics.")
lines.append("3. AFTER this response, we will RETURN to the main scenario goal above.")
lines.append("4. Your next action after this MUST be to continue with the scenario.")
lines.append("=== END FOLLOW-UP INSTRUCTIONS ===")
else:
lines.append("=== IMPORTANT INSTRUCTIONS ===")
lines.append("1. Your PRIMARY objective is to achieve the scenario goal above.")
lines.append(
"2. If the bot asks a follow-up question, answer directly in persona style."
)
lines.append(
"3. AFTER answering the follow-up, IMMEDIATELY return to the main scenario goal."
)
lines.append("4. DO NOT let the conversation drift away from testing the scenario.")
lines.append("5. Stay focused: 1 follow-up max, then back to the scenario.")
# Check if we already did a follow-up for this topic
if scenario_id in self._followup_topics:
topics = self._followup_topics[scenario_id]
if topics:
lines.append(
f"6. ALREADY EXPLORED: {', '.join(t[:30] + '...' for t in topics[-2:])}"
)
lines.append(
" → Do NOT explore these topics again. Proceed with main scenario."
)
lines.append("=== END INSTRUCTIONS ===")
# Log scenario goal in real-time
if hasattr(step, "expected_intent") and step.expected_intent:
self._emit(
{
"type": "goal",
"goal": step.expected_intent,
"scenario_id": scenario_id,
"scenario_name": getattr(step, "scenario_name", "Unknown"),
}
)
return "\n".join(lines)
def _should_continue_conversation(self, bot_response: str, step) -> bool:
"""Check if the bot asked a follow-up question that we should answer.
CRITICAL: Only answer 1 follow-up per topic, then return to main scenario.
We want to test scenarios, not get lost in endless follow-ups.
"""
if not bot_response:
return False
scenario_id = str(getattr(step, "scenario_id", "unknown"))
subscenario_id = str(getattr(step, "subscenario_id", "") or "").strip()
followup_policy = self._normalize_followup_policy(
getattr(step, "followup_policy", "limited")
)
followup_max_turns = int(
getattr(step, "followup_max_turns", self._max_followups_per_step)
or self._max_followups_per_step
)
if followup_policy == "forbidden":
self._emit(
{
"type": "followup_check",
"message": "Follow-up disabled by policy (forbidden), proceeding with next planned step",
"step_id": step.step_id,
}
)
return False
# Preserve one message slot for each not-yet-covered scenario.
if self.max_messages:
remaining_budget = max(self.max_messages - self.messages_sent_count, 0)
if remaining_budget <= int(self._reserved_messages_for_future_scenarios or 0):
self._emit(
{
"type": "followup_check",
"message": (
"Skipping follow-up to preserve message budget "
"for remaining scenarios"
),
"step_id": step.step_id,
}
)
return False
# Check if this is already a follow-up step
if "_followup" in str(step.step_id):
# This IS a follow-up - don't do another one, return to scenario
self._emit(
{
"type": "followup_check",
"message": "Already in follow-up, returning to main scenario flow",
"step_id": step.step_id,
}
)
return False
# Check if we already did a follow-up for this step
if scenario_id in self.scenario_results:
turns = self.scenario_results[scenario_id].get("turns", [])
if subscenario_id:
turns = [
turn
for turn in turns
if str(turn.get("subscenario_id", "") or "").strip() == subscenario_id
]
followup_count = sum(1 for t in turns if "_followup" in str(t.get("step_id", "")))
if followup_count >= followup_max_turns:
self._emit(
{
"type": "followup_check",
"message": f"Max follow-ups ({followup_max_turns}) reached for this step, continuing with scenario",
}
)
return False
# Check if this topic was already followed up
current_topic = getattr(step, "expected_intent", "unknown")
if scenario_id in self._followup_topics:
if current_topic in self._followup_topics[scenario_id]:
self._emit(
{
"type": "followup_check",
"message": f"Topic '{current_topic[:30]}...' already explored, continuing with scenario",
}
)
return False
# Check if response ends with a question
response_lower = bot_response.lower()
# Question indicators - keep focused
question_words = [
# Italiano
"ti piacerebbe",
"vorresti",
"puoi dirmi",
"hai bisogno",
"vuoi",
"preferisci",
"potresti",
"ti interessa",
"posso aiutarti",
"come posso",
"dimmi",
"fammi sapere",
"seleziona",
"scegli",
# Inglese
"would you like",
"do you want",
"can you tell me",
"do you need",
"would you prefer",
"are you interested",
"shall i",
"let me know",
"please select",
"choose",
"tell me",
]
# Check for question marks
has_question_mark = "?" in bot_response
# Check for question phrases
has_question_phrase = any(qw in response_lower for qw in question_words)
# Check for interrogative words
interrogative_words = [
"quale",
"quali",
"come",
"dove",
"quando",
"perché",
"perche",
"quanto",
"chi",
"cosa",
"which",
"what",
"how",
"where",
"when",
"why",
]
has_interrogative = any(iw in response_lower for iw in interrogative_words)
# Emittiamo log per debug
self._emit(
{
"type": "followup_check",
"has_question_mark": has_question_mark,
"has_question_phrase": has_question_phrase,
"has_interrogative": has_interrogative,
"response_preview": bot_response[:100],
}
)
# Only continue if there's a clear question
should_continue = has_question_mark or has_question_phrase or has_interrogative
if should_continue and followup_policy == "adaptive":
# Lightweight contribution gate: avoid follow-up loops with generic prompts.
weak_patterns = ("fammi sapere", "let me know", "if needed", "se vuoi")
if any(pattern in response_lower for pattern in weak_patterns):
self._emit(
{
"type": "followup_check",
"message": "Adaptive policy skipped low-value follow-up",
}
)
return False
if should_continue:
# Mark this topic as explored
if scenario_id not in self._followup_topics:
self._followup_topics[scenario_id] = []
if current_topic not in self._followup_topics[scenario_id]:
self._followup_topics[scenario_id].append(current_topic)
self._emit(
{
"type": "followup_check",
"message": f"Will answer 1 follow-up for '{current_topic[:30]}...' then return to scenario",
}
)
return should_continue
def _handle_follow_up(self, bot: Bot, persona: Persona, step, result: TestResult) -> bool:
"""Handle follow-up question from bot.
CRITICAL: Answer the follow-up directly, then return to main scenario.
"""
try:
console.print("[bold yellow]🔄 Handling bot follow-up question...[/bold yellow]")
# Emit that we're handling a follow-up
self._emit(
{
"type": "followup",
"message": "🔄 Bot asked a follow-up. Will answer briefly then return to scenario.",
"step_id": step.step_id,
}
)
# Wait a bit for natural flow
time.sleep(random.uniform(1.0, 2.0))
# Create a new step for the follow-up
from ..models import Step
follow_up_step = Step(
step_id=f"{step.step_id}_followup_{int(time.time())}", # Unique ID
action_type=step.action_type,
content="", # Will be decided by AI
expected_intent=getattr(step, "expected_intent", ""),
wait_for_response=True,
metadata={"question_source": "followup", "dedup_retries": 0},
)
follow_up_step.scenario_id = str(getattr(step, "scenario_id", "unknown"))
follow_up_step.scenario_name = getattr(step, "scenario_name", "Unknown")
follow_up_step.subscenario_id = (
str(getattr(step, "subscenario_id", "") or "").strip() or None
)
follow_up_step.subscenario_name = (
str(getattr(step, "subscenario_name", "") or "").strip() or None
)
follow_up_step.subscenario_goal = (
str(getattr(step, "subscenario_goal", "") or "").strip() or None
)
follow_up_step.followup_policy = self._normalize_followup_policy(
getattr(step, "followup_policy", "limited")
)
follow_up_step.followup_max_turns = int(
getattr(step, "followup_max_turns", self._max_followups_per_step)
or self._max_followups_per_step
)
follow_up_step.is_followup = True # Mark as follow-up
follow_up_step.parent_step_id = step.step_id # Track parent
console.print(f"[dim]Created follow-up step: {follow_up_step.step_id}[/dim]")
# Execute the follow-up turn
success = self._execute_conversation_turn(bot, persona, follow_up_step, result)
if self._disarm_turn_watchdog():
# Watchdog fired during the follow-up turn — treat as failed.
success = False
self._emit_log(
"warning",
"engine",
"Follow-up turn aborted by watchdog.",
step_id=follow_up_step.step_id,
)
if success:
console.print(
"[bold green]✅ Follow-up handled. Returning to main scenario...[/bold green]"
)
self._emit(
{
"type": "followup",
"message": "✅ Follow-up completed. Continuing with main scenario.",
"step_id": step.step_id,
}
)
else:
console.print("[bold red]❌ Follow-up handling failed[/bold red]")
return success
except Exception as e:
console.print(f"[bold red]Follow-up handling error: {e}[/bold red]")
import traceback
console.print(f"[red]{traceback.format_exc()}[/red]")
return False
def _perform_action(self, action) -> bool:
"""Execute action on browser."""
if not self.browser:
return False
if action.action_type in [ActionType.SEND_MESSAGE, ActionType.TYPE]:
if not action.content:
return False
return self.browser.send_message(action.content, human_like=True)
elif action.action_type == ActionType.CLICK:
if not action.selector:
return False
return self.browser.click_element(action.selector)
elif action.action_type == ActionType.WAIT:
try:
wait_time = float(action.content) if action.content else 2.0
time.sleep(wait_time)
return True
except ValueError:
time.sleep(2.0)
return True
return False
def _load_knowledge_boundary(self, bot: Bot):
"""Load knowledge boundary once per session run."""
boundary_url = getattr(bot, "knowledge_boundary_url", None)
if not boundary_url:
return None
try:
boundary = fetch_duolly_boundary(str(boundary_url))
if boundary:
self._emit(
{
"type": "log",
"level": "info",
"message": f"Knowledge boundary loaded: {str(boundary_url)}",
}
)
return boundary
self._emit(
{
"type": "log",
"level": "warning",
"message": f"Knowledge boundary unavailable: {str(boundary_url)}",
}
)
except Exception as exc:
self._emit(
{
"type": "log",
"level": "warning",
"message": f"Knowledge boundary error: {str(exc)[:180]}",
}
)
return None
def _collect_source_evidence(self, rich_content: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Fetch excerpts from cited links in bot rich content."""
links = []
if isinstance(rich_content, dict):
links = rich_content.get("links") or []
if links:
self._emit(
{
"type": "log",
"level": "info",
"message": f"Factuality link candidates detected: {len(links)}",
}
)
else:
self._emit(
{
"type": "log",
"level": "warning",
"message": "Factuality link candidates detected: 0 (no cited links found in response/aside)",
}
)
evidence = self._source_fetcher.collect_from_links(links)
if evidence:
ok_count = sum(1 for item in evidence if item.get("status") == "ok")
self._emit(
{
"type": "log",
"level": "info",
"message": (
f"Factuality sources: {ok_count}/{len(evidence)} readable "
f"(max {self._source_fetcher.max_sources_per_turn} per turn)"
),
}
)
return evidence
def _retrieve_memory_hits(self, *, bot: Bot, query: str) -> List[Dict[str, Any]]:
workspace_id = (
getattr(self.current_session, "workspace_id", None) if self.current_session else None
)
if not workspace_id or not str(query or "").strip():
return []
try:
return knowledge_memory_service.retrieve(
workspace_id=workspace_id,
bot_id=bot.id,
query=query,
top_k=self._memory_top_k,
source_scope="active",
)
except Exception as exc:
self._emit(
{
"type": "log",
"level": "warning",
"message": f"Knowledge memory retrieval error: {str(exc)[:180]}",
}
)
return []
def _build_factuality_sources(
self,
bot: Bot,
source_evidence: List[Dict[str, Any]],
memory_hits: Optional[List[Dict[str, Any]]] = None,
) -> List[Dict[str, Any]]:
"""Build normalized source payload for the AIS turn evaluator."""
sources: List[Dict[str, Any]] = []
agent_description = (getattr(bot, "description", None) or "").strip()
if agent_description:
sources.append(
{
"source_id": "AGENT_DESC",
"source_type": "agent_description",
"title": "AI Agent description",
"url": None,
"content": agent_description[:2500],
}
)
if self._knowledge_boundary:
sources.append(
{
"source_id": "BOUNDARY",
"source_type": "knowledge_boundary",
"title": "Knowledge boundary",
"url": getattr(self._knowledge_boundary, "source_url", None),
"content": (getattr(self._knowledge_boundary, "content_raw", "") or "")[:4000],
}
)
for idx, item in enumerate(source_evidence, start=1):
status = str(item.get("status") or "").strip().lower()
excerpt = str(item.get("excerpt") or "").strip()
source_id = f"SRC_{idx}"
content = excerpt
if not content:
error = str(item.get("error") or "unavailable").strip()
content = f"[SOURCE_UNAVAILABLE] status={status or 'unknown'}; error={error}"
elif len(content) < 80:
# SPA JS-rendered: il fetch HTTP ritorna solo lo skeleton
# ("Skip to main content" o div vuoti) → ~15-30 char.
# Marcando come UNAVAILABLE, la SRC non viene contata come
# "real source" e il judge ricade sui MEM_n del RAG, evitando
# falsi unsupported quando il bot cita una pagina SPA.
content = (
f"[SOURCE_UNAVAILABLE] status=spa_or_thin_content; "
f"error=Fetched HTML had no readable text ({len(excerpt)} chars). "
"Probabile pagina SPA: il content è renderizzato lato client."
)
sources.append(
{
"source_id": source_id,
"source_type": "cited_source",
"title": item.get("title") or f"Cited source {idx}",
"url": item.get("url"),
"fetch_status": status or "unknown",
"content": content,
}
)
for idx, hit in enumerate(memory_hits or [], start=1):
snippet = str(hit.get("snippet") or "").strip()
if not snippet:
continue
sources.append(
{
"source_id": f"MEM_{idx}",
"source_type": "knowledge_memory",
"title": hit.get("title") or hit.get("source_name") or f"Memory source {idx}",
"url": hit.get("url"),
"fetch_status": "indexed",
"content": snippet[:1800],
}
)
return sources
def _auto_generate_steps_for_scenario(self, scenario: Scenario) -> List[Any]:
"""Auto-generate steps for a scenario (supports subscenario sequencing)."""
from ..models import Step
goal = scenario.description or f"Test {scenario.name}"
session_critical = list(getattr(self.current_session, "critical_questions", []) or [])
steps: List[Any] = []
subscenarios = sorted(
list(getattr(scenario, "subscenarios", []) or []),
key=lambda sub: (
int(getattr(sub, "priority", 1) or 1),
str(getattr(sub, "name", "") or ""),
),
)
if subscenarios:
step_counter = 1
for sub_index, subscenario in enumerate(subscenarios):
sub_goal = str(getattr(subscenario, "goal", "") or "").strip() or goal
sub_name = str(getattr(subscenario, "name", "") or "").strip() or scenario.name
sub_seed_questions = [
str(item).strip()
for item in (getattr(subscenario, "seed_questions", []) or [])
if str(item).strip()
]
effective_seed = sub_seed_questions or list(
getattr(scenario, "seed_questions", []) or []
)
effective_critical = session_critical if sub_index == 0 else []
max_questions = 2 if len(subscenarios) == 1 else 1
plan = self.question_planner.build(
critical_questions=effective_critical,
seed_questions=effective_seed,
scenario_name=f"{scenario.name} / {sub_name}",
scenario_goal=sub_goal,
max_questions=max_questions,
)
if not plan:
plan = self.question_planner.build(
critical_questions=[],
seed_questions=[],
scenario_name=f"{scenario.name} / {sub_name}",
scenario_goal=sub_goal,
max_questions=max_questions,
)
for question in plan:
step = Step(
step_id=f"{scenario.id}_{step_counter}",
action_type=ActionType.SEND_MESSAGE,
content=question.text,
expected_intent=sub_goal,
wait_for_response=True,
metadata={
"question_source": question.source,
"dedup_retries": question.dedup_retries,
"subscenario_id": str(subscenario.id),
"subscenario_name": sub_name,
},
)
step.subscenario_id = str(subscenario.id)
step.subscenario_name = sub_name
step.subscenario_goal = sub_goal
step.followup_policy = self._normalize_followup_policy(
getattr(subscenario, "followup_policy", None)
or getattr(scenario, "followup_policy", "limited")
)
step.followup_max_turns = int(
getattr(subscenario, "followup_max_turns", None)
or getattr(scenario, "followup_max_turns", self._max_followups_per_step)
or self._max_followups_per_step
)
steps.append(step)
step_counter += 1
return steps
plan = self.question_planner.build(
critical_questions=session_critical,
seed_questions=list(getattr(scenario, "seed_questions", []) or []),
scenario_name=scenario.name,
scenario_goal=goal,
max_questions=2,
)
if not plan:
plan = self.question_planner.build(
critical_questions=[],
seed_questions=[],
scenario_name=scenario.name,
scenario_goal=goal,
max_questions=2,
)
for idx, question in enumerate(plan, start=1):
step = Step(
step_id=f"{scenario.id}_{idx}",
action_type=ActionType.SEND_MESSAGE,
content=question.text,
expected_intent=goal,
wait_for_response=True,
metadata={
"question_source": question.source,
"dedup_retries": question.dedup_retries,
},
)
steps.append(step)
return steps
def _normalize_followup_policy(self, value: Any) -> str:
"""Normalize follow-up policy values coming from enums/string payloads."""
raw = value.value if hasattr(value, "value") else value
normalized = str(raw or "limited").strip().lower()
if "." in normalized:
normalized = normalized.split(".")[-1]
if normalized not in {"forbidden", "limited", "adaptive"}:
return "limited"
return normalized
def _infer_scope_expectation(self, scenario: Scenario) -> str:
"""Infer if the scenario is expected in-scope or out-of-scope."""
return self._infer_scope_expectation_for_components(
success_criteria=getattr(scenario, "success_criteria", None),
category=(getattr(scenario, "category", "") or ""),
name=(scenario.name or ""),
description=(scenario.description or ""),
tags=list(getattr(scenario, "tags", []) or []),
)
def _infer_scope_expectation_for_components(
self,
*,
success_criteria: Optional[Any],
category: str,
name: str,
description: str,
tags: List[str],
) -> str:
"""Infer scope expectation from explicit criteria and textual markers."""
explicit_scope = (
str(getattr(success_criteria, "scope_expectation", "auto")).strip().lower()
if success_criteria
else "auto"
)
if explicit_scope in ("in_scope", "out_of_scope"):
return explicit_scope
normalized_category = str(category or "").lower()
normalized_tags = [str(t).lower() for t in (tags or []) if isinstance(t, str)]
normalized_name = str(name or "").lower()
normalized_description = str(description or "").lower()
searchable = " ".join(
[normalized_category, normalized_name, normalized_description] + normalized_tags
)
out_of_scope_markers = (
"out_of_scope",
"out-of-scope",
"oos",
"fallback_expected",
"knowledge_boundary_negative",
"fuori scope",
"fuori_scopo",
)
in_scope_markers = ("in_scope", "in-scope", "in scope", "dentro scope")
if any(marker in searchable for marker in out_of_scope_markers):
return "out_of_scope"
if any(marker in searchable for marker in in_scope_markers):
return "in_scope"
return "in_scope"
def _effective_fallbacks_for(
self,
step: Optional[Any] = None,
scenario: Optional[Scenario] = None,
subscenario: Optional[Any] = None,
lowercase: bool = False,
) -> List[str]:
"""Resolve effective fallback markers per il contesto di questo step.
Fix 2026-05-17 (audit pipeline fallback): unifica bot + scenario
+ subscenario + session usando `collect_effective_fallbacks`.
Prima il live judge riceveva SOLO bot.deterministic_fallbacks,
ignorando i marker scenario/sub/session-level → doppia verità
outcome (heuristic) vs AIS label (judge).
Argomenti:
step: oggetto step con eventuali ref `_scenario_obj`/
`_subscenario_obj` allegati da `run_multi_scenario_test`.
Se None, usa scenario/subscenario passati esplicitamente.
scenario, subscenario: override espliciti (utile da context
diversi dal main loop).
lowercase: se True normalizza tutto in lowercase (usato
dall'heuristic detector che fa matching `in` su lower).
Backward compat: se `_current_bot` non è stato impostato (test
legacy che bypassano `run_multi_scenario_test`), pesca i marker
bot da `_agent_deterministic_fallbacks` (vecchia interfaccia).
"""
scen = scenario or getattr(step, "_scenario_obj", None) if step else scenario
sub = subscenario or (getattr(step, "_subscenario_obj", None) if step else subscenario)
from src.utils.fallback_resolution import collect_effective_fallbacks
bot_obj = getattr(self, "_current_bot", None)
if bot_obj is None and getattr(self, "_agent_deterministic_fallbacks", None):
# Legacy path: nessun bot object disponibile, ma il chiamante
# ha popolato _agent_deterministic_fallbacks. Creiamo un
# SimpleNamespace al volo per il helper.
from types import SimpleNamespace
bot_obj = SimpleNamespace(
deterministic_fallbacks=list(self._agent_deterministic_fallbacks)
)
return collect_effective_fallbacks(
bot=bot_obj,
scenario=scen,
subscenario=sub,
session=getattr(self, "current_session", None),
lowercase=lowercase,
)
def _is_fallback_response(
self,
response: str,
scenario: Optional[Scenario] = None,
success_criteria: Optional[Any] = None,
) -> bool:
"""Detect safe fallback responses for out-of-scope queries.
Generic hardcoded markers + tutti i marker custom (bot, scenario,
subscenario, session) risolti via `_effective_fallbacks_for`.
"""
if not response:
return False
response_lower = response.lower()
# Hardcoded baseline (lingua-aware: IT + EN). Restano qui perché
# sono pattern universali di refusal/limits che non dipendono dal
# bot specifico.
fallback_markers = [
"non posso rispondere",
"non posso aiutarti su questo",
"non ho informazioni",
"non dispongo di informazioni",
"non rientra nelle mie competenze",
"non rientra nel mio ambito",
"fuori dal mio scope",
"fuori dal mio ambito",
"non sono autorizzato",
"non posso fornire",
"i don't have enough information",
"i cannot answer",
"outside my scope",
"outside my knowledge",
]
# Custom markers da bot/scenario/sub/session — risolti dal helper
# centralizzato (2026-05-17). Quando success_criteria è passato
# esplicitamente (chiamata legacy), la usiamo direttamente; in
# tutti gli altri casi pesca dal contesto corrente.
if success_criteria is not None:
custom_markers = getattr(success_criteria, "fallback_markers", None)
if custom_markers is None and isinstance(success_criteria, dict):
custom_markers = success_criteria.get("fallback_markers")
for marker in (custom_markers or []):
m = str(marker).strip().lower()
if m:
fallback_markers.append(m)
# Aggiungi i marker effettivi (bot + scenario + sub + session)
fallback_markers.extend(
self._effective_fallbacks_for(scenario=scenario, lowercase=True)
)
return any(marker in response_lower for marker in fallback_markers)
def _count_boundary_violations(self, turns: List[Dict[str, Any]]) -> int:
"""Boundary violations are no longer derived from per-turn 5D scores.
Kept as zero for callers that still consult this counter; AIS labels
('not_attributable', 'inappropriate_fallback') are the new source of truth.
"""
return 0
def _check_goal_completion_from_turns(
self,
goal: str,
scenario_turns: List[Dict[str, Any]],
) -> bool:
"""Evaluate goal completion using a normalized turn slice."""
if not scenario_turns:
return False
goal_lower = str(goal or "").lower()
goal_keywords = self._extract_goal_keywords(goal)
last_bot_response = str(scenario_turns[-1].get("bot_response", "") or "").lower()
keyword_matches = sum(1 for kw in goal_keywords if kw in last_bot_response)
keyword_coverage = keyword_matches / len(goal_keywords) if goal_keywords else 0
if keyword_coverage >= 0.3:
return True
completion_indicators = [
"is ready",
"has been created",
"here is",
"ti presento",
"puoi trovare",
"è disponibile",
"ecco",
"done",
"completato",
"puoi partire",
"buon viaggio",
"have a good trip",
]
if any(ind in last_bot_response for ind in completion_indicators):
return True
if any(
marker in last_bot_response
for marker in ["€", "$", "euro", "dollar", "price", "cost", "prezzo"]
):
if "booking" in goal_lower or "reservation" in goal_lower or "itinerary" in goal_lower:
return True
return self._analyze_rich_content(scenario_turns, goal_lower)
def _evaluate_turn_group_outcome(
self,
*,
turns: List[Dict[str, Any]],
scope_expectation: str,
success_criteria: Optional[Any],
goal: str,
attempt_success: bool,
label: str,
) -> Dict[str, Any]:
"""Evaluate outcome for a scenario or subscenario turn group."""
fallback_required = (
bool(getattr(success_criteria, "fallback_required_if_out_of_scope", True))
if success_criteria
else True
)
if not attempt_success or not turns:
if scope_expectation == "out_of_scope":
return {
"passed": False,
"outcome_type": "out_of_scope_fallback_fail",
"reason": f"No valid response captured for {label} out-of-scope validation",
"fallback_detected": False,
"boundary_violations_count": 0,
"fallback_required": fallback_required,
}
return {
"passed": False,
"outcome_type": "in_scope_fail",
"reason": f"No valid response captured for {label} in-scope validation",
"fallback_detected": False,
"boundary_violations_count": 0,
"fallback_required": fallback_required,
}
last_response = str(turns[-1].get("bot_response", "") or "")
fallback_detected = self._is_fallback_response(
last_response,
success_criteria=success_criteria,
)
boundary_violations_count = self._count_boundary_violations(turns)
if scope_expectation == "out_of_scope":
passed = (
(fallback_detected and boundary_violations_count == 0)
if fallback_required
else boundary_violations_count == 0
)
reason = (
"Fallback response detected for out-of-scope request"
if passed and fallback_required
else (
"No boundary violations detected for out-of-scope request"
if passed
else "Fallback missing or boundary violation detected"
)
)
return {
"passed": passed,
"outcome_type": (
"out_of_scope_fallback_pass" if passed else "out_of_scope_fallback_fail"
),
"reason": reason,
"fallback_detected": fallback_detected,
"boundary_violations_count": boundary_violations_count,
"fallback_required": fallback_required,
}
# Criterio principale in-scope: intent satisfaction prodotto dal
# judge. È l'unico segnale che valuta semanticamente "il bot ha
# davvero risposto a quello che il sub-scenario chiedeva?".
# Il vecchio `_check_goal_completion_from_turns` faceva text-matching
# euristico tra goal e response: troppo brittle (passava risposte
# tangenti, falliva risposte corrette ma riformulate).
intent_labels = [
str(t.get("intent_label") or "").strip().lower()
for t in turns
]
intent_labels = [lab for lab in intent_labels if lab and lab != "not_applicable"]
if intent_labels:
satisfied_or_partial = sum(1 for lab in intent_labels if lab in {"satisfied", "partial"})
not_satisfied = sum(1 for lab in intent_labels if lab == "not_satisfied")
# Pass se almeno un turno ha soddisfatto (anche parziale) l'intent
# E nessun turno è stato esplicitamente classificato not_satisfied
# E non ci sono violazioni di boundary.
intent_passed = satisfied_or_partial > 0 and not_satisfied == 0
passed = intent_passed and boundary_violations_count == 0
if passed:
reason = (
f"Intent soddisfatto: {satisfied_or_partial}/{len(intent_labels)} "
"turni con intent_label satisfied/partial."
)
elif not_satisfied > 0:
reason = (
f"Intent non soddisfatto: {not_satisfied} turno/i marcati "
"not_satisfied dal judge."
)
elif boundary_violations_count > 0:
reason = "Violazione di boundary rilevata (intent ignorato)."
else:
reason = "Nessun turno ha soddisfatto l'intent."
return {
"passed": passed,
"outcome_type": "in_scope_pass" if passed else "in_scope_fail",
"reason": reason,
"fallback_detected": fallback_detected,
"boundary_violations_count": boundary_violations_count,
"fallback_required": fallback_required,
}
# Fallback: nessun turno è stato valutato dal judge (TurnEvaluator
# spento o errore). Tornano al vecchio criterio testuale per non
# bloccare le sessioni dove l'evaluator non è girato.
goal_completed = self._check_goal_completion_from_turns(goal, turns)
passed = goal_completed and boundary_violations_count == 0
return {
"passed": passed,
"outcome_type": "in_scope_pass" if passed else "in_scope_fail",
"reason": (
"Goal achieved within in-scope expectations (heuristic — judge non disponibile)"
if passed
else "Goal not achieved or boundary violation detected (heuristic — judge non disponibile)"
),
"fallback_detected": fallback_detected,
"boundary_violations_count": boundary_violations_count,
"fallback_required": fallback_required,
}
def _evaluate_scenario_outcome(
self,
scenario: Scenario,
attempt_success: bool,
) -> Dict[str, Any]:
"""Evaluate scenario outcome with in-scope/out-of-scope semantics."""
scenario_id = str(scenario.id)
scenario_turns = [
turn
for turn in self.conversation_log
if str(turn.get("scenario_id", "")) == scenario_id
]
subscenarios = sorted(
list(getattr(scenario, "subscenarios", []) or []),
key=lambda sub: (
int(getattr(sub, "priority", 1) or 1),
str(getattr(sub, "name", "") or ""),
),
)
if subscenarios:
subscenario_outcomes: Dict[str, Dict[str, Any]] = {}
for subscenario in subscenarios:
sub_id = str(getattr(subscenario, "id"))
sub_name = str(getattr(subscenario, "name", "") or sub_id).strip()
sub_goal = str(
getattr(subscenario, "goal", "") or scenario.description or scenario.name
).strip()
sub_turns = [
turn
for turn in scenario_turns
if str(turn.get("subscenario_id", "") or "").strip() == sub_id
]
sub_criteria = getattr(subscenario, "success_criteria", None) or getattr(
scenario, "success_criteria", None
)
sub_scope = self._infer_scope_expectation_for_components(
success_criteria=sub_criteria,
category=(getattr(scenario, "category", "") or ""),
name=sub_name,
description=sub_goal,
tags=list(getattr(scenario, "tags", []) or []),
)
sub_outcome = self._evaluate_turn_group_outcome(
turns=sub_turns,
scope_expectation=sub_scope,
success_criteria=sub_criteria,
goal=sub_goal,
attempt_success=attempt_success,
label=f"subscenario '{sub_name}'",
)
sub_outcome["name"] = sub_name
sub_outcome["goal"] = sub_goal
subscenario_outcomes[sub_id] = sub_outcome
all_passed = bool(subscenario_outcomes) and all(
bool(item.get("passed")) for item in subscenario_outcomes.values()
)
total_boundary_violations = sum(
int(item.get("boundary_violations_count", 0) or 0)
for item in subscenario_outcomes.values()
)
fallback_detected_any = any(
bool(item.get("fallback_detected")) for item in subscenario_outcomes.values()
)
fallback_required_all = all(
bool(item.get("fallback_required", True)) for item in subscenario_outcomes.values()
)
first_failure = next(
(item for item in subscenario_outcomes.values() if not bool(item.get("passed"))),
None,
)
if all_passed:
return {
"passed": True,
"outcome_type": "in_scope_pass",
"reason": "All subscenarios completed successfully",
"fallback_detected": fallback_detected_any,
"boundary_violations_count": total_boundary_violations,
"fallback_required": fallback_required_all,
"subscenario_outcomes": subscenario_outcomes,
}
return {
"passed": False,
"outcome_type": (
"out_of_scope_fallback_fail"
if first_failure
and str(first_failure.get("outcome_type", "")).startswith("out_of_scope")
else "in_scope_fail"
),
"reason": (
f"Subscenario failed: {first_failure.get('name')}. "
f"{str(first_failure.get('reason') or '').strip()}"
if first_failure
else "At least one subscenario failed"
),
"fallback_detected": fallback_detected_any,
"boundary_violations_count": total_boundary_violations,
"fallback_required": fallback_required_all,
"subscenario_outcomes": subscenario_outcomes,
}
scope_expectation = self._infer_scope_expectation(scenario)
success_criteria = getattr(scenario, "success_criteria", None)
goal = str(scenario.description or scenario.name or "").strip()
return self._evaluate_turn_group_outcome(
turns=scenario_turns,
scope_expectation=scope_expectation,
success_criteria=success_criteria,
goal=goal,
attempt_success=attempt_success,
label=f"scenario '{scenario.name}'",
)
def _check_scenario_completion(self, scenario: Scenario, attempt_success: bool) -> bool:
"""
Check if a scenario has been completed successfully.
Uses AI to evaluate if the bot's responses satisfy the scenario goal.
Also analyzes rich content (maps, images, links) in responses.
"""
if not attempt_success:
return False
scenario_id = str(scenario.id)
# Get conversation history for this scenario
scenario_turns = []
for turn in self.conversation_log:
if turn.get("scenario_id") == scenario_id or turn.get("scenario_id") == str(
scenario_id
):
scenario_turns.append(turn)
if not scenario_turns:
return False
goal = scenario.description or scenario.name
return self._check_goal_completion_from_turns(goal, scenario_turns)
def _analyze_rich_content(self, scenario_turns: List[Dict], goal_lower: str) -> bool:
"""Analyze rich content (maps, images, links) in bot responses."""
# Collect all rich content from bot responses
all_maps = []
all_images = []
all_links = []
all_buttons = []
for turn in scenario_turns:
bot_response_data = turn.get("bot_response_data")
if isinstance(bot_response_data, dict):
if bot_response_data.get("has_map"):
all_maps.append(turn.get("bot_response", ""))
if bot_response_data.get("has_image"):
all_images.append(turn.get("bot_response", ""))
if bot_response_data.get("links"):
all_links.extend(bot_response_data.get("links", []))
if bot_response_data.get("buttons"):
all_buttons.extend(bot_response_data.get("buttons", []))
# Check if goal requires location/directions and map was provided
if any(
kw in goal_lower
for kw in [
"dove",
"where",
"posizione",
"location",
"indirizzo",
"address",
"mappa",
"map",
]
):
if all_maps:
console.print(
"[green]Goal completion detected (map provided for location query)[/green]"
)
return True
# Check if goal requires visual info and image was provided
if any(
kw in goal_lower
for kw in ["foto", "photo", "image", "immagine", "vedere", "see", "look"]
):
if all_images:
console.print(
"[green]Goal completion detected (image provided for visual query)[/green]"
)
return True
# Check if goal requires navigation/action and buttons were provided
if any(
kw in goal_lower
for kw in ["prenotare", "book", "acquistare", "buy", "procedere", "proceed"]
):
if all_buttons:
console.print("[green]Goal completion detected (action buttons provided)[/green]")
return True
# Check if goal requires external resources and links were provided
if any(kw in goal_lower for kw in ["link", "url", "sito", "website", "pagina", "page"]):
if all_links:
console.print("[green]Goal completion detected (links provided)[/green]")
return True
# General: if response contains rich content and matches goal type
if all_maps and any(
kw in goal_lower
for kw in ["itinerario", "itinerary", "percorso", "route", "viaggio", "trip"]
):
console.print("[green]Goal completion detected (itinerary map provided)[/green]")
return True
return False
def _extract_goal_keywords(self, goal: str) -> List[str]:
"""Extract important keywords from scenario goal."""
# Simple keyword extraction - remove common words and keep important terms
common_words = {
"the",
"a",
"an",
"and",
"or",
"to",
"in",
"on",
"at",
"for",
"with",
"of",
"is",
"are",
"be",
"this",
"that",
"i",
"want",
"need",
"would",
"like",
"can",
"you",
"help",
"me",
"un",
"una",
"e",
"o",
"il",
"la",
"di",
"per",
"con",
"vorrei",
"mi",
"puoi",
"aiutare",
}
words = goal.lower().split()
keywords = [
w.strip(".,;!?") for w in words if w.strip(".,;!?") not in common_words and len(w) > 2
]
return keywords[:10] # Max 10 keywords
def _convert_log_to_steps(self) -> List[Dict[str, Any]]:
"""Convert conversation log to steps_results format for report compatibility."""
steps = []
for turn in self.conversation_log:
step = {
"step_id": turn.get("step_id", f"turn_{turn.get('turn', 0)}"),
"action": "send_message",
"content": turn.get("user_message", ""),
"bot_response": turn.get("bot_response", ""),
"expected_intent": turn.get("scenario_name", ""),
"success": turn.get("bot_response") is not None
and len(turn.get("bot_response", "")) > 0,
"response_time_ms": None, # Could be calculated if we track timestamps
"rag_faithfulness": None,
"tone_match": None,
"intent_match": None,
"sentiment_score": None,
"sentiment_label": None,
"screenshot": turn.get("screenshot"),
}
steps.append(step)
return steps
def _save_intermediate_results(self, result: TestResult):
"""Save intermediate results to ensure data persistence even if session fails."""
try:
# Update result object with current state
result.conversation_log = json.dumps(
self.conversation_log, ensure_ascii=False, default=str
)
result.scenario_results = self.scenario_results
# Convert conversation log to steps_results for report compatibility
result.steps_results = self._convert_log_to_steps()
# Calculate current stats
total_turns = len(self.conversation_log)
completed_scenarios = (
sum(1 for s in result.scenario_results.values() if s.get("completed", False))
if result.scenario_results
else 0
)
# Update result metrics
result.total_steps = total_turns
result.passed_steps = sum(1 for s in result.steps_results if s.get("success"))
result.failed_steps = result.total_steps - result.passed_steps
# Use save callback if available (for DB persistence)
if self.save_callback:
try:
self.save_callback(result)
console.print(
f"[dim]💾 Saved to database: {total_turns} turns, {completed_scenarios} scenarios completed[/dim]"
)
except Exception as cb_err:
console.print(f"[yellow]Save callback error: {cb_err}[/yellow]")
# Emit save event for real-time tracking
self._emit(
{
"type": "data_saved",
"turns_recorded": total_turns,
"scenarios_completed": completed_scenarios,
"timestamp": datetime.now().isoformat(),
}
)
console.print(
f"[dim]💾 Saved intermediate results: {total_turns} turns, {result.passed_steps} passed[/dim]"
)
except Exception as e:
console.print(f"[yellow]Warning: Could not save intermediate results: {e}[/yellow]")
"""
Test Engine V3 - Realistic conversation flow, no contamination.
"""
import json
import random
import time
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from rich.console import Console
from rich.panel import Panel
from ..models import ActionType, Bot, Persona, Scenario, TestResult, TestSession
from ..utils.env import env_float, env_int
from ..utils.logging import get_logger
from .ai_client import AIClient
from .browser_controller import BrowserController
from .knowledge_boundary import fetch_duolly_boundary
from .knowledge_memory import knowledge_memory_service
from .question_planner import QuestionPlanner
from .rag_evaluator import RAGEvaluator
from .response_usefulness import is_response_useful_for_continuation
from .source_evidence import SourceEvidenceFetcher
from .tone_evaluator import ToneEvaluator
from .turn_evaluator import TurnEvaluator
from .turn_watchdog import TurnWatchdog
logger = get_logger(__name__)
console = Console()
class BotResponse:
"""Risposta del bot con contenuti testuali e non testuali."""
text: str = ""
has_map: bool = False
has_image: bool = False
has_link: bool = False
has_button: bool = False
has_list: bool = False
has_table: bool = False
links: List[Any] = field(default_factory=list)
buttons: List[str] = field(default_factory=list)
raw_html: str = ""
def has_rich_content(self) -> bool:
"""Verifica se la risposta contiene contenuti non testuali."""
return (
self.has_map
or self.has_image
or self.has_link
or self.has_button
or self.has_list
or self.has_table
)
def to_text(self) -> str:
"""Restituisce il testo completo per backward compatibility."""
parts = [self.text]
if self.has_map:
parts.append("[Mappa fornita]")
if self.has_image:
parts.append("[Immagine fornita]")
if self.links:
rendered_links = []
for link in self.links:
if isinstance(link, dict):
title = str(link.get("title") or "").strip()
url = str(link.get("url") or "").strip()
rendered_links.append(f"{title} ({url})" if title else url)
else:
rendered_links.append(str(link))
parts.append(f"[Links: {', '.join(rendered_links)}]")
if self.buttons:
parts.append(f"[Bottoni: {', '.join(self.buttons)}]")
return " ".join(parts)
class TestEngine:
"""Test engine with realistic conversation flow."""
def __init__(
self,
ai_client: AIClient,
rag_evaluator: RAGEvaluator,
tone_evaluator: ToneEvaluator,
turn_evaluator: Optional[TurnEvaluator] = None,
output_dir: str = "./output",
event_handler: Optional[Callable[[Dict[str, Any]], None]] = None,
stop_requested: Optional[Callable[[], bool]] = None,
save_callback: Optional[Callable[[TestResult], None]] = None,
max_messages: Optional[int] = None,
persona_system_prompt_override: Optional[str] = None,
):
self.ai_client = ai_client