Spaces:
Runtime error
Runtime error
File size: 119,769 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 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 | """
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)
|