Spaces:
Runtime error
Runtime error
File size: 38,751 Bytes
ed86a97 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 | """
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]")
|