Spaces:
Runtime error
Runtime error
Download src/core/browser_controller.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 120 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/browser_controller.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/core/browser_controller.py
-
curl -L -o browser_controller.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/browser_controller.py
120 kB
"""
Playwright wrapper for browser automation with human-like interaction.
REFACTORED: Improved response synchronization with message fingerprinting.
"""
import hashlib
import io
import os
import random
import re
import subprocess
import sys
import threading
import time
from collections import Counter
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
from urllib.parse import urljoin
from playwright.sync_api import (
Browser,
BrowserContext,
Error as PlaywrightError,
Frame,
Page,
TimeoutError as PlaywrightTimeoutError,
sync_playwright,
)
from rich.console import Console
from ..utils.env import env_bool, env_int, env_str
from ..utils.selectors import normalize_selector_value
console = Console()
# Lazy import del sanitizer HTML — `nh3` è un binding Rust (Ammonia di Mozilla)
# usato per pulire il raw HTML estratto dal widget del bot prima di salvarlo
# e prima di farlo viaggiare via WebSocket / API. Se nh3 non è installato
# (es. wheel mancante su una piattaforma esotica) facciamo fallback elegante a
# `_sanitize_bot_html_fallback` che ritorna stringa vuota — i template
# renderizzano comunque il plain text. Vedi requirements.txt / pyproject.toml.
try:
import nh3 as _nh3 # type: ignore
except Exception: # pragma: no cover - lib missing on this environment
_nh3 = None
# Whitelist conservativa di tag/attributi consentiti nelle risposte bot.
# Pensata per coprire la formattazione che i widget di chat producono di solito
# (bold, italico, liste, link, codice, headings di basso livello, tabelle
# semplici) escludendo tutto ciò che potrebbe iniettare JS o caricare risorse
# esterne (script, style, iframe, img, video, form, input).
_BOT_HTML_ALLOWED_TAGS = {
"p", "br", "hr", "span", "div",
"b", "strong", "i", "em", "u", "s", "del", "ins", "mark", "sup", "sub",
"a",
"ul", "ol", "li",
"blockquote", "code", "pre", "kbd", "samp",
"h1", "h2", "h3", "h4", "h5", "h6",
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption",
}
_BOT_HTML_ALLOWED_ATTRS = {
# NB: `rel` su <a> non va in whitelist quando passiamo `link_rel` a nh3 —
# il sanitizer lo gestisce da solo (riscrive sempre rel="noopener
# noreferrer"). Se metti "rel" qui, nh3 solleva ValueError.
"a": {"href", "title", "target"},
"span": {"class"},
"div": {"class"},
"th": {"colspan", "rowspan", "scope"},
"td": {"colspan", "rowspan"},
"code": {"class"},
"pre": {"class"},
"ol": {"start", "type"},
}
# Solo schema di URL safe nei link — nh3 di default fa già questo controllo,
# lo esplicitiamo per chiarezza nel caso il sanitizer cambi default.
_BOT_HTML_ALLOWED_URL_SCHEMES = {"http", "https", "mailto", "tel"}
def _sanitize_bot_html(raw_html: str) -> str:
"""Pulisce l'HTML estratto dal widget del bot per renderlo safe in UI.
Strategia:
- Whitelist stretta di tag/attributi (vedi costanti sopra).
- Strip totale di script/style/on*/javascript:.
- Link forzati a target=_blank + rel=noopener,noreferrer (defense-in-depth
contro tabnabbing — il render è dentro un iframe della popup live, ma
meglio dare già al server payload sicuro).
- Truncation a 200 KB per evitare che un widget rumoroso esploda il payload
WebSocket (la popup live mantiene la chat in memoria + ricarica al
reconnect tramite replay_last).
Ritorna stringa vuota se l'input è vuoto o se nh3 non è disponibile —
i caller devono gestire il fallback al plain text.
"""
if not raw_html:
return ""
if _nh3 is None:
return ""
try:
cleaned = _nh3.clean(
raw_html,
tags=_BOT_HTML_ALLOWED_TAGS,
attributes=_BOT_HTML_ALLOWED_ATTRS,
url_schemes=_BOT_HTML_ALLOWED_URL_SCHEMES,
link_rel="noopener noreferrer",
)
except Exception as exc: # pragma: no cover - difensivo
console.print(f"[yellow]nh3 sanitize failed, dropping HTML: {exc}[/yellow]")
return ""
# Hard cap: 200 KB sanitizzato. Una risposta normale di chat sta sotto 5 KB.
if len(cleaned) > 200_000:
cleaned = cleaned[:200_000]
return cleaned
def _browser_debug_enabled() -> bool:
# Central gate for noisy extraction/debug logs in production.
return env_bool("BROWSER_DEBUG", env_bool("DEBUG", False))
def _retry_playwright_read(default_max: int = 2):
"""Decorator: retry idempotent read-only Playwright calls on transient errors.
Wraps only read-style methods (no mutating side-effect on bot state).
Catches PlaywrightTimeoutError and transient PlaywrightError (frame
detached, target closed-but-restartable, network blip). Bails immediately
if the target was permanently closed (TargetClosed/Browser closed): that
case is handled by the higher-level mid-session browser recovery.
Disabled when PLAYWRIGHT_ACTION_RETRY_MAX=0.
"""
def deco(fn):
def wrapper(self, *args, **kwargs):
attempts = max(0, env_int("PLAYWRIGHT_ACTION_RETRY_MAX", default_max))
for i in range(attempts + 1):
try:
return fn(self, *args, **kwargs)
except PlaywrightTimeoutError:
if i >= attempts:
raise
time.sleep(1.0 * (i + 1))
except PlaywrightError as exc:
msg = str(exc)
# Permanent failures: don't retry; let the engine's
# browser-recovery path handle a relaunch.
if "TargetClosed" in msg or "Browser closed" in msg or "has been closed" in msg:
raise
if i >= attempts:
raise
time.sleep(1.0 * (i + 1))
# Unreachable; loop either returns or raises.
return fn(self, *args, **kwargs)
wrapper.__name__ = getattr(fn, "__name__", "wrapper")
wrapper.__doc__ = fn.__doc__
return wrapper
return deco
class TrackedMessage:
"""A chat message with unique tracking identifiers."""
def __init__(self, text: str, sender: str, elem_idx: int = -1):
self.text = text.strip()
self.sender = sender
self.elem_idx = elem_idx
self.content_hash = self._compute_hash(text)
self.text_length = len(self.text)
def _compute_hash(self, text: str) -> str:
"""Compute normalized hash for comparison."""
normalized = " ".join(text.lower().split())
# Used for de-dup tracking, not a security primitive (bandit B324).
return hashlib.md5(normalized.encode(), usedforsecurity=False).hexdigest()[:16]
def is_duplicate_of(self, other: 'TrackedMessage') -> bool:
"""Check if this message is a duplicate of another."""
return self.content_hash == other.content_hash
def is_content_subset_of(self, other: 'TrackedMessage') -> bool:
"""Check if this message's content is contained within another (for growing messages)."""
return self.text in other.text or other.text in self.text
def __repr__(self):
return f"TrackedMessage({self.sender}, len={self.text_length}, hash={self.content_hash[:8]})"
class MessageSnapshot:
"""Snapshot of chat state at a specific point in time."""
def __init__(self, messages: List[TrackedMessage]):
self.messages = messages
self.all_hashes = {m.content_hash for m in messages}
self.bot_hashes = {m.content_hash for m in messages if m.sender == "bot"}
self._by_index = {m.elem_idx: m for m in messages if m.elem_idx >= 0}
self.timestamp = time.time()
def find_new_bot_messages(self, current_messages: List[TrackedMessage]) -> List[TrackedMessage]:
"""
Return ALL new bot bubbles compared to baseline snapshot, in DOM order.
Some bots send several bubbles per turn (e.g. answer + sources card +
suggestions). Returning only the last one truncates the captured
response. Callers concatenate the texts in DOM order to get the full
turn output.
"""
baseline_len = len(self.messages)
out: List[TrackedMessage] = []
# Pre-compute list of bot baseline texts long enough to do content
# similarity matching (skip very short ones to avoid false positives
# on header-only bubbles like "AI Agent Campania.Divina"). Used as
# safety net contro virtualization DOM: se il sito target shifta
# gli elem_idx delle bolle vecchie quando ne arrivano di nuove,
# `self._by_index.get(msg.elem_idx)` ritorna None per la bolla
# vecchia (è sotto un nuovo idx ora) e finiva in `out.append(msg)`
# come falsamente nuova. Vedi tracking bug 2026-05.
baseline_bot_texts: List[str] = [
m.text for m in self.messages if m.sender == "bot" and m.text and len(m.text) >= 30
]
def _is_continuation_of_any_baseline_bot(msg_text: str) -> bool:
"""True se msg_text è subset/superset di una bolla bot del
baseline. Significa che è la stessa bolla, ricomparsa con un
elem_idx diverso (virtualization) o con piccoli aggiornamenti
di streaming."""
if not msg_text or len(msg_text) < 30:
return False
for bt in baseline_bot_texts:
shorter, longer = (msg_text, bt) if len(msg_text) <= len(bt) else (bt, msg_text)
if shorter and shorter in longer:
return True
return False
for msg in current_messages:
if msg.sender != "bot":
continue
# Strong signal: appended message after baseline capture.
if msg.elem_idx >= baseline_len:
# Safety net: anche se l'elem_idx ci dice "appended", se
# il testo è già presente come bolla bot nel baseline
# (virtualization / DOM reflow), è la stessa bolla. Skip.
if _is_continuation_of_any_baseline_bot(msg.text):
continue
out.append(msg)
continue
# Ignore exact duplicates already present in baseline.
if msg.content_hash in self.bot_hashes:
continue
# Ignore same element index whose text only changed superficially.
baseline_msg = self._by_index.get(msg.elem_idx)
if baseline_msg and baseline_msg.sender == "bot" and msg.is_content_subset_of(baseline_msg):
continue
# Cross-idx content match (virtualization): la stessa bolla
# potrebbe essere ora a un elem_idx diverso da quello del
# baseline. Riconosciamola per contenuto.
if _is_continuation_of_any_baseline_bot(msg.text):
continue
out.append(msg)
if out:
return out
# Fallback for UIs that re-render with unstable indices.
return [
msg
for msg in current_messages
if msg.sender == "bot" and msg.content_hash not in self.bot_hashes
]
def find_new_bot_message(self, current_messages: List[TrackedMessage]) -> Optional[TrackedMessage]:
"""Backwards-compat: last new bot bubble (kept for legacy callers)."""
msgs = self.find_new_bot_messages(current_messages)
return msgs[-1] if msgs else None
def has_message(self, msg: TrackedMessage) -> bool:
"""Check if a message existed in this snapshot."""
return msg.content_hash in self.all_hashes
def __repr__(self):
return f"MessageSnapshot(msgs={len(self.messages)}, bot_hashes={len(self.bot_hashes)})"
class BrowserController:
"""Controller for browser interaction via Playwright."""
def __init__(
self,
selectors: Optional[Dict[str, str]] = None,
output_dir: str = "./output",
headless: bool = False,
slow_mo: int = 0,
viewport_width: int = 1280,
viewport_height: int = 720,
):
self.output_dir = Path(output_dir)
self.screenshots_dir = self.output_dir / "screenshots"
self.headless = headless
self.slow_mo = slow_mo
self.viewport = {"width": viewport_width, "height": viewport_height}
self.last_error: Optional[str] = None
if selectors:
self.selectors = {
key: normalize_selector_value(value) if isinstance(value, str) else value
for key, value in selectors.items()
}
else:
self.selectors = {}
self.playwright = None
self.browser: Optional[Browser] = None
self.context: Optional[BrowserContext] = None
self.page: Optional[Page] = None
self.active_frame: Optional[Frame] = None
self.chat_messages: List[Dict[str, str]] = []
self.last_bot_message: Optional[str] = None
self.last_error: Optional[str] = None
self.last_user_message: Optional[str] = None
self.conversation_history: List[Dict[str, str]] = [] # Track conversation for sender inference
# REFACTORED: Message tracking for synchronization
self._tracked_messages: List[TrackedMessage] = []
self._pre_send_snapshot: Optional[MessageSnapshot] = None
# Lock difensivo sullo state di tracking. Ogni session ha la sua
# BrowserController, quindi in teoria non c'è race tra session sullo
# stesso controller. Ma se un caller esterno (es. live preview API
# endpoint che fa _extract_tracked_messages durante un poll del
# wait_for_bot_response) accede in parallelo, evitiamo letture
# parziali di `_tracked_messages`/`_pre_send_snapshot`. RLock per
# supportare chiamate annidate dallo stesso thread.
self._state_lock = threading.RLock()
# Set a True quando wait_for_bot_response ritorna una risposta
# *parziale* perché il timeout è scaduto su un candidate che la
# heuristica ha riconosciuto come troncato. Il runner usa questo
# flag per marcare il turno come `was_truncated_at_capture` nel
# log: il judge salta la valutazione factuality e dichiara
# `insufficient_sources` invece di penalizzare claim incompleti.
self.last_response_was_truncated: bool = False
def _get_root(self):
"""Return active frame if set, otherwise page."""
if self.active_frame:
return self.active_frame
return self.page
def _try_locator(self, container, selector: str, timeout: int = 2000):
"""Try to locate an element in a container and wait for visibility."""
locator = container.locator(selector).first
locator.wait_for(state="visible", timeout=timeout)
return locator
def _find_in_frames(self, selector: str, timeout: int = 2000) -> Tuple[Optional[Any], Optional[Frame]]:
"""Find a selector across all frames."""
if not self.page:
return None, None
for frame in self.page.frames:
if self.active_frame and frame == self.active_frame:
continue
try:
locator = self._try_locator(frame, selector, timeout=timeout)
return locator, frame
except Exception:
continue
return None, None
def _find_chat_input(self, selector: str) -> Optional[Any]:
"""Find the best chat input element using configured selector or fallback."""
if not self.page:
self.last_error = "Browser not initialized"
return None
# 1) Try configured selector first
if selector:
try:
if self.active_frame:
try:
locator = self._try_locator(self.active_frame, selector)
self.last_error = None
return locator
except Exception:
pass
locator = self._try_locator(self.page, selector)
self.last_error = None
return locator
except Exception:
self.last_error = f"Chat input not found for selector: {selector}"
# Try selector in any frame
locator, frame = self._find_in_frames(selector)
if locator:
self.active_frame = frame
self.last_error = None
return locator
# 2) Fallback: try common input candidates
best = None
best_score = -1
best_frame = None
keywords = ["message", "chat", "type", "ask", "question", "scrivi", "messaggio", "invia"]
for frame in self.page.frames:
try:
candidates = frame.locator("textarea, input[type='text'], [contenteditable='true']").all()
except Exception:
continue
for cand in candidates:
try:
if not cand.is_visible():
continue
placeholder = (cand.get_attribute("placeholder") or "").lower()
aria = (cand.get_attribute("aria-label") or "").lower()
role = (cand.get_attribute("role") or "").lower()
text = " ".join([placeholder, aria, role])
score = 0
for kw in keywords:
if kw in text:
score += 2
try:
is_editable = cand.evaluate("el => !!el.isContentEditable")
except Exception:
is_editable = False
if is_editable:
score += 1
if score > best_score:
best = cand
best_frame = frame
best_score = score
except Exception:
continue
if best:
self.active_frame = best_frame
self.last_error = f"Using fallback input (score {best_score})"
return best
self.last_error = "No visible chat input found"
return None
def _get_input_value(self, locator) -> str:
"""Return current value or innerText for an input-like element."""
try:
return locator.evaluate("el => el.isContentEditable ? (el.innerText || '') : (el.value || '')")
except Exception:
return ""
def _trigger_input_events(self, locator, text: str) -> None:
"""Force common input events to help UI frameworks enable send buttons."""
try:
locator.evaluate(
"""(el, value) => {
const setValue = () => {
if (el.isContentEditable) {
if ((el.innerText || '') !== value) {
el.innerText = value;
}
} else {
if ((el.value || '') !== value) {
el.value = value;
}
}
};
setValue();
const bubble = { bubbles: true };
try { el.dispatchEvent(new Event('input', bubble)); } catch (e) {}
try { el.dispatchEvent(new Event('change', bubble)); } catch (e) {}
try { el.dispatchEvent(new Event('keyup', bubble)); } catch (e) {}
try { el.dispatchEvent(new Event('keydown', bubble)); } catch (e) {}
try {
if (window.InputEvent) {
el.dispatchEvent(new InputEvent('input', { bubbles: true, data: value }));
}
} catch (e) {}
}""",
text,
)
except Exception:
pass
def _collect_chat_texts(self) -> List[str]:
"""Collect visible chat-like texts near the input as a fallback."""
root = self._get_root() or self.page
if not root:
return []
try:
return root.evaluate(
"""() => {
const isVisible = (el) => {
const style = window.getComputedStyle(el);
if (!style || style.display === 'none' || style.visibility === 'hidden') return false;
if (el.offsetParent === null) return false;
return true;
};
// First try to find chat container
const input = document.querySelector('textarea, input[type="text"], [contenteditable="true"]');
let chatRoot = input && (input.closest('[data-chat], .chat, .chat-container, .chatbox, .chat-widget, .widget, main, section') || document.body);
if (!chatRoot) chatRoot = document.body;
const texts = [];
// Strategy 1: Get full text from article elements (for Duolly-like interfaces)
const articles = chatRoot.querySelectorAll('article');
articles.forEach(article => {
if (!isVisible(article)) return;
// Get all text including from nested elements
const fullText = article.innerText || article.textContent || '';
const cleanText = fullText.replace(/\\s+/g, ' ').trim();
if (cleanText.length >= 10) {
texts.push(cleanText);
}
});
// Strategy 2: Get text from message containers
const messageContainers = chatRoot.querySelectorAll('[class*="message"], [class*="bubble"], [class*="chat-item"], [role="article"]');
messageContainers.forEach(container => {
if (!isVisible(container)) return;
const fullText = container.innerText || container.textContent || '';
const cleanText = fullText.replace(/\\s+/g, ' ').trim();
if (cleanText.length >= 10 && !texts.includes(cleanText)) {
texts.push(cleanText);
}
});
// Strategy 3: Get text from paragraph and div elements (fallback)
if (texts.length === 0) {
const nodes = chatRoot.querySelectorAll('p, div');
nodes.forEach(el => {
if (!isVisible(el)) return;
if (el.querySelector('input, textarea')) return;
// Skip if parent is already processed
if (el.parentElement && el.parentElement.className &&
(el.parentElement.className.includes('message') ||
el.parentElement.tagName === 'ARTICLE')) return;
const fullText = el.innerText || el.textContent || '';
const cleanText = fullText.replace(/\\s+/g, ' ').trim();
if (cleanText.length >= 10 && cleanText.length <= 2000) {
texts.push(cleanText);
}
});
}
return texts;
}"""
)
except Exception:
return []
@staticmethod
def _normalize_text(text: Optional[str]) -> str:
"""Normalize text for robust equality checks."""
if not text:
return ""
return " ".join(text.split()).strip().lower()
@staticmethod
def _clean_extracted_text(text: Optional[str]) -> str:
"""Clean accessibility/metadata noise from extracted chat bubbles."""
if not text:
return ""
cleaned = " ".join(text.split()).strip()
lower = cleaned.lower()
# WebChat accessibility wrappers can include labels/timestamps in the same node.
if "ha detto:" in lower or "inviato alle" in lower or "uno o più collegamenti" in lower:
cleaned = re.sub(r"(?:\bil bot ha detto:\s*|\bhai detto:\s*)+", "", cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r"(?:\buno o più collegamenti nel messaggio\.?\s*)+", "", cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r"\binviato alle\b.*$", "", cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r"^(\w+)\s+\1\b", r"\1", cleaned, flags=re.IGNORECASE)
return " ".join(cleaned.split()).strip()
def _extract_message_text(self, elem) -> str:
"""Extract visible message text from a message element with WebChat-safe fallback.
IMPORTANTE: `inner_text` rispetta CSS visibility e SCARTA il testo
in `display:none`, `aria-hidden`, `<details>` collassati. Bot che
rivelano il messaggio gradualmente (animazione di apparizione)
possono produrre un inner_text più corto del DOM reale, e noi
salveremmo una risposta troncata. Confrontiamo con textContent
(full-DOM, ignora CSS): se diverge significativamente preferiamo
textContent normalizzato.
"""
# Prefer explicit text nodes for Microsoft WebChat wrappers (e.g. JULIA).
try:
text_nodes = elem.locator(".webchat__text-content").all()
parts: List[str] = []
for node in text_nodes:
try:
chunk = node.inner_text() or node.text_content() or ""
except Exception:
chunk = node.text_content() or ""
chunk = self._clean_extracted_text(chunk)
if chunk and chunk not in parts:
parts.append(chunk)
if parts:
return " ".join(parts).strip()
except Exception:
pass
try:
inner = elem.inner_text() or ""
except Exception:
inner = ""
try:
full = elem.text_content() or ""
full = re.sub(r"\s+", " ", full).strip()
except Exception:
full = ""
# Se textContent è apprezzabilmente più ricco di inner_text (≥30%
# in più E ≥80 char totali), preferiamolo: è il segnale tipico di
# contenuto in <details>/aria-hidden/display:none che inner_text
# ha scartato ma il bot ha già reso disponibile nel DOM.
if full and len(full) > len(inner) * 1.3 and len(full) > 80:
chosen = full
else:
chosen = inner
return self._clean_extracted_text(chosen)
def _is_loading_message(self, text: str) -> bool:
"""Return True if text is a loading/processing indicator."""
if not text:
return False
normalized = self._normalize_text(text)
loading_patterns = [
"sto elaborando",
"elaborazione",
"sto raccogliendo",
"raccogliendo",
"sto pensando",
"pensando",
"thinking",
"processing",
"processing",
"loading",
"caricamento",
"sto caricando",
"attendere",
"attendi",
"attendere prego",
"un momento",
"wait",
"in corso",
"elaborando",
"...",
"…", # Ellipsis unicode
"elaboro",
"calcolo",
"sto calcolando",
]
is_loading = any(pattern in normalized for pattern in loading_patterns)
if is_loading:
if _browser_debug_enabled():
console.print(f"[dim]→ Detected loading message: '{text[:60]}...'[/dim]")
return is_loading
def _looks_like_user_echo(self, candidate: str, user_text: str) -> bool:
"""Return True when candidate appears to be the user's own message."""
cand = self._normalize_text(candidate)
user = self._normalize_text(user_text)
if not cand or not user:
return False
if cand == user:
return True
if cand.startswith(user) and len(cand) <= len(user) + 12:
return True
return False
def _find_new_texts(self, baseline: List[str], current: List[str]) -> List[str]:
"""Return texts that are new compared to baseline, preserving current order."""
baseline_counter = Counter(self._normalize_text(t) for t in baseline if self._normalize_text(t))
current_counter = Counter()
new_items: List[str] = []
for raw in current:
normalized = self._normalize_text(raw)
if not normalized:
continue
current_counter[normalized] += 1
if current_counter[normalized] > baseline_counter.get(normalized, 0):
new_items.append(raw)
return new_items
def _selector_list(self, selector_value: str) -> List[str]:
"""Split a selector list by comma and keep valid non-empty selectors."""
if not selector_value:
return []
return [s.strip() for s in selector_value.split(",") if s.strip()]
def _matches_any_selector(self, elem, selectors: List[str]) -> bool:
"""Return True if element matches at least one selector."""
for sel in selectors:
try:
if elem.evaluate("(el, s) => { try { return el.matches(s); } catch { return false; } }", sel):
return True
except Exception:
continue
return False
def _attempt_open_chat_widget(self) -> bool:
"""Try to open a collapsed chat widget by clicking likely launchers."""
if not self.page:
return False
try:
return self.page.evaluate(
"""() => {
const deny = ['language','lingua','lang','privacy','cookie','login','sign'];
const prefer = ['chat','assistant','ai','support','help','duolly','messaggio','messaggi','scrivi','ask'];
const nodes = Array.from(document.querySelectorAll('button, [role=\"button\"], a, div, span'))
.filter(el => el.offsetParent !== null);
if (!nodes.length) return false;
const score = (el) => {
const label = (el.getAttribute('aria-label') || el.getAttribute('title') || '').toLowerCase();
const text = (el.textContent || '').toLowerCase();
if (deny.some(k => label.includes(k) || text.includes(k))) return -10;
let s = 0;
if (prefer.some(k => label.includes(k) || text.includes(k))) s += 4;
const cls = (el.className || '').toString().toLowerCase();
if (cls.includes('chat') || cls.includes('widget') || cls.includes('launcher') || cls.includes('bubble')) s += 3;
const rect = el.getBoundingClientRect();
if (rect) {
// Prefer floating widgets bottom-right
if (rect.right > window.innerWidth * 0.6) s += 1;
if (rect.bottom > window.innerHeight * 0.6) s += 1;
}
return s;
};
let best = null;
let bestScore = -Infinity;
for (const el of nodes) {
const s = score(el);
if (s > bestScore) { bestScore = s; best = el; }
}
if (!best || bestScore < 0) return false;
best.click();
return true;
}"""
)
except Exception:
return False
def click_new_chat(self) -> bool:
"""Try to click a 'new chat' button to reset the conversation."""
if not self.page:
return False
patterns = [
"nuova chat",
"new chat",
"nuova conversazione",
"new conversation",
"nuova sessione",
"restart",
"start over",
"ricomincia",
"reset",
]
deny = ["language", "lingua", "lang", "cookie", "privacy", "login", "sign"]
max_scan = env_int("NEW_CHAT_SCAN_LIMIT", 200)
max_ms = env_int("NEW_CHAT_MAX_MS", 3000)
if max_scan < 0:
max_scan = 0
if max_ms < 0:
max_ms = 0
def match_text(text: str) -> bool:
if not text:
return False
t = text.lower()
if any(d in t for d in deny):
return False
return any(p in t for p in patterns)
def try_container(container) -> bool:
try:
# Fast-path: ask Playwright to filter by text first.
try:
pattern_re = re.compile("|".join(re.escape(p) for p in patterns), re.IGNORECASE)
filtered = container.locator("button, [role='button'], a").filter(has_text=pattern_re)
if filtered.count() > 0:
candidate = filtered.first
if candidate.is_visible(timeout=250):
candidate.click()
return True
except Exception:
pass
buttons = container.locator("button, [role='button'], a")
total = buttons.count()
start = time.time()
scanned = 0
for i in range(total):
if max_scan and scanned >= max_scan:
break
if max_ms and ((time.time() - start) * 1000) > max_ms:
break
btn = buttons.nth(i)
try:
if not btn.is_visible():
continue
text = (btn.text_content() or "").strip()
label = (btn.get_attribute("aria-label") or "").strip()
title = (btn.get_attribute("title") or "").strip()
combined = " ".join([text, label, title])
if match_text(combined):
btn.click()
return True
except Exception:
continue
scanned += 1
except Exception:
pass
return False
# Try active frame first
if self.active_frame and try_container(self.active_frame):
return True
# Try page
if try_container(self.page):
return True
# Try other frames
for frame in self.page.frames:
if self.active_frame and frame == self.active_frame:
continue
if try_container(frame):
self.active_frame = frame
return True
return False
def start(self, url: str) -> bool:
"""Start browser and navigate to URL."""
attempted_install = False
while True:
try:
self.last_error = None
self.playwright = sync_playwright().start()
console.print(f"[dim]Launching browser (headless={self.headless})...[/dim]")
is_linux = sys.platform.startswith("linux")
is_render = bool(
os.getenv("RENDER")
or os.getenv("RENDER_SERVICE_ID")
or os.getenv("RENDER_EXTERNAL_HOSTNAME")
or os.getenv("RENDER_INSTANCE_ID")
)
# Render (and most Linux containers) have no display. Ensure we don't
# attempt headed mode in production, which would fail immediately.
if is_linux and not os.getenv("DISPLAY") and not self.headless:
console.print("[yellow]No DISPLAY detected. Forcing headless mode.[/yellow]")
self.headless = True
launch_args: List[str] = []
if is_linux and is_render:
# Chromium sandbox is commonly unavailable in PaaS containers.
launch_args.extend(
[
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
]
)
self.browser = self.playwright.chromium.launch(
headless=self.headless,
slow_mo=self.slow_mo,
args=launch_args or None,
)
self.context = self.browser.new_context(
viewport=self.viewport,
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
)
self.page = self.context.new_page()
self.page.on("dialog", lambda dialog: dialog.accept())
console.print(f"[dim]Navigating to {url}...[/dim]")
try:
# networkidle can hang or time out on pages with long-polling/websockets.
self.page.goto(url, wait_until="networkidle", timeout=30000)
except Exception as e:
console.print(f"[yellow]Navigation wait_until=networkidle failed: {e}. Retrying with wait_until=load...[/yellow]")
self.page.goto(url, wait_until="load", timeout=45000)
console.print(f"[green]✓ Page loaded: {self.page.title()}[/green]")
self.active_frame = None
# Zoom-out di default: a parità di viewport, il browser
# mostra più contenuto (~25% in più con zoom 0.8). Aiuta su
# chat con UI verbosa (header + sidebar + footer) dove le
# risposte del bot in streaming si vedevano tagliate negli
# screenshot anche con viewport_height alto. Override via
# env BROWSER_ZOOM_LEVEL (es. "0.75" più aggressivo, "1.0"
# per disabilitare). Iniettato via JS subito dopo il load:
# CSS zoom non è standard W3C ma è ben supportato dai motori
# Blink/WebKit/Firefox e non rompe il layout responsivo
# come farebbe transform: scale().
try:
zoom_level = (env_str("BROWSER_ZOOM_LEVEL", "0.8") or "0.8").strip()
if zoom_level and zoom_level != "1.0":
self.page.evaluate(
f"document.documentElement.style.zoom = '{zoom_level}'"
)
except Exception as e:
# Best-effort: se lo zoom fallisce (es. sito con CSP
# strict che blocca lo style inline via JS) procediamo
# comunque, è solo un miglioramento visivo.
console.print(f"[yellow]Impostazione zoom-out fallita: {e}[/yellow]")
self.screenshots_dir.mkdir(parents=True, exist_ok=True)
return True
except Exception as e:
message = str(e)
missing_browser = (
"Executable doesn't exist" in message
or "download new browsers" in message
or "playwright install" in message.lower()
)
should_auto_install = env_bool("AUTO_INSTALL_PLAYWRIGHT", True)
if missing_browser and should_auto_install and not attempted_install:
attempted_install = True
console.print("[yellow]Playwright Chromium not found. Attempting automatic install...[/yellow]")
self.cleanup()
if self._install_chromium_browser():
console.print("[green]Chromium installed. Retrying browser launch...[/green]")
continue
self.last_error = message
console.print(f"[red]✗ Failed to start browser: {message}[/red]")
self.cleanup()
return False
def _install_chromium_browser(self) -> bool:
"""Install Chromium runtime for Playwright when missing."""
browsers_path = (os.getenv("PLAYWRIGHT_BROWSERS_PATH") or "").strip()
if not browsers_path:
default_browsers = Path.home() / ".ai-testing-platform" / "runtime" / "ms-playwright"
default_browsers.mkdir(parents=True, exist_ok=True)
browsers_path = str(default_browsers)
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = browsers_path
# Preferred path: invoke Playwright CLI in-process. This works in bundled
# desktop apps where sys.executable is the app launcher, not a Python CLI.
try:
import playwright.__main__ as playwright_main
original_argv = list(sys.argv)
try:
sys.argv = ["playwright", "install", "chromium"]
playwright_main.main()
return True
except SystemExit as exc:
code = int(exc.code) if isinstance(exc.code, int) else 1
if code == 0:
return True
self.last_error = f"Playwright install failed (exit {code})"
finally:
sys.argv = original_argv
except Exception:
# Fall back to subprocess-based installation.
pass
cmd_candidates: List[List[str]] = []
executable_name = Path(sys.executable or "").name.lower()
if executable_name.startswith("python") or executable_name in {"python", "python3", "python.exe"}:
cmd_candidates.append([sys.executable, "-m", "playwright", "install", "chromium"])
cmd_candidates.append(["playwright", "install", "chromium"])
env = os.environ.copy()
try:
for cmd in cmd_candidates:
result = subprocess.run(
cmd,
check=False,
capture_output=True,
text=True,
timeout=900,
env=env,
)
if result.returncode == 0:
return True
output = (result.stdout or "") + ("\n" + result.stderr if result.stderr else "")
trimmed = output[-1200:] if output else ""
self.last_error = f"Playwright install failed (exit {result.returncode})"
if trimmed and _browser_debug_enabled():
console.print(f"[dim]{trimmed}[/dim]")
except Exception as exc:
self.last_error = f"Playwright install error: {exc}"
console.print(f"[red]Automatic Playwright install error: {exc}[/red]")
return False
console.print("[red]Automatic Playwright install failed.[/red]")
return False
def cleanup(self):
"""Cleanup browser resources."""
try:
if self.context:
self.context.close()
if self.browser:
self.browser.close()
if self.playwright:
self.playwright.stop()
except Exception as e:
console.print(f"[yellow]Warning during cleanup: {e}[/yellow]")
finally:
self.page = None
self.context = None
self.browser = None
self.playwright = None
def is_alive(self) -> bool:
"""Lightweight liveness probe for the underlying browser process.
Used by the engine to detect a dead Chromium mid-session so a
restart can be attempted without aborting the whole run. Combines
cheap state checks (page/browser still wired) with a no-op JS eval
to confirm the page responds.
"""
try:
if not self.browser or not self.page:
return False
try:
if not self.browser.is_connected():
return False
except Exception:
return False
try:
if self.page.is_closed():
return False
except Exception:
return False
self.page.evaluate("1+1")
return True
except Exception:
return False
@_retry_playwright_read()
def get_context(self) -> str:
"""Extract current page context for AI."""
if not self.page:
return "Browser not initialized"
try:
title = self.page.title()
url = self.page.url
context_parts = [f"Page Title: {title}", f"URL: {url}"]
messages = self.get_chat_messages()
if messages:
context_parts.append("\nRecent Chat Messages:")
for i, msg in enumerate(messages[-5:], 1):
sender = msg.get("sender", "unknown")
text = msg.get("text", "")[:200]
context_parts.append(f" {i}. [{sender}] {text}")
input_selector = self.selectors.get("chat_input", "")
if input_selector:
try:
root = self._get_root() or self.page
input_locator = root.locator(input_selector).first
if input_locator.is_visible(timeout=1000):
placeholder = input_locator.get_attribute("placeholder") or ""
context_parts.append(f"\nChat Input: Available (placeholder: '{placeholder}')")
else:
context_parts.append("\nChat Input: Not visible")
except Exception:
context_parts.append("\nChat Input: Not found")
return "\n".join(context_parts)
except Exception as e:
return f"Error getting context: {e}"
def _extract_tracked_messages(self) -> List[TrackedMessage]:
"""
Extract messages with tracking metadata for synchronization.
REFACTORED: Returns TrackedMessage objects with content hashing.
"""
if not self.page:
if _browser_debug_enabled():
console.print("[red]🔴 _extract_tracked_messages: No page available![/red]")
return []
tracked_messages = []
selectors = self.selectors.get("chat_messages", ".message, .chat-bubble, article, [role='article'], .message-bubble")
user_selectors = self.selectors.get("user_messages", ".user-message, .user, .me, .sent, [data-sender='user']")
bot_selectors = self.selectors.get("bot_messages", ".bot-message, .bot, .assistant, .ai, .received, [data-sender='bot'], [data-sender='assistant']")
user_selector_list = self._selector_list(user_selectors)
bot_selector_list = self._selector_list(bot_selectors)
debug = _browser_debug_enabled()
is_linux = sys.platform.startswith("linux")
is_render = bool(
os.getenv("RENDER")
or os.getenv("RENDER_SERVICE_ID")
or os.getenv("RENDER_EXTERNAL_HOSTNAME")
or os.getenv("RENDER_INSTANCE_ID")
)
default_limit = 40 if (is_linux and is_render) else 80
max_elems = env_int("CHAT_MESSAGES_LIMIT", default_limit)
if max_elems < 0:
max_elems = 0
if debug:
console.print(f"[dim]🔍 _extract_tracked_messages: selectors='{selectors[:80]}...'[/dim]")
try:
root = self._get_root() or self.page
locator = root.locator(selectors)
total = locator.count()
if debug:
console.print(f"[dim]📊 Found {total} message elements[/dim]")
start_idx = 0
if max_elems and total > max_elems:
start_idx = total - max_elems
for idx in range(start_idx, total):
try:
elem = locator.nth(idx)
text = self._extract_message_text(elem)
if not text or len(text) < 2:
if debug:
console.print(f"[dim] ⚠️ Message {idx}: too short, skipping[/dim]")
continue
# Skip loading messages
if self._is_loading_message(text):
if debug:
console.print(f"[dim] ⏳ Message {idx}: loading indicator, skipping[/dim]")
continue
# Determine sender
is_user = False
is_bot = False
if user_selector_list:
is_user = self._matches_any_selector(elem, user_selector_list)
if bot_selector_list:
is_bot = self._matches_any_selector(elem, bot_selector_list)
if debug:
console.print(
f"[dim] Message {idx}: sender detection - is_user={is_user}, is_bot={is_bot}, text='{text[:50]}...'[/dim]"
)
if not is_user and not is_bot:
try:
class_attr = (elem.get_attribute("class") or "").lower()
is_user = any(kw in class_attr for kw in ["user", "me", "mine", "sent", "human"])
is_bot = any(kw in class_attr for kw in ["bot", "assistant", "ai", "received", "agent", "model"])
except Exception:
pass
if not is_user and not is_bot:
try:
data_sender = (elem.get_attribute("data-sender") or "").lower()
data_role = (elem.get_attribute("data-role") or "").lower()
if data_sender in ["user", "human", "me"] or data_role in ["user", "human"]:
is_user = True
elif data_sender in ["bot", "assistant", "ai", "agent"] or data_role in ["bot", "assistant", "ai"]:
is_bot = True
except Exception:
pass
if is_user:
sender = "user"
elif is_bot:
sender = "bot"
else:
sender = "unknown"
tracked = TrackedMessage(text=text, sender=sender, elem_idx=idx)
tracked_messages.append(tracked)
if debug:
console.print(f"[dim] ✅ Message {idx}: ADDED as '{sender}' - '{text[:40]}...'[/dim]")
except Exception as e:
if debug:
console.print(f"[yellow] ⚠️ Message {idx}: extraction error - {e}[/yellow]")
continue
# Post-process: infer senders for unknown messages using position
# and comparison with last_user_message
tracked_messages = self._infer_senders(tracked_messages)
# Summary
bot_count = sum(1 for m in tracked_messages if m.sender == "bot")
user_count = sum(1 for m in tracked_messages if m.sender == "user")
if debug:
console.print(f"[dim]📊 Extraction complete: {len(tracked_messages)} total ({bot_count} bot, {user_count} user)[/dim]")
return tracked_messages
except Exception as e:
if debug:
console.print(f"[yellow]Error extracting tracked messages: {e}[/yellow]")
return []
def _infer_senders(self, messages: List[TrackedMessage]) -> List[TrackedMessage]:
"""Infer sender for unknown messages using position and content comparison."""
if not messages:
return messages
debug = _browser_debug_enabled()
# Raccogli TUTTI i testi user inviati finora (non solo l'ultimo). In
# passato qui c'era solo `last_user_text`: bastava a riconoscere
# l'echo della query corrente, ma falliva se nel DOM ricompariva
# una domanda di un turno precedente (es. dopo virtualization /
# widget feedback che ripete history). Quel msg restava `unknown`
# → finiva nell'alternating fallback → mis-classificato bot →
# concatenato alla response. Vedi tracking bug 2026-05.
user_texts: List[str] = []
if self.conversation_history:
for entry in self.conversation_history:
if entry.get("role") == "user":
t = (entry.get("content") or "").strip()
if t:
user_texts.append(t)
# `last_user_text` mantenuto per il debug log; vero matching su tutta
# la history.
last_user_text = user_texts[-1] if user_texts else ""
# First pass: mark obvious matches
for i, msg in enumerate(messages):
if msg.sender != "unknown":
continue
# Check if msg text matches ANY user message we sent during this
# conversation (echo del DOM). Includiamo entrambe le direzioni
# del containment per robustezza su trim/wrapping/whitespace.
matched_user_text = None
for ut in user_texts:
if not ut or len(ut) < 5:
continue
if ut in msg.text or msg.text in ut:
matched_user_text = ut
break
if matched_user_text:
msg.sender = "user"
if debug:
is_last = (matched_user_text == last_user_text)
tag = "last sent" if is_last else "older turn"
console.print(f"[dim] 📝 Inferred sender for msg {i}: user (matches {tag})[/dim]")
continue
# Check for bot indicators in content
bot_indicators = ["ai agent", "assistant", "bot:", "agent:", "ciao! sono", "benvenuto", "posso aiutarti"]
if any(ind in msg.text.lower()[:100] for ind in bot_indicators):
msg.sender = "bot"
if debug:
console.print(f"[dim] 🤖 Inferred sender for msg {i}: bot (content indicators)[/dim]")
continue
# NOTA: in passato qui c'era un fallback "alternating pattern" che,
# trovato un msg con sender noto, attribuiva agli unknown ai lati
# bot/user in alternanza. È stato RIMOSSO perché creava un fallout
# a cascata: se anche un solo elemento DOM (es. un widget di
# sidebar che il selettore CSS bot_messages cattura per sbaglio,
# un header ripetuto, un placeholder mid-stream) veniva
# classificato come "bot", la sequenza alternata propagava la
# mis-classificazione a TUTTI gli unknown successivi. Effetto
# osservato in prod: dal turno 9 di una test session in poi, le
# domande utente dei turni precedenti finivano classificate come
# bot → entravano in `find_new_bot_messages` come "novità" →
# concatenate alla risposta vera con `\n\n`. Vedi browser tracking
# bug investigato il 2026-05.
#
# Trade-off: ora gli unknown restano unknown e vengono ignorati a
# valle (in `find_new_bot_messages` la condizione `sender != "bot"`
# li skippa naturalmente). Preferiamo perdere qualche msg
# ambiguo che inquinare la response del bot con contenuti
# estranei.
return messages
def extract_rich_content(self, elem) -> Dict[str, Any]:
"""
Extract rich content from a message element (maps, images, links, buttons).
Returns a dictionary with content analysis.
"""
content = {
"has_map": False,
"has_image": False,
"has_link": False,
"has_button": False,
"has_list": False,
"has_table": False,
"links": [],
"buttons": [],
"raw_html": "",
# HTML sanitizzato (whitelist tag/attr) usato dalla popup live e
# dalla pagina risultati per preservare grassetto / liste /
# paragrafi / link. Resta vuoto se il widget non espone HTML
# ricco o se nh3 non è installato — i template fanno fallback
# automatico al plain text con whitespace-pre-wrap.
"sanitized_html": "",
}
if not elem or not self.page:
return content
try:
# Check for maps (iframe with map, map containers, etc.)
map_selectors = [
"iframe[src*='google.com/maps']",
"iframe[src*='map']",
".map",
"[class*='map']",
"[id*='map']",
]
for selector in map_selectors:
try:
if elem.locator(selector).count() > 0:
content["has_map"] = True
break
except Exception:
pass
# Check for images
try:
if elem.locator("img").count() > 0:
content["has_image"] = True
except Exception:
pass
# Extract links
try:
link_elements = elem.locator("a[href]").all()
for link in link_elements:
href = link.get_attribute("href") or ""
text = link.text_content() or ""
if not href or href.startswith("javascript:"):
continue
if href.startswith("/"):
href = urljoin(self.page.url, href)
link_payload = {
"title": (text or href).strip()[:120],
"url": href.strip(),
}
if link_payload["url"] and link_payload not in content["links"]:
content["links"].append(link_payload)
content["has_link"] = True
except Exception:
pass
# Extract buttons
try:
button_selectors = ["button", "[role='button']", ".btn", "[class*='button']"]
for selector in button_selectors:
buttons = elem.locator(selector).all()
for btn in buttons:
text = btn.text_content() or btn.inner_text() or ""
if text.strip():
content["buttons"].append(text.strip()[:50])
content["has_button"] = True
except Exception:
pass
# Check for lists
try:
if elem.locator("ul, ol").count() > 0:
content["has_list"] = True
except Exception:
pass
# Check for tables
try:
if elem.locator("table").count() > 0:
content["has_table"] = True
except Exception:
pass
# Get raw HTML for advanced analysis
try:
content["raw_html"] = elem.inner_html() or ""
except Exception:
pass
# Sanitize raw HTML (whitelist) per uso in UI. Lo facciamo qui
# perché abbiamo già il raw e non vogliamo serializzare HTML
# rumoroso/insicuro più giù nello stack (websocket payload, JSON
# in DB). Vedi `_sanitize_bot_html` per la whitelist.
try:
if content["raw_html"]:
content["sanitized_html"] = _sanitize_bot_html(content["raw_html"])
except Exception as sanitize_exc: # pragma: no cover - difensivo
console.print(
f"[yellow]Bot HTML sanitize failed: {sanitize_exc}[/yellow]"
)
except Exception as e:
console.print(f"[yellow]Error extracting rich content: {e}[/yellow]")
# Always merge source links exposed in right-side insights/aside panels.
sidebar_links = self._extract_sidebar_source_links()
if sidebar_links:
for link_payload in sidebar_links:
if link_payload["url"] and link_payload not in content["links"]:
content["links"].append(link_payload)
content["has_link"] = True
return content
def _extract_sidebar_source_links(self) -> List[Dict[str, str]]:
"""Collect cited source links shown in side insight panels (e.g. FONTI)."""
if not self.page:
return []
try:
raw_links = self.page.evaluate(
"""() => {
const isVisible = (el) => {
if (!el) return false;
const style = window.getComputedStyle(el);
if (!style || style.display === 'none' || style.visibility === 'hidden') return false;
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
};
const toText = (el) => (el?.innerText || el?.textContent || '').replace(/\\s+/g, ' ').trim();
const roots = new Set();
document.querySelectorAll('aside, [class*="insight"], [class*="sidebar"], [class*="source"], [data-testid*="insight"], [data-testid*="source"], [aria-label*="insight" i], [aria-label*="fonti" i], [aria-label*="sources" i]').forEach((node) => {
if (isVisible(node)) roots.add(node);
});
// Include lightweight keyword roots (avoid full DOM scan for performance).
document.querySelectorAll('section, article, aside, div').forEach((node) => {
if (!isVisible(node)) return;
const marker = (node.getAttribute('data-testid') || '') + ' ' + (node.className || '') + ' ' + (node.getAttribute('aria-label') || '');
const markerLower = marker.toLowerCase();
if (markerLower.includes('insight') || markerLower.includes('source') || markerLower.includes('fonti')) {
roots.add(node);
return;
}
const text = toText(node).toLowerCase().slice(0, 240);
if (/\\bfonti\\b|\\bsources\\b|ai insights/.test(text)) {
roots.add(node);
}
});
if (roots.size === 0) {
document.querySelectorAll('aside').forEach((node) => {
if (isVisible(node)) roots.add(node);
});
}
const out = [];
const seen = new Set();
roots.forEach((root) => {
root.querySelectorAll('a[href]').forEach((a) => {
if (!isVisible(a)) return;
const href = (a.getAttribute('href') || '').trim();
if (!href || href.startsWith('javascript:') || href.startsWith('#')) return;
const abs = new URL(href, window.location.href).href;
if (seen.has(abs)) return;
seen.add(abs);
out.push({
title: toText(a).slice(0, 120) || abs,
url: abs,
});
});
});
return out;
}"""
)
except Exception:
return []
links: List[Dict[str, str]] = []
seen_urls: Set[str] = set()
for item in raw_links or []:
if not isinstance(item, dict):
continue
href = str(item.get("url") or "").strip()
title = str(item.get("title") or href).strip()[:120]
if not href:
continue
if href.startswith("/"):
href = urljoin(self.page.url, href)
if href in seen_urls:
continue
seen_urls.add(href)
links.append({"title": title or href, "url": href})
return links
def get_last_bot_response_with_rich_content(self) -> Dict[str, Any]:
"""Get the last bot response with rich content analysis."""
if not self.page:
return {"text": "", "rich_content": {}}
try:
# Get last tracked messages
messages = self._extract_tracked_messages()
bot_messages = [m for m in messages if m.sender == "bot"]
if not bot_messages:
fallback_links = self._extract_sidebar_source_links()
return {
"text": "",
"rich_content": {
"links": fallback_links,
"has_link": bool(fallback_links),
},
}
last_bot = bot_messages[-1]
# Find the element for this message
selectors = self.selectors.get("chat_messages", ".message, .chat-bubble, article, [role='article'], .message-bubble")
root = self._get_root() or self.page
msg_elements = root.locator(selectors).all()
if last_bot.elem_idx < len(msg_elements):
elem = msg_elements[last_bot.elem_idx]
rich_content = self.extract_rich_content(elem)
return {
"text": last_bot.text,
"rich_content": rich_content,
}
fallback_links = self._extract_sidebar_source_links()
return {
"text": last_bot.text,
"rich_content": {
"links": fallback_links,
"has_link": bool(fallback_links),
},
}
except Exception as e:
console.print(f"[yellow]Error getting bot response with rich content: {e}[/yellow]")
fallback_links = self._extract_sidebar_source_links()
return {
"text": self.last_bot_message or "",
"rich_content": {
"links": fallback_links,
"has_link": bool(fallback_links),
},
}
def _capture_snapshot(self) -> MessageSnapshot:
"""Capture current message state for comparison."""
with self._state_lock:
messages = self._extract_tracked_messages()
return MessageSnapshot(messages)
@_retry_playwright_read()
def get_chat_messages(self) -> List[Dict[str, str]]:
"""Extract chat messages from page (legacy format for compatibility)."""
if not self.page:
return []
# Fast path: reuse tracked-message extractor (no heavy debug work).
try:
tracked = self._extract_tracked_messages()
self._tracked_messages = tracked
messages = [{"sender": m.sender, "text": m.text} for m in tracked]
self.chat_messages = messages
bot_msgs = [m for m in messages if m.get("sender") == "bot"]
if bot_msgs:
self.last_bot_message = bot_msgs[-1]["text"]
return messages
except Exception:
return []
def send_message(self, text: str, human_like: bool = True) -> bool:
"""Send message in chat with human-like typing.
Sincronizzazione robusta: PRIMA di inviare il nuovo messaggio,
aspetta che la chat sia veramente "ready":
- input field editable / non disabled / non readonly
- bot non più in streaming (no streaming-indicator visibile)
Senza questa sincronizzazione, il sistema poteva inviare il
prossimo messaggio user mentre il bot stava ancora streamando la
risposta precedente. Il bot completava la generazione DOPO il
nostro send, e noi catturavamo quel completamento come "risposta
del turno successivo" — off-by-one nel transcript.
"""
if not self.page:
self.last_error = "Browser not initialized"
console.print("[red]Browser not initialized[/red]")
return False
# Wait for chat to be ready (bot stream finished, input enabled).
ready = self._wait_for_chat_ready(timeout=int(env_int("CHAT_READY_TIMEOUT", 60)))
if not ready:
console.print("[yellow]⚠ Chat non sembra pronta dopo il timeout, procedo comunque[/yellow]")
# REFACTORED: Capture snapshot BEFORE any interaction
console.print("[dim]📸 Capturing pre-send snapshot...[/dim]")
with self._state_lock:
self._pre_send_snapshot = self._capture_snapshot()
console.print(f"[dim] Captured {len(self._pre_send_snapshot.messages)} messages ({len(self._pre_send_snapshot.bot_hashes)} bot)[/dim]")
input_selector = self.selectors.get("chat_input", "")
send_button_selector = self.selectors.get("send_button", "")
input_locator = self._find_chat_input(input_selector)
if not input_locator:
if self._attempt_open_chat_widget():
self.page.wait_for_timeout(800)
input_locator = self._find_chat_input(input_selector)
if not input_locator:
console.print(f"[red]{self.last_error}[/red]")
return False
root = self._get_root() or self.page
self.last_user_message = text
try:
# Clear and focus
try:
is_editable = input_locator.evaluate("el => !!el.isContentEditable")
except Exception:
is_editable = False
if is_editable:
input_locator.click()
input_locator.evaluate("el => { el.innerText = ''; }")
else:
input_locator.fill("")
input_locator.click()
input_locator.focus()
# Type with human-like delay to trigger JavaScript events
# Default: 50% slower than before for more realistic typing
if human_like:
if env_bool("INSTANT_TYPING", False):
# Instant typing: fastest path (name matches behavior).
input_locator.type(text, delay=0)
else:
# Human-like typing: 30-80ms per character (about 150-400 WPM)
min_delay = env_int("TYPING_DELAY_MIN_MS", 30)
max_delay = env_int("TYPING_DELAY_MAX_MS", 80)
if max_delay < min_delay:
max_delay = min_delay
for char in text:
input_locator.type(char, delay=random.randint(min_delay, max_delay))
# Add occasional pause for realism (comma, period, or random)
if char in ',.!?;' or random.random() < 0.05:
time.sleep(random.uniform(0.1, 0.3))
else:
input_locator.fill(text)
# Verify text was typed
typed_value = self._get_input_value(input_locator)
if text and not typed_value.strip():
# Fallback: set value directly and re-trigger events
try:
input_locator.evaluate(
"""(el, value) => {
if (el.isContentEditable) {
el.innerText = value;
} else {
el.value = value;
}
}""",
text,
)
self._trigger_input_events(input_locator, text)
typed_value = self._get_input_value(input_locator)
except Exception:
pass
if text and not typed_value.strip():
try:
input_locator.click()
self.page.keyboard.type(text, delay=env_int("TYPING_DELAY_FALLBACK_MS", 0))
self._trigger_input_events(input_locator, text)
typed_value = self._get_input_value(input_locator)
except Exception:
pass
if text and not typed_value.strip():
self.last_error = "Input did not receive text. Check selector or contenteditable support."
console.print(f"[yellow]{self.last_error}[/yellow]")
return False
# Force input events to enable send buttons in React/Vue apps
self._trigger_input_events(input_locator, text)
try:
input_locator.press(" ")
input_locator.press("Backspace")
except Exception:
pass
console.print(f"[dim]Typed: '{text[:50]}{'...' if len(text) > 50 else ''}'[/dim]")
# Wait for any button to become enabled
self.page.wait_for_timeout(env_int("WAIT_AFTER_TYPING_MS", 80))
# Try multiple send methods
sent = False
# Method 1: Try enabled send button
if send_button_selector and not sent:
try:
scan_limit = env_int("SEND_BUTTON_SCAN_LIMIT", 120)
if scan_limit < 0:
scan_limit = 0
candidates_locator = root.locator(send_button_selector)
total_candidates = candidates_locator.count()
input_box = None
try:
input_box = input_locator.bounding_box()
except Exception:
input_box = None
def is_bad(btn) -> bool:
try:
label = (btn.get_attribute("aria-label") or "").lower()
title = (btn.get_attribute("title") or "").lower()
text = (btn.text_content() or "").lower()
for kw in ["language", "lingua", "lang"]:
if kw in label or kw in title or kw in text:
return True
except Exception:
pass
return False
def distance(a, b):
if not a or not b:
return None
ax = a["x"] + a["width"] / 2
ay = a["y"] + a["height"] / 2
bx = b["x"] + b["width"] / 2
by = b["y"] + b["height"] / 2
return ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5
best = None
best_dist = None
for i in range(total_candidates):
if scan_limit and i >= scan_limit:
break
btn = candidates_locator.nth(i)
try:
if not btn.is_visible() or btn.is_disabled():
continue
if is_bad(btn):
continue
btn_box = None
try:
btn_box = btn.bounding_box()
except Exception:
btn_box = None
dist = distance(input_box, btn_box) if input_box and btn_box else None
if best is None or (dist is not None and (best_dist is None or dist < best_dist)):
best = btn
best_dist = dist
except Exception:
continue
if best:
best.click()
console.print("[dim]Clicked send button[/dim]")
sent = True
except Exception:
pass
# Method 2: Heuristic click within nearest chat/form container
if not sent:
try:
clicked = input_locator.evaluate(
"""(el) => {
const root = el.closest('form')
|| el.closest('[data-chat], .chat, .chat-container, .chatbox, .chat-widget, .widget')
|| el.parentElement;
if (!root) return false;
const deny = ['language','lingua','lang'];
const prefer = ['send','invia','submit','ai'];
const inputRect = el.getBoundingClientRect();
const buttons = Array.from(root.querySelectorAll('button, [role=\"button\"]'));
if (!buttons.length) return false;
const scoreBtn = (btn) => {
if (btn.disabled || btn.getAttribute('aria-disabled') === 'true') return -10;
const label = (btn.getAttribute('aria-label') || btn.getAttribute('title') || '').toLowerCase();
const text = (btn.textContent || '').toLowerCase();
if (deny.some(k => label.includes(k) || text.includes(k))) return -10;
let score = 0;
if ((btn.getAttribute('type') || '').toLowerCase() === 'submit') score += 5;
if (prefer.some(k => label.includes(k) || text.includes(k))) score += 3;
const rect = btn.getBoundingClientRect();
const dx = (rect.x + rect.width / 2) - (inputRect.x + inputRect.width / 2);
const dy = (rect.y + rect.height / 2) - (inputRect.y + inputRect.height / 2);
const dist = Math.hypot(dx, dy);
score += Math.max(0, 300 - dist) / 100;
return score;
};
let best = null;
let bestScore = -Infinity;
for (const btn of buttons) {
const s = scoreBtn(btn);
if (s > bestScore) { bestScore = s; best = btn; }
}
if (!best || bestScore < 0) return false;
best.click();
return true;
}"""
)
if clicked:
console.print("[dim]Clicked send button (heuristic)[/dim]")
sent = True
except Exception:
pass
# Method 3: Page fallback if frame mismatch
if not sent and self.active_frame and self.page and send_button_selector:
try:
scan_limit = env_int("SEND_BUTTON_SCAN_LIMIT", 120)
if scan_limit < 0:
scan_limit = 0
candidates_locator = self.page.locator(send_button_selector)
total_candidates = candidates_locator.count()
input_box = None
try:
input_box = input_locator.bounding_box()
except Exception:
input_box = None
best = None
best_dist = None
for i in range(total_candidates):
if scan_limit and i >= scan_limit:
break
btn = candidates_locator.nth(i)
try:
if not btn.is_visible() or btn.is_disabled():
continue
label = (btn.get_attribute("aria-label") or "").lower()
title = (btn.get_attribute("title") or "").lower()
text = (btn.text_content() or "").lower()
if any(kw in label or kw in title or kw in text for kw in ["language", "lingua", "lang"]):
continue
btn_box = None
try:
btn_box = btn.bounding_box()
except Exception:
btn_box = None
if input_box and btn_box:
dist = ((input_box["x"] + input_box["width"] / 2 - (btn_box["x"] + btn_box["width"] / 2)) ** 2 + (input_box["y"] + input_box["height"] / 2 - (btn_box["y"] + btn_box["height"] / 2)) ** 2) ** 0.5
else:
dist = None
if best is None or (dist is not None and (best_dist is None or dist < best_dist)):
best = btn
best_dist = dist
except Exception:
continue
if best:
best.click()
console.print("[dim]Clicked send button (page fallback)[/dim]")
sent = True
except Exception:
pass
# Method 4: Keyboard shortcuts
if not sent:
shortcuts = ["Enter", "Control+Enter", "Shift+Enter", "Return"]
for shortcut in shortcuts:
try:
input_locator.press(shortcut)
console.print(f"[dim]Pressed {shortcut}[/dim]")
self.page.wait_for_timeout(300)
# Check if page changed (indicates send might have worked)
# We'll consider it sent if no error
sent = True
break
except Exception:
continue
# Check if input cleared after send
if sent:
post_value = self._get_input_value(input_locator).strip()
if post_value:
self.last_error = "Input not cleared after send; message may not have been sent."
else:
self.last_error = None
console.print("[green]✓ Message sent[/green]")
# Track in conversation history for sender inference
self.conversation_history.append({"role": "user", "content": text})
else:
self.last_error = "Message not sent (no send method succeeded)"
console.print("[yellow]⚠ Could not confirm message was sent[/yellow]")
return sent
except Exception as e:
self.last_error = str(e)
console.print(f"[red]Failed to send message: {e}[/red]")
return False
def click_element(self, selector: str, timeout: int = 5000) -> bool:
"""Click element on page."""
if not self.page:
self.last_error = "Browser not initialized"
return False
selector = normalize_selector_value(selector) if selector else selector
try:
root = self._get_root() or self.page
locator = root.locator(selector).first
locator.wait_for(state="visible", timeout=timeout)
locator.click()
self.last_error = None
return True
except Exception as e:
if self.active_frame and self.page:
try:
locator = self.page.locator(selector).first
locator.wait_for(state="visible", timeout=timeout)
locator.click()
self.last_error = None
return True
except Exception:
pass
self.last_error = str(e)
console.print(f"[red]Failed to click {selector}: {e}[/red]")
return False
def wait(self, seconds: float):
"""Wait for specified seconds."""
if self.page:
self.page.wait_for_timeout(int(seconds * 1000))
@_retry_playwright_read()
def capture_screenshot(self, name: str) -> Optional[str]:
"""Capture screenshot of current page (persisted evidence for reports)."""
if not self.page:
return None
try:
is_linux = sys.platform.startswith("linux")
is_render = bool(
os.getenv("RENDER")
or os.getenv("RENDER_SERVICE_ID")
or os.getenv("RENDER_EXTERNAL_HOSTNAME")
or os.getenv("RENDER_INSTANCE_ID")
)
# On Render (free plan especially), keep screenshots in Playwright-native formats
# to avoid heavy conversions that can stall the runner.
fmt = env_str("SCREENSHOT_FORMAT", "jpeg" if (is_linux and is_render) else "png").strip().lower()
if fmt == "jpg":
fmt = "jpeg"
quality = env_int("SCREENSHOT_QUALITY", 70)
stamp = int(time.time() * 1000) + int(random.random() * 1000)
if fmt in {"jpeg", "png"}:
ext = "jpg" if fmt == "jpeg" else "png"
filename = f"{name}_{stamp}.{ext}"
filepath = self.screenshots_dir / filename
kwargs: Dict[str, Any] = {"path": str(filepath), "full_page": False, "type": fmt}
if fmt == "jpeg":
kwargs["quality"] = max(1, min(quality, 100))
self.page.screenshot(**kwargs)
console.print(f"[dim]Screenshot: {filepath.name}[/dim]")
return str(filepath)
if fmt == "webp":
filename = f"{name}_{stamp}.webp"
filepath = self.screenshots_dir / filename
try:
from PIL import Image # type: ignore
png_bytes = self.page.screenshot(type="png", full_page=False)
img = Image.open(io.BytesIO(png_bytes))
img.save(str(filepath), "WEBP", quality=max(1, min(quality, 100)), method=6)
console.print(f"[dim]Screenshot: {filepath.name}[/dim]")
return str(filepath)
except Exception as e:
# Fall back to PNG if WebP conversion is unavailable.
fallback = self.screenshots_dir / f"{name}_{stamp}.png"
self.page.screenshot(path=str(fallback), full_page=False, type="png")
console.print(f"[yellow]WebP screenshot failed, saved PNG instead: {e}[/yellow]")
return str(fallback)
# Unknown format fallback.
filename = f"{name}_{stamp}.png"
filepath = self.screenshots_dir / filename
self.page.screenshot(path=str(filepath), full_page=False, type="png")
console.print(f"[dim]Screenshot: {filepath.name}[/dim]")
return str(filepath)
except Exception as e:
console.print(f"[yellow]Screenshot failed: {e}[/yellow]")
return None
def capture_live_screenshot(self, name: str = "live") -> Optional[str]:
"""Capture a live preview screenshot, overwriting a single file (constant disk usage)."""
if not self.page:
return None
try:
is_linux = sys.platform.startswith("linux")
is_render = bool(
os.getenv("RENDER")
or os.getenv("RENDER_SERVICE_ID")
or os.getenv("RENDER_EXTERNAL_HOSTNAME")
or os.getenv("RENDER_INSTANCE_ID")
)
fmt = env_str("LIVE_SCREENSHOT_FORMAT", "").strip().lower()
if not fmt:
fmt = env_str("SCREENSHOT_FORMAT", "jpeg" if (is_linux and is_render) else "png").strip().lower()
if fmt == "jpg":
fmt = "jpeg"
default_quality = 45 if (is_linux and is_render) else 70
quality = env_int("LIVE_SCREENSHOT_QUALITY", env_int("SCREENSHOT_QUALITY", default_quality))
if fmt in {"jpeg", "png"}:
ext = "jpg" if fmt == "jpeg" else "png"
filepath = self.screenshots_dir / f"{name}.{ext}"
kwargs: Dict[str, Any] = {"path": str(filepath), "full_page": False, "type": fmt}
if fmt == "jpeg":
kwargs["quality"] = max(1, min(quality, 100))
self.page.screenshot(**kwargs)
return str(filepath)
if fmt == "webp":
filepath = self.screenshots_dir / f"{name}.webp"
try:
from PIL import Image # type: ignore
png_bytes = self.page.screenshot(type="png", full_page=False)
img = Image.open(io.BytesIO(png_bytes))
img.save(str(filepath), "WEBP", quality=max(1, min(quality, 100)), method=6)
return str(filepath)
except Exception:
# Fall back to a PNG live preview.
fallback = self.screenshots_dir / f"{name}.png"
self.page.screenshot(path=str(fallback), full_page=False, type="png")
return str(fallback)
# Unknown format fallback.
fallback = self.screenshots_dir / f"{name}.png"
self.page.screenshot(path=str(fallback), full_page=False, type="png")
return str(fallback)
except Exception:
return None
def _wait_for_chat_ready(self, timeout: int = 60) -> bool:
"""Aspetta che la chat sia "ready" per ricevere il prossimo input.
Tre check combinati (tutti e tre veri = chat ready):
1. **Input editable**: l'input/textarea NON è `disabled` né `readonly`,
ed è interattivo. Quasi tutte le chat-platform disabilitano
l'input mentre il bot streama; tornano editable solo a fine.
2. **No streaming indicator**: nessun elemento visibile con classi
tipiche di streaming attivo (`.streaming`, `[data-streaming="true"]`,
`[aria-busy="true"]`, `[aria-live="polite"]` con dots, "stop"
button, ecc.).
3. **No typing indicator**: usa `_is_typing()` esistente per pattern
testuali ("sto scrivendo", `…`, `▌`).
Se uno dei tre fallisce continua a polling fino al timeout. Più
robusto delle heuristiche text-based perché legge segnali
strutturati DOM emessi dall'app stessa.
Ritorna True se ready entro timeout, False se timeout scaduto.
"""
if not self.page:
return True
start = time.time()
poll_s = 0.4
debug = _browser_debug_enabled()
# Selettori indicatori di streaming attivo. Lista ampia per coprire
# diverse implementazioni: Duolly/Campania, Vercel ai-sdk, ChatGPT
# clone, Botpress, Microsoft WebChat, Gradio, ecc.
STREAM_INDICATORS = (
"[data-streaming='true']",
"[data-state='streaming']",
"[aria-busy='true']",
"button[aria-label*='stop' i]",
"button[aria-label*='ferma' i]",
"button[title*='stop' i]:not([disabled])",
".streaming",
".is-streaming",
".cursor-blink",
"[class*='generating' i]",
".animate-pulse",
)
input_selector = self.selectors.get(
"chat_input",
"textarea, input[type='text'], [contenteditable='true'], [role='textbox']",
)
last_log = 0.0
while time.time() - start < timeout:
elapsed = time.time() - start
# 1. Input editable check
input_ok = False
try:
root = self._get_root() or self.page
loc = root.locator(input_selector).first
if loc.is_visible(timeout=200):
is_disabled = bool(loc.get_attribute("disabled"))
is_readonly = bool(loc.get_attribute("readonly"))
aria_disabled = (loc.get_attribute("aria-disabled") or "").lower() == "true"
input_ok = not (is_disabled or is_readonly or aria_disabled)
except Exception:
input_ok = False
# 2. No streaming indicator
stream_active = False
for sel in STREAM_INDICATORS:
try:
if self.page.locator(sel).first.is_visible(timeout=80):
stream_active = True
break
except Exception:
continue
# 3. No typing indicator (text-based)
typing_active = self._is_typing() if int(elapsed * 10) % 5 == 0 else False
if input_ok and not stream_active and not typing_active:
if debug or elapsed > 5:
console.print(
f"[dim]✓ Chat ready dopo {elapsed:.1f}s "
f"(input enabled, no streaming, no typing)[/dim]"
)
return True
# Log periodico ogni 5s per visibility
if elapsed - last_log >= 5.0:
reasons = []
if not input_ok:
reasons.append("input not editable")
if stream_active:
reasons.append("streaming indicator visible")
if typing_active:
reasons.append("bot is typing")
console.print(
f"[dim]⏳ Aspetto chat ready ({elapsed:.0f}s/{timeout}s): "
f"{', '.join(reasons) or 'unknown'}…[/dim]"
)
last_log = elapsed
time.sleep(poll_s)
return False
def _is_typing(self) -> bool:
"""Check if the bot is currently typing/indicating activity."""
if not self.page:
return False
try:
# Check for common typing indicators
typing_selectors = [
'[data-testid="typing-indicator"]',
'.typing-indicator',
'.typing',
'[data-typing="true"]',
'.cursor-blink',
'[class*="typing"]',
'[class*="generating"]',
'[class*="loading"]',
'article[class*="streaming"]',
'[data-streaming="true"]',
# SVG dots animation
'svg[class*="dots"]',
'.animate-pulse',
'[class*="pulse"]',
]
for selector in typing_selectors:
try:
if self.page.locator(selector).first.is_visible(timeout=100):
return True
except Exception:
continue
# Check for text content indicating streaming/typing
try:
# Avoid scanning the whole DOM every poll (very slow in PaaS containers).
locator = self.page.locator("article")
total = locator.count()
scan_limit = max(env_int("TYPING_TEXT_SCAN_LIMIT", 2), 0)
start = max(0, total - scan_limit) if scan_limit else total
for i in range(start, total):
try:
text = locator.nth(i).text_content() or ""
if any(
indicator in text.lower()
for indicator in [
"sto scrivendo",
"typing",
"generating",
"elaborando",
"in corso",
"...",
"…",
"▌",
"█",
"░",
]
):
return True
except Exception:
continue
except Exception:
pass
return False
except Exception:
return False
def _response_looks_truncated(self, text: str) -> bool:
"""Heuristica: il testo della risposta sembra tagliato a metà?
Caso reale Duolly Campania: il bot sta ancora streamando ma la pausa
tra un token e l'altro supera la soglia di stabilizzazione → il
sistema dichiara "stabile" troppo presto, quindi salviamo
'... **Piazza del Plebisci' invece di '... **Piazza del Plebiscito**'.
Difesa: se il testo termina con segnali di mid-stream (markdown
non chiuso, parola "tronca", nessuna punteggiatura terminale),
consideralo come bot-still-typing e fai ripartire il timer.
I segnali sono volutamente conservativi: meglio aspettare 1-2
cicli in più che salvare una risposta troncata.
"""
if not text:
return False
stripped = text.rstrip()
if not stripped:
return False
# 1. Markdown bold con un numero DISPARI di `**`: il bot stava per
# chiudere una sequenza in grassetto (tipico delle liste "**Nome**").
if stripped.count("**") % 2 == 1:
return True
# 2. Backtick di codice non chiusi.
if stripped.count("`") % 2 == 1:
return True
# 3. Ultima riga è un bullet point o titolo markdown senza contenuto
# (es. la riga finisce con "-", "*", "**" — tipico durante streaming).
# Dopo rstrip, "Lista:\n- " ha last_line = "-" (vuoto bullet).
last_line = stripped.splitlines()[-1].rstrip()
if last_line in ("-", "*", "##", "###"):
return True
if last_line.endswith(("**", "**:", ":**")):
return True
# 4. Termina nel mezzo di una parola in markdown (es. "**Piazza del Plebisci"):
# ultimo char è una lettera ma il token contiene ** all'inizio non chiuso.
# (Già coperto dal punto 1 nella maggior parte dei casi, qui difesa extra.)
# 5. Risposta lunga che NON termina con punteggiatura.
# Nelle chat, le risposte concluse terminano sempre con `.`/`?`/`!`
# (o `:` quando segue una lista, ma in quel caso hanno il bullet
# successivo già coperto da regola #3). Se finisce con una lettera
# è quasi sicuro un troncamento mid-token.
# Caso reale di Duolly: "...Nei sotterran" (9 char tail) — la
# vecchia regola "tail ≤ 3 char" non scattava. Ora controlliamo
# solo l'ultimo carattere, indipendentemente dalla lunghezza
# dell'ultima parola. Soglia 180 char per evitare falsi positivi
# su risposte volutamente brevi tipo "Va bene" o "Buongiorno".
terminators = ".?!\")]}»’'"
if len(stripped) > 180 and stripped[-1].isalpha():
return True
# 6. Risposta media (60-180 char) che termina con una lettera + l'ultima
# parola è "tronca" (parola corta = <8 char, plausibilmente in
# corso di scrittura, es. "...delle prin"). Caso visto 2026-05 su
# HF Space 2vCPU: streaming bot più lento di quanto la heuristica
# 180-char prevedesse, perdevamo le risposte di lunghezza media.
if 60 <= len(stripped) <= 180 and stripped[-1].isalpha():
last_word = stripped.split()[-1] if stripped.split() else ""
# Parola finale < 8 char + non termina in puntuazione: sospetta.
# Evita falsi positivi su risposte legit tipo "Ciao." (terminate).
if 1 <= len(last_word) <= 7 and last_word.isalpha():
# Whitelist: parole brevi che chiudono naturalmente la frase
# (saluti, sì/no, conferme). Se la risposta INTERA è una di
# queste, non è troncata.
short_complete = {
"ciao", "salve", "buongiorno", "buonasera", "buonanotte",
"grazie", "prego", "scusa", "scusi", "ok", "okay", "bene",
"si", "sì", "no", "perfetto", "certo", "certamente",
}
if stripped.lower().strip(".,?!") not in short_complete:
return True
return False
def _looks_like_user_echo(self, candidate_text: str) -> bool:
"""Heuristic: il candidato è davvero il messaggio user appena inviato?
Il sender-detection in `_extract_tracked_messages` può sbagliare quando
la chat-platform sotto test non espone classi/data-attr coerenti per
user vs bot. In quel caso, il messaggio della persona appena inviato
viene marchiato `sender="bot"` e finisce come "nuova bot response".
Confronto: lower-cased, normalize whitespace, trim. Match esatto o
substring con soglia di lunghezza per evitare falsi positivi (es. due
risposte brevi tipo "Sì." o "Ok").
"""
last_user = (self.last_user_message or "").strip()
if not last_user or len(last_user) < 16:
return False
cand = " ".join((candidate_text or "").split()).strip().lower()
ref = " ".join(last_user.split()).strip().lower()
if not cand:
return False
# Match esatto
if cand == ref:
return True
# Substring (la chat può prependere prefissi tipo "AI Tester" / timestamp)
if len(ref) >= 24 and ref in cand:
return True
if len(cand) >= 24 and cand in ref:
return True
return False
def wait_for_bot_response(
self,
timeout: int = 30,
stop_requested=None,
live_screenshot_interval_ms: Optional[int] = None,
on_live_screenshot: Optional[Callable[[str], None]] = None,
) -> Optional[str]:
"""
REFACTORED: Wait for a NEW bot response using snapshot comparison.
This method compares messages against the pre-send snapshot to identify
genuinely new responses, avoiding the confusion with old messages.
"""
import time
if not self.page:
self.last_error = "Browser not initialized"
return None
# Use pre-send snapshot captured by send_message
baseline_snapshot = getattr(self, '_pre_send_snapshot', None)
if baseline_snapshot is None:
console.print("[yellow]⚠ No pre-send snapshot found! Capturing now (may cause sync issues).[/yellow]")
baseline_snapshot = self._capture_snapshot()
debug = _browser_debug_enabled()
is_linux = sys.platform.startswith("linux")
is_render = bool(
os.getenv("RENDER")
or os.getenv("RENDER_SERVICE_ID")
or os.getenv("RENDER_EXTERNAL_HOSTNAME")
or os.getenv("RENDER_INSTANCE_ID")
)
if live_screenshot_interval_ms is None:
# Default to 1fps in Render to emulate a near realtime viewer; local default off.
live_screenshot_interval_ms = env_int("LIVE_SCREENSHOT_INTERVAL_MS", 1000 if (is_linux and is_render) else 0)
live_interval_s = max(int(live_screenshot_interval_ms or 0), 0) / 1000.0
last_live_ts = 0.0
start_time = time.time()
default_poll_ms = 500 if (is_linux and is_render) else 300
poll_ms = max(env_int("BOT_RESPONSE_POLL_MS", default_poll_ms), 100)
poll_seconds = poll_ms / 1000.0
# Stabilization: bot in streaming con pause naturali (>4-5s) venivano
# dichiarati "stabili" prematuramente, quindi la prossima domanda
# partiva su una risposta troncata. Default 6500ms: copre le pause
# tipiche di Duolly/LLM-streaming durante la generazione di liste
# markdown lunghe. Override via env per bot non-streaming.
stabilization_seconds = env_int("BOT_RESPONSE_STABILIZATION_MS", 6500) / 1000.0
# Extended timeout: fino a 240s per bot lenti che generano risposte
# multi-paragrafo. Senza questo, il timeout 120s ritornava risposte
# parziali e il prossimo user message arrivava mentre il bot ancora
# streamava → lo streaming finale veniva catturato come "risposta del
# turno successivo" (off-by-one nel transcript).
extended_timeout = env_int("BOT_RESPONSE_EXTENDED_TIMEOUT", 240)
# Tempo minimo di osservazione del candidato prima di poterlo considerare
# completo, indipendentemente dalla stability. Difensivo per bot che
# rispondono "subito" con un placeholder e poi rimpiazzano con il testo.
min_candidate_age_seconds = env_int("BOT_RESPONSE_MIN_AGE_MS", 1200) / 1000.0
if debug:
console.print(f"[cyan]⏳ wait_for_bot_response START (timeout: {timeout}s, max: {extended_timeout}s)[/cyan]")
console.print(f"[dim] Baseline: {len(baseline_snapshot.messages)} messages, {len(baseline_snapshot.bot_hashes)} bot hashes[/dim]")
console.print("[dim] Looking for NEW messages not in baseline...[/dim]")
# We track the FULL concatenated response (all new bot bubbles for
# this turn), not just one bubble. Bots that emit "answer + sources
# card + suggestion chips" used to lose everything except the last
# bubble.
candidate_text: Optional[str] = None
candidate_found_at: Optional[float] = None
is_extended_mode = False
loop_iteration = 0
def _texts_overlap(a: str, b: str) -> bool:
return bool(a) and bool(b) and (a in b or b in a)
while True:
# Check for stop request
if stop_requested and stop_requested():
self.last_error = "Stopped manually"
return None
# Live preview screenshot (overwrites the same file to keep disk usage constant).
if live_interval_s > 0 and on_live_screenshot:
now = time.time()
if (now - last_live_ts) >= live_interval_s:
path = self.capture_live_screenshot("live")
if path:
try:
on_live_screenshot(path)
except Exception:
pass
last_live_ts = now
# Get current messages
current_msgs = self._extract_tracked_messages()
# Find ALL NEW bot bubbles (not in baseline) and concatenate.
new_bot_msgs = baseline_snapshot.find_new_bot_messages(current_msgs)
# Difensivo: alcune chat-platform non distinguono in modo affidabile
# user vs bot via CSS/data-attr; il messaggio appena inviato dalla
# persona può finire classificato come "bot". Filtra echo user e
# loading indicators dall'aggregazione.
new_bot_msgs = [
m for m in new_bot_msgs
if not self._looks_like_user_echo(m.text)
and not self._is_loading_message(m.text)
]
combined_text = "\n\n".join(m.text for m in new_bot_msgs).strip() if new_bot_msgs else ""
if combined_text:
if debug:
bubble_info = (
f"{len(new_bot_msgs)} bubble(s), {len(combined_text)} chars total"
)
console.print(f"[green]🔍 NEW BOT RESPONSE: {bubble_info}[/green]")
if candidate_text is None:
# First time seeing this turn's response
candidate_text = combined_text
candidate_found_at = time.time()
if debug:
console.print(f"[dim]📨 Tracking new response ({len(combined_text)} chars), stabilizing...[/dim]")
elif not _texts_overlap(candidate_text, combined_text):
# Totally different content (rare): treat as a fresh candidate
if debug:
console.print(f"[dim]📝 Response replaced ({len(combined_text)} chars)[/dim]")
candidate_text = combined_text
candidate_found_at = time.time()
elif candidate_text != combined_text:
# Growing / shrinking but overlapping → reset stability timer
if debug:
console.print(f"[dim]📝 Response growing: {len(combined_text)} chars[/dim]")
candidate_text = combined_text
candidate_found_at = time.time()
else:
# Same combined text → stability check
stable_time = time.time() - candidate_found_at
candidate_age = time.time() - candidate_found_at
typing_now = self._is_typing()
truncated_now = self._response_looks_truncated(candidate_text)
if typing_now or truncated_now:
if truncated_now and not typing_now:
# Visibile sempre (non solo in debug): è la causa
# principale dei "salvati troncati" e l'operatore
# deve poter capire perché stiamo aspettando.
console.print(
f"[yellow]⏳ Response sembra troncata (markdown/parola incompleta), aspetto altri token… ({len(candidate_text)} chars)[/yellow]"
)
elif debug:
cause = "bot is still typing" if typing_now else "response looks mid-stream"
console.print(f"[dim]⌛ stability candidate but {cause} → reset stability timer[/dim]")
candidate_found_at = time.time()
elif stable_time >= stabilization_seconds and candidate_age >= min_candidate_age_seconds:
# Double-check post-stable: aspetto 2s e ricontrollo
# se il testo è ancora cresciuto. Difesa contro bot
# con pause lunghe (>stabilization) tra burst di
# token che ingannerebbero la heuristica di stabilità.
# Se cresciuto → reset timer e continuo polling.
time.sleep(2.0)
try:
recheck_msgs = self._extract_tracked_messages()
recheck_new = baseline_snapshot.find_new_bot_messages(recheck_msgs)
recheck_new = [
m for m in recheck_new
if not self._looks_like_user_echo(m.text)
and not self._is_loading_message(m.text)
]
recheck_text = (
"\n\n".join(m.text for m in recheck_new).strip()
if recheck_new else ""
)
except Exception:
recheck_text = candidate_text
if recheck_text and recheck_text != candidate_text and len(recheck_text) > len(candidate_text):
if debug:
console.print(f"[yellow]⌛ Post-stable recheck: response still growing ({len(candidate_text)}→{len(recheck_text)} chars) → reset timer[/yellow]")
candidate_text = recheck_text
candidate_found_at = time.time()
continue
if debug:
console.print(f"[green]✅ Response stable after {stable_time:.1f}s ({len(candidate_text)} chars)[/green]")
# Reset flag: questo è il path "tutto OK"
self.last_response_was_truncated = False
self.last_bot_message = candidate_text
self.conversation_history.append({"role": "assistant", "content": candidate_text})
return candidate_text
# Check if bot is typing
is_typing = False
# Avoid expensive typing-detection scans on every loop iteration.
if loop_iteration % 5 == 0:
is_typing = self._is_typing()
if is_typing and not is_extended_mode:
is_extended_mode = True
if debug:
console.print(f"[dim]✍️ Bot typing detected, extending timeout to {extended_timeout}s[/dim]")
# Check timeout
current_timeout = extended_timeout if is_extended_mode or is_typing else timeout
elapsed = time.time() - start_time
if elapsed >= current_timeout:
if candidate_text:
# Second-chance: se il candidate appare TRONCATO al
# momento del timeout (markdown unbalanced, parola
# finale senza punteggiatura, ecc.), il bot probabilmente
# stava ancora streamando. Aspettiamo fino a EXTRA 30s
# in più, ricontrollando ogni 2s. Se completa, salviamo
# la versione completa; altrimenti ritorniamo il parziale
# ma con un flag esposto al runner.
if self._response_looks_truncated(candidate_text):
extra_budget_s = env_int("BOT_RESPONSE_TRUNCATED_GRACE_S", 30)
console.print(
f"[yellow]⏳ TIMEOUT con risposta apparentemente troncata ({len(candidate_text)} chars), "
f"aspetto fino a {extra_budget_s}s extra per il completamento…[/yellow]"
)
extra_deadline = time.time() + extra_budget_s
while time.time() < extra_deadline:
time.sleep(2.0)
try:
recheck = self._extract_tracked_messages()
new_msgs = baseline_snapshot.find_new_bot_messages(recheck)
new_msgs = [
m for m in new_msgs
if not self._looks_like_user_echo(m.text)
and not self._is_loading_message(m.text)
]
new_text = (
"\n\n".join(m.text for m in new_msgs).strip()
if new_msgs else ""
)
except Exception:
new_text = ""
if new_text and len(new_text) > len(candidate_text):
if debug:
console.print(f"[dim]📝 grace-period: response grew {len(candidate_text)}→{len(new_text)}[/dim]")
candidate_text = new_text
if not self._response_looks_truncated(candidate_text):
console.print(f"[green]✅ Risposta completata durante il grace period ({len(candidate_text)} chars)[/green]")
break
final_truncated = self._response_looks_truncated(candidate_text)
if final_truncated:
console.print(
f"[red]⚠️ TIMEOUT - risposta ancora troncata dopo grace ({len(candidate_text)} chars). "
"Salvo parziale + flag was_truncated_at_capture per il judge.[/red]"
)
# Flag esposto al runner: il judge legge questo
# attributo e tratta il turno come "insufficient
# sources" invece di valutarne i claim parziali.
self.last_response_was_truncated = True
else:
self.last_response_was_truncated = False
self.last_bot_message = candidate_text
self.conversation_history.append({"role": "assistant", "content": candidate_text})
return candidate_text
if debug:
console.print(f"[red]⏰ TIMEOUT ({current_timeout}s) - NO NEW RESPONSE DETECTED[/red]")
console.print(f"[dim] Baseline had {len(baseline_snapshot.bot_hashes)} bot messages[/dim]")
return None
# Progress logging
loop_iteration += 1
if loop_iteration % 10 == 0:
status = f"{elapsed:.1f}s/{current_timeout}s"
if candidate_text:
status += f" (stabilizing {len(candidate_text)}ch)"
if debug:
console.print(f"[dim]⏳ Waiting... {status}[/dim]")
time.sleep(poll_seconds)
"""
Playwright wrapper for browser automation with human-like interaction.
REFACTORED: Improved response synchronization with message fingerprinting.
"""
import hashlib
import io
import os
import random
import re
import subprocess
import sys
import threading
import time
from collections import Counter
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
from urllib.parse import urljoin
from playwright.sync_api import (
Browser,
BrowserContext,
Error as PlaywrightError,
Frame,
Page,
TimeoutError as PlaywrightTimeoutError,
sync_playwright,
)
from rich.console import Console
from ..utils.env import env_bool, env_int, env_str
from ..utils.selectors import normalize_selector_value
console = Console()
# Lazy import del sanitizer HTML — `nh3` è un binding Rust (Ammonia di Mozilla)
# usato per pulire il raw HTML estratto dal widget del bot prima di salvarlo
# e prima di farlo viaggiare via WebSocket / API. Se nh3 non è installato
# (es. wheel mancante su una piattaforma esotica) facciamo fallback elegante a
# `_sanitize_bot_html_fallback` che ritorna stringa vuota — i template
# renderizzano comunque il plain text. Vedi requirements.txt / pyproject.toml.
try:
import nh3 as _nh3 # type: ignore
except Exception: # pragma: no cover - lib missing on this environment
_nh3 = None
# Whitelist conservativa di tag/attributi consentiti nelle risposte bot.
# Pensata per coprire la formattazione che i widget di chat producono di solito
# (bold, italico, liste, link, codice, headings di basso livello, tabelle
# semplici) escludendo tutto ciò che potrebbe iniettare JS o caricare risorse
# esterne (script, style, iframe, img, video, form, input).
_BOT_HTML_ALLOWED_TAGS = {
"p", "br", "hr", "span", "div",
"b", "strong", "i", "em", "u", "s", "del", "ins", "mark", "sup", "sub",
"a",
"ul", "ol", "li",
"blockquote", "code", "pre", "kbd", "samp",
"h1", "h2", "h3", "h4", "h5", "h6",
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption",
}
_BOT_HTML_ALLOWED_ATTRS = {
# NB: `rel` su <a> non va in whitelist quando passiamo `link_rel` a nh3 —
# il sanitizer lo gestisce da solo (riscrive sempre rel="noopener
# noreferrer"). Se metti "rel" qui, nh3 solleva ValueError.
"a": {"href", "title", "target"},
"span": {"class"},
"div": {"class"},
"th": {"colspan", "rowspan", "scope"},
"td": {"colspan", "rowspan"},
"code": {"class"},
"pre": {"class"},
"ol": {"start", "type"},
}
# Solo schema di URL safe nei link — nh3 di default fa già questo controllo,
# lo esplicitiamo per chiarezza nel caso il sanitizer cambi default.
_BOT_HTML_ALLOWED_URL_SCHEMES = {"http", "https", "mailto", "tel"}
def _sanitize_bot_html(raw_html: str) -> str:
"""Pulisce l'HTML estratto dal widget del bot per renderlo safe in UI.
Strategia:
- Whitelist stretta di tag/attributi (vedi costanti sopra).
- Strip totale di script/style/on*/javascript:.
- Link forzati a target=_blank + rel=noopener,noreferrer (defense-in-depth
contro tabnabbing — il render è dentro un iframe della popup live, ma
meglio dare già al server payload sicuro).
- Truncation a 200 KB per evitare che un widget rumoroso esploda il payload
WebSocket (la popup live mantiene la chat in memoria + ricarica al
reconnect tramite replay_last).
Ritorna stringa vuota se l'input è vuoto o se nh3 non è disponibile —
i caller devono gestire il fallback al plain text.
"""
if not raw_html:
return ""
if _nh3 is None:
return ""
try:
cleaned = _nh3.clean(