Spaces:
Runtime error
Runtime error
Download src/core/browser_controller_async.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 38.8 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/browser_controller_async.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/core/browser_controller_async.py
-
curl -L -o browser_controller_async.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/browser_controller_async.py
38.8 kB
| """ | |
| Browser Controller using Playwright Async API. | |
| This solves the thread-safety issues with the sync API. | |
| """ | |
| import asyncio | |
| import io | |
| import os | |
| import re | |
| import sys | |
| import time | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional | |
| from rich.console import Console | |
| from ..utils.env import env_int, env_str | |
| try: | |
| from playwright.async_api import async_playwright | |
| except ImportError: | |
| raise ImportError("Playwright not installed. Run: pip install playwright") | |
| console = Console() | |
| class BrowserControllerAsync: | |
| """Async browser controller for interacting with chatbots.""" | |
| def __init__( | |
| self, | |
| selectors: Dict[str, str], | |
| output_dir: str = "./output", | |
| headless: bool = False, | |
| slow_mo: int = 0, | |
| ): | |
| self.selectors = selectors | |
| self.output_dir = Path(output_dir) | |
| self.output_dir.mkdir(parents=True, exist_ok=True) | |
| self.headless = headless | |
| self.slow_mo = slow_mo | |
| self.playwright = None | |
| self.browser = None | |
| self.page = None | |
| self.active_frame = None | |
| self.last_error = None | |
| def _iter_roots(self) -> List[Any]: | |
| """Return page/frame roots with active frame priority.""" | |
| roots: List[Any] = [] | |
| seen: set[int] = set() | |
| if self.active_frame is not None: | |
| roots.append(self.active_frame) | |
| if self.page is not None: | |
| roots.append(self.page) | |
| try: | |
| for frame in self.page.frames: | |
| roots.append(frame) | |
| except Exception: | |
| pass | |
| ordered: List[Any] = [] | |
| for root in roots: | |
| rid = id(root) | |
| if rid in seen: | |
| continue | |
| seen.add(rid) | |
| ordered.append(root) | |
| return ordered | |
| async def _pick_visible_locator( | |
| self, | |
| selector: str, | |
| timeout_ms: int = 800, | |
| enabled_only: bool = False, | |
| max_candidates: int = 60, | |
| ) -> Optional[Any]: | |
| """Pick first visible locator across page/frames.""" | |
| sel = str(selector or "").strip() | |
| if not sel or not self.page: | |
| return None | |
| for root in self._iter_roots(): | |
| try: | |
| loc = root.locator(sel) | |
| total = await loc.count() | |
| except Exception: | |
| continue | |
| for idx in range(min(int(total or 0), max_candidates)): | |
| candidate = loc.nth(idx) | |
| try: | |
| if not await candidate.is_visible(timeout=max(100, int(timeout_ms))): | |
| continue | |
| if enabled_only: | |
| try: | |
| if await candidate.is_disabled(): | |
| continue | |
| except Exception: | |
| pass | |
| if root is not self.page: | |
| self.active_frame = root | |
| return candidate | |
| except Exception: | |
| continue | |
| return None | |
| async def _find_chat_input(self, selector: str) -> Optional[Any]: | |
| """Find a usable chat input with selector first, then fallback heuristics.""" | |
| configured = str(selector or "").strip() | |
| if configured: | |
| picked = await self._pick_visible_locator( | |
| configured, timeout_ms=900, enabled_only=False | |
| ) | |
| if picked is not None: | |
| return picked | |
| keywords = ["message", "chat", "type", "ask", "question", "scrivi", "messaggio", "invia"] | |
| fallback_selector = ( | |
| "textarea, input[type='text'], [contenteditable='true'], [role='textbox']" | |
| ) | |
| best = None | |
| best_score = -1 | |
| best_root = None | |
| for root in self._iter_roots(): | |
| try: | |
| loc = root.locator(fallback_selector) | |
| total = await loc.count() | |
| except Exception: | |
| continue | |
| for idx in range(min(int(total or 0), 80)): | |
| cand = loc.nth(idx) | |
| try: | |
| if not await cand.is_visible(timeout=120): | |
| continue | |
| meta = await cand.evaluate( | |
| """(el) => ({ | |
| placeholder: (el.getAttribute('placeholder') || '').toLowerCase(), | |
| aria: (el.getAttribute('aria-label') || '').toLowerCase(), | |
| role: (el.getAttribute('role') || '').toLowerCase(), | |
| id: (el.id || '').toLowerCase(), | |
| name: (el.getAttribute('name') || '').toLowerCase(), | |
| className: (String(el.className || '')).toLowerCase(), | |
| tag: (el.tagName || '').toLowerCase(), | |
| type: (el.getAttribute('type') || '').toLowerCase(), | |
| editable: !!el.isContentEditable, | |
| disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true' | |
| })""" | |
| ) | |
| if bool(meta.get("disabled")): | |
| continue | |
| text = " ".join( | |
| [ | |
| str(meta.get("placeholder") or ""), | |
| str(meta.get("aria") or ""), | |
| str(meta.get("role") or ""), | |
| str(meta.get("id") or ""), | |
| str(meta.get("name") or ""), | |
| str(meta.get("className") or ""), | |
| ] | |
| ) | |
| score = 0 | |
| for kw in keywords: | |
| if kw in text: | |
| score += 2 | |
| if str(meta.get("tag") or "") == "textarea": | |
| score += 2 | |
| if bool(meta.get("editable")): | |
| score += 2 | |
| if str(meta.get("type") or "") in {"text", "search"}: | |
| score += 1 | |
| if score > best_score: | |
| best = cand | |
| best_score = score | |
| best_root = root | |
| except Exception: | |
| continue | |
| if best is not None: | |
| if best_root is not self.page: | |
| self.active_frame = best_root | |
| return best | |
| opened = await self._attempt_open_chat_widget() | |
| if opened: | |
| try: | |
| await asyncio.sleep(0.7) | |
| except Exception: | |
| pass | |
| if configured: | |
| picked = await self._pick_visible_locator( | |
| configured, timeout_ms=900, enabled_only=False | |
| ) | |
| if picked is not None: | |
| return picked | |
| fallback_picked = await self._pick_visible_locator( | |
| fallback_selector, timeout_ms=900, enabled_only=False | |
| ) | |
| if fallback_picked is not None: | |
| return fallback_picked | |
| return None | |
| async def _get_input_value(self, locator: Any) -> str: | |
| try: | |
| val = await locator.evaluate( | |
| "el => el && (el.isContentEditable ? (el.innerText || el.textContent || '') : (el.value || ''))" | |
| ) | |
| return str(val or "") | |
| except Exception: | |
| return "" | |
| async def _trigger_input_events(self, locator: Any, text: str) -> None: | |
| try: | |
| await locator.evaluate( | |
| """(el, value) => { | |
| if (!el) return; | |
| if (el.isContentEditable) { | |
| if (!el.innerText || !el.innerText.trim()) { | |
| el.innerText = value; | |
| } | |
| } else if ('value' in el && !el.value) { | |
| el.value = value; | |
| } | |
| ['input', 'change', 'keyup'].forEach((name) => { | |
| el.dispatchEvent(new Event(name, { bubbles: true })); | |
| }); | |
| }""", | |
| text, | |
| ) | |
| except Exception: | |
| pass | |
| async def _heuristic_click_send(self, input_locator: Any) -> bool: | |
| try: | |
| clicked = await input_locator.evaluate( | |
| """(el) => { | |
| if (!el) return false; | |
| 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', 'ask']; | |
| const inputRect = el.getBoundingClientRect(); | |
| const buttons = Array.from(root.querySelectorAll('button, [role=\"button\"], input[type=\"submit\"]')); | |
| if (!buttons.length) return false; | |
| const scoreBtn = (btn) => { | |
| if (!btn) return -10; | |
| 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 += 4; | |
| 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, 320 - dist) / 100; | |
| return score; | |
| }; | |
| let best = null; | |
| let bestScore = -Infinity; | |
| for (const btn of buttons) { | |
| const s = scoreBtn(btn); | |
| if (s > bestScore) { | |
| best = btn; | |
| bestScore = s; | |
| } | |
| } | |
| if (!best || bestScore < 0) return false; | |
| best.click(); | |
| return true; | |
| }""" | |
| ) | |
| return bool(clicked) | |
| except Exception: | |
| return False | |
| async def _submit_via_form(self, input_locator: Any) -> bool: | |
| """Try deterministic form submission from the current input element.""" | |
| try: | |
| submitted = await input_locator.evaluate( | |
| """(el) => { | |
| if (!el) return false; | |
| const form = el.closest('form'); | |
| if (!form) return false; | |
| const submit = form.querySelector("button[type='submit'], input[type='submit']"); | |
| if (submit && !(submit.disabled || submit.getAttribute('aria-disabled') === 'true')) { | |
| submit.click(); | |
| return true; | |
| } | |
| if (typeof form.requestSubmit === 'function') { | |
| form.requestSubmit(); | |
| return true; | |
| } | |
| const evt = new Event('submit', { bubbles: true, cancelable: true }); | |
| form.dispatchEvent(evt); | |
| return true; | |
| }""" | |
| ) | |
| return bool(submitted) | |
| except Exception: | |
| return False | |
| async 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: | |
| opened = await 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 && 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 = String(el.className || '').toLowerCase(); | |
| if (cls.includes('chat') || cls.includes('widget') || cls.includes('launcher') || cls.includes('bubble')) s += 3; | |
| const rect = el.getBoundingClientRect(); | |
| if (rect) { | |
| 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) { | |
| best = el; | |
| bestScore = s; | |
| } | |
| } | |
| if (!best || bestScore < 0) return false; | |
| best.click(); | |
| return true; | |
| }""" | |
| ) | |
| return bool(opened) | |
| except Exception: | |
| return False | |
| async def click_new_chat(self) -> bool: | |
| """Try to click a 'new chat' button to reset the conversation.""" | |
| if not self.page: | |
| self.last_error = "Browser not initialized" | |
| 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 = max(env_int("NEW_CHAT_SCAN_LIMIT", 200), 0) | |
| max_ms = max(env_int("NEW_CHAT_MAX_MS", 3000), 0) | |
| def _matches(text: str) -> bool: | |
| if not text: | |
| return False | |
| lowered = text.lower() | |
| if any(d in lowered for d in deny): | |
| return False | |
| return any(p in lowered for p in patterns) | |
| async def _try_root(root: Any) -> bool: | |
| try: | |
| try: | |
| pattern_re = re.compile("|".join(re.escape(p) for p in patterns), re.IGNORECASE) | |
| filtered = root.locator("button, [role='button'], a").filter( | |
| has_text=pattern_re | |
| ) | |
| total = await filtered.count() | |
| for idx in range(min(int(total or 0), max_scan or int(total or 0))): | |
| candidate = filtered.nth(idx) | |
| try: | |
| if await candidate.is_visible(timeout=250): | |
| text = (await candidate.inner_text(timeout=250) or "").strip() | |
| aria = (await candidate.get_attribute("aria-label") or "").strip() | |
| title = (await candidate.get_attribute("title") or "").strip() | |
| if not _matches(" ".join([text, aria, title])): | |
| continue | |
| await candidate.click(timeout=1500) | |
| if root is not self.page: | |
| self.active_frame = root | |
| self.last_error = None | |
| return True | |
| except Exception: | |
| continue | |
| except Exception: | |
| pass | |
| buttons = root.locator("button, [role='button'], a") | |
| total = await buttons.count() | |
| started = time.time() | |
| scanned = 0 | |
| for idx in range(int(total or 0)): | |
| if max_scan and scanned >= max_scan: | |
| break | |
| if max_ms and ((time.time() - started) * 1000) > max_ms: | |
| break | |
| candidate = buttons.nth(idx) | |
| scanned += 1 | |
| try: | |
| if not await candidate.is_visible(timeout=200): | |
| continue | |
| text = (await candidate.inner_text(timeout=250) or "").strip() | |
| aria = (await candidate.get_attribute("aria-label") or "").strip() | |
| title = (await candidate.get_attribute("title") or "").strip() | |
| if not _matches(" ".join([text, aria, title])): | |
| continue | |
| await candidate.click(timeout=1500) | |
| if root is not self.page: | |
| self.active_frame = root | |
| self.last_error = None | |
| return True | |
| except Exception: | |
| continue | |
| except Exception: | |
| return False | |
| return False | |
| if self.active_frame and await _try_root(self.active_frame): | |
| return True | |
| if await _try_root(self.page): | |
| return True | |
| try: | |
| for frame in self.page.frames: | |
| if self.active_frame and frame == self.active_frame: | |
| continue | |
| if await _try_root(frame): | |
| return True | |
| except Exception: | |
| pass | |
| self.last_error = "New chat button not found" | |
| return False | |
| async def start(self, url: str) -> bool: | |
| """Start browser and navigate to URL.""" | |
| try: | |
| self.playwright = await async_playwright().start() | |
| 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 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_options = { | |
| "headless": self.headless, | |
| } | |
| if self.slow_mo > 0: | |
| launch_options["slow_mo"] = self.slow_mo | |
| if is_linux and is_render: | |
| launch_options["args"] = [ | |
| "--no-sandbox", | |
| "--disable-setuid-sandbox", | |
| "--disable-dev-shm-usage", | |
| "--disable-gpu", | |
| ] | |
| self.browser = await self.playwright.chromium.launch(**launch_options) | |
| context_options = { | |
| "viewport": {"width": 1280, "height": 800}, | |
| } | |
| context = await self.browser.new_context(**context_options) | |
| self.page = await context.new_page() | |
| console.print(f"[dim]Navigating to {url}...[/dim]") | |
| await self.page.goto(url, wait_until="networkidle", timeout=30000) | |
| console.print(f"[green]Browser started: {url}[/green]") | |
| return True | |
| except Exception as e: | |
| self.last_error = str(e) | |
| console.print(f"[red]Failed to start browser: {e}[/red]") | |
| return False | |
| async def send_message(self, text: str, human_like: bool = True) -> bool: | |
| """Send a message in the chat.""" | |
| if not self.page: | |
| self.last_error = "Browser not initialized" | |
| return False | |
| try: | |
| input_selector = self.selectors.get( | |
| "chat_input", "textarea, input[type='text'], [contenteditable='true']" | |
| ) | |
| input_locator = await self._find_chat_input(input_selector) | |
| if not input_locator: | |
| self.last_error = ( | |
| f"Chat input not found or not visible for selector: {input_selector}" | |
| ) | |
| console.print(f"[yellow]{self.last_error}[/yellow]") | |
| return False | |
| try: | |
| await input_locator.scroll_into_view_if_needed(timeout=1200) | |
| except Exception: | |
| pass | |
| is_editable = False | |
| try: | |
| is_editable = bool(await input_locator.evaluate("el => !!el.isContentEditable")) | |
| except Exception: | |
| is_editable = False | |
| try: | |
| await input_locator.click(timeout=1500) | |
| except Exception: | |
| pass | |
| if is_editable: | |
| try: | |
| await input_locator.evaluate( | |
| "el => { el.innerText = ''; el.textContent = ''; }" | |
| ) | |
| except Exception: | |
| pass | |
| else: | |
| try: | |
| await input_locator.fill("", timeout=2000) | |
| except Exception: | |
| try: | |
| await input_locator.press("Control+A", timeout=800) | |
| await input_locator.press("Backspace", timeout=800) | |
| except Exception: | |
| pass | |
| if human_like: | |
| try: | |
| if is_editable: | |
| await input_locator.click(timeout=1200) | |
| await self.page.keyboard.type(text, delay=35) | |
| else: | |
| await input_locator.type(text, delay=35, timeout=7000) | |
| except Exception: | |
| if is_editable: | |
| await input_locator.evaluate( | |
| "(el, value) => { el.innerText = value; }", text | |
| ) | |
| else: | |
| await input_locator.fill(text, timeout=2500) | |
| else: | |
| if is_editable: | |
| await input_locator.evaluate("(el, value) => { el.innerText = value; }", text) | |
| else: | |
| await input_locator.fill(text, timeout=2500) | |
| typed_value = (await self._get_input_value(input_locator)).strip() | |
| if text and not typed_value: | |
| try: | |
| await input_locator.evaluate( | |
| """(el, value) => { | |
| if (el.isContentEditable) { | |
| el.innerText = value; | |
| } else { | |
| el.value = value; | |
| } | |
| }""", | |
| text, | |
| ) | |
| except Exception: | |
| pass | |
| await self._trigger_input_events(input_locator, text) | |
| typed_value = (await self._get_input_value(input_locator)).strip() | |
| if text and not typed_value: | |
| self.last_error = ( | |
| "Input did not receive text (selector/contenteditable mismatch)" | |
| ) | |
| console.print(f"[yellow]{self.last_error}[/yellow]") | |
| return False | |
| await self._trigger_input_events(input_locator, text) | |
| sent = False | |
| send_selector = str(self.selectors.get("send_button", "") or "").strip() | |
| if send_selector: | |
| send_btn = await self._pick_visible_locator( | |
| send_selector, timeout_ms=600, enabled_only=True | |
| ) | |
| if send_btn is not None: | |
| try: | |
| await send_btn.click(timeout=1400) | |
| sent = True | |
| except Exception: | |
| sent = False | |
| if not sent: | |
| sent = await self._heuristic_click_send(input_locator) | |
| if not sent: | |
| sent = await self._submit_via_form(input_locator) | |
| if not sent: | |
| for key in ("Enter", "Control+Enter", "Meta+Enter"): | |
| try: | |
| await input_locator.press(key, timeout=900) | |
| sent = True | |
| break | |
| except Exception: | |
| continue | |
| if not sent: | |
| self.last_error = "No send method succeeded (button/keyboard)" | |
| console.print(f"[yellow]{self.last_error}[/yellow]") | |
| return False | |
| await asyncio.sleep(0.25) | |
| post_value = (await self._get_input_value(input_locator)).strip() | |
| if text and post_value and post_value == typed_value: | |
| self.last_error = "Message sent but input not cleared by UI (non-blocking)" | |
| else: | |
| self.last_error = None | |
| console.print(f"[dim]Sent: {text[:50]}...[/dim]") | |
| return True | |
| except Exception as e: | |
| self.last_error = str(e) | |
| console.print(f"[red]Failed to send message: {e}[/red]") | |
| return False | |
| async def get_chat_messages(self) -> List[Dict[str, str]]: | |
| """Extract chat messages from page.""" | |
| if not self.page: | |
| return [] | |
| try: | |
| chat_selector = self.selectors.get( | |
| "chat_messages", | |
| ".message, .chat-bubble, article, [class*='message'], .conversation-item", | |
| ) | |
| best_messages: List[Dict[str, str]] = [] | |
| for root in self._iter_roots(): | |
| try: | |
| loc = root.locator(chat_selector) | |
| total = await loc.count() | |
| except Exception: | |
| continue | |
| messages: List[Dict[str, str]] = [] | |
| for i in range(min(int(total or 0), 220)): | |
| elem = loc.nth(i) | |
| try: | |
| # inner_text rispetta CSS visibility e può escludere | |
| # contenuto in <details> collassati / display:none. | |
| # Confrontiamo con textContent: se diverge molto, | |
| # preferiamo textContent (cattura completa del DOM). | |
| inner = (await elem.inner_text(timeout=2000) or "").strip() | |
| try: | |
| full = (await elem.evaluate("el => el.textContent || ''") or "").strip() | |
| full = re.sub(r"\s+", " ", full) | |
| except Exception: | |
| full = "" | |
| if full and len(full) > len(inner) * 1.3 and len(full) > 80: | |
| text = full | |
| else: | |
| text = inner | |
| if not text or len(text) < 2: | |
| continue | |
| meta = await elem.evaluate( | |
| """(el) => ({ | |
| cls: String(el.className || '').toLowerCase(), | |
| sender: String(el.getAttribute('data-sender') || '').toLowerCase(), | |
| aria: String(el.getAttribute('aria-label') || '').toLowerCase() | |
| })""" | |
| ) | |
| low = " ".join( | |
| [ | |
| str(meta.get("cls") or ""), | |
| str(meta.get("sender") or ""), | |
| str(meta.get("aria") or ""), | |
| ] | |
| ) | |
| tokens = set(re.findall(r"[a-z0-9_-]+", low)) | |
| if tokens & {"user", "from-user", "sent", "outgoing", "human"}: | |
| sender = "user" | |
| elif tokens & {"bot", "assistant", "agent", "from-bot", "incoming", "ai"}: | |
| sender = "bot" | |
| else: | |
| sender = "unknown" | |
| messages.append({"sender": sender, "text": text}) | |
| except Exception: | |
| continue | |
| if len(messages) > len(best_messages): | |
| best_messages = messages | |
| if root is not self.page: | |
| self.active_frame = root | |
| return best_messages | |
| except Exception as e: | |
| console.print(f"[yellow]Error getting messages: {e}[/yellow]") | |
| return [] | |
| async def extract_sidebar_source_links(self) -> List[Dict[str, str]]: | |
| """Collect cited/source links exposed in right-side insight panels.""" | |
| if not self.page: | |
| return [] | |
| try: | |
| raw_links = await 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); | |
| }); | |
| if (roots.size === 0) { | |
| document.querySelectorAll('section, article, div, aside').forEach((node) => { | |
| if (!isVisible(node)) return; | |
| const marker = `${node.getAttribute('data-testid') || ''} ${node.className || ''} ${node.getAttribute('aria-label') || ''}`.toLowerCase(); | |
| const text = toText(node).toLowerCase().slice(0, 240); | |
| if ( | |
| marker.includes('insight') || | |
| marker.includes('source') || | |
| marker.includes('fonti') || | |
| /\\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 or href in seen_urls: | |
| continue | |
| seen_urls.add(href) | |
| links.append({"title": title or href, "url": href}) | |
| return links | |
| async def wait_for_bot_response( | |
| self, timeout: int = 60, stop_requested: Optional[callable] = None | |
| ) -> Optional[str]: | |
| """Wait for bot to respond.""" | |
| if not self.page: | |
| return None | |
| start_time = time.time() | |
| last_messages = [] | |
| stable_count = 0 | |
| console.print(f"[dim]Waiting for bot response (timeout: {timeout}s)...[/dim]") | |
| while time.time() - start_time < timeout: | |
| if stop_requested and stop_requested(): | |
| return None | |
| # Get current messages | |
| messages = await self.get_chat_messages() | |
| # Some bots emit MULTIPLE bubbles per turn (text + sources card, | |
| # text + suggestions, "thinking" + final answer). Taking only | |
| # bot_messages[-1] truncated the response to the last bubble. We | |
| # now concatenate every bot bubble that appears AFTER the most | |
| # recent user message — that's the full response for this turn. | |
| last_user_idx = -1 | |
| for i, m in enumerate(messages): | |
| if m.get("sender") == "user": | |
| last_user_idx = i | |
| current_turn_bots = [ | |
| m["text"] | |
| for i, m in enumerate(messages) | |
| if m.get("sender") == "bot" and i > last_user_idx and m.get("text") | |
| ] | |
| if current_turn_bots: | |
| latest = "\n\n".join(current_turn_bots).strip() | |
| # Check if message is stable (same for 3 checks) | |
| if latest in last_messages: | |
| stable_count += 1 | |
| if stable_count >= 3: | |
| console.print(f"[green]Bot response: {latest[:100]}...[/green]") | |
| return latest | |
| else: | |
| stable_count = 0 | |
| last_messages = [latest] | |
| console.print(f"[dim]Bot typing... ({len(latest)} chars)[/dim]") | |
| await asyncio.sleep(1) | |
| console.print("[yellow]Timeout waiting for bot response[/yellow]") | |
| return None | |
| async def capture_screenshot(self, name: str = "screenshot") -> Optional[str]: | |
| """Capture screenshot.""" | |
| 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("SCREENSHOT_FORMAT", "webp" if (is_linux and is_render) else "png") | |
| .strip() | |
| .lower() | |
| ) | |
| if fmt == "jpg": | |
| fmt = "jpeg" | |
| quality = env_int("SCREENSHOT_QUALITY", 70) | |
| stamp = time.strftime("%Y%m%d_%H%M%S") | |
| if fmt in {"jpeg", "png"}: | |
| ext = "jpg" if fmt == "jpeg" else "png" | |
| filename = f"{name}_{stamp}.{ext}" | |
| filepath = self.output_dir / filename | |
| kwargs: Dict[str, Any] = {"path": str(filepath), "full_page": True, "type": fmt} | |
| if fmt == "jpeg": | |
| kwargs["quality"] = max(1, min(quality, 100)) | |
| await self.page.screenshot(**kwargs) | |
| console.print(f"[dim]Screenshot: {filepath}[/dim]") | |
| return str(filepath) | |
| if fmt == "webp": | |
| filename = f"{name}_{stamp}.webp" | |
| filepath = self.output_dir / filename | |
| try: | |
| from PIL import Image # type: ignore | |
| png_bytes = await self.page.screenshot(type="png", full_page=True) | |
| 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}[/dim]") | |
| return str(filepath) | |
| except Exception: | |
| fallback = self.output_dir / f"{name}_{stamp}.png" | |
| await self.page.screenshot(path=str(fallback), full_page=True, type="png") | |
| console.print(f"[dim]Screenshot: {fallback}[/dim]") | |
| return str(fallback) | |
| # Unknown format fallback. | |
| filename = f"{name}_{stamp}.png" | |
| filepath = self.output_dir / filename | |
| await self.page.screenshot(path=str(filepath), full_page=True, type="png") | |
| console.print(f"[dim]Screenshot: {filepath}[/dim]") | |
| return str(filepath) | |
| except Exception as e: | |
| console.print(f"[yellow]Screenshot failed: {e}[/yellow]") | |
| return None | |
| async def cleanup(self): | |
| """Close browser.""" | |
| if self.page: | |
| await self.page.close() | |
| if self.browser: | |
| await self.browser.close() | |
| if self.playwright: | |
| await self.playwright.stop() | |
| console.print("[dim]Browser closed[/dim]") | |