Spaces:
Running
Running
File size: 40,306 Bytes
6eb6c4e 9fa7eea | 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 | """Browser management with Playwright for persistent contexts."""
import asyncio
import logging
import os
import time
import uuid
from collections.abc import Callable
from pathlib import Path
from typing import Any, cast
from playwright.async_api import (
Browser,
BrowserContext,
Page,
Playwright,
async_playwright,
)
from ..config import settings
from ..protocol import ActionType, SessionInfo, SessionStatus, TaskStep
from .errors import (
UNKNOWN,
ClassifiedError,
classify_launch_error,
classify_os_error,
write_diagnostic_log,
)
from .session import (
ProfileLock,
acquire_profile_lock,
preflight_profile_dir,
redact_path,
)
_FIREFOX_RUNTIME_ENV = {
"MOZ_DISABLE_CONTENT_SANDBOX": "1",
"MOZ_DISABLE_GFX_SANDBOX": "1",
"MOZ_DISABLE_RDD_SANDBOX": "1",
"MOZ_DISABLE_SOCKET_PROCESS_SANDBOX": "1",
}
# Channels a session (or the global default) may pin: the Playwright bundled
# Chromium, the real installed Chrome/Edge via channel discovery, Firefox and
# WebKit. Mirrored by the public /api/engines endpoint and the UI pickers.
SUPPORTED_CHANNELS = ("chromium", "chrome", "msedge", "firefox", "webkit")
logger = logging.getLogger(__name__)
def _resolve_writable_dir(
configured: Path,
fallback: Path,
on_fallback: Callable[[ClassifiedError], None] | None = None,
) -> Path:
"""Return the first directory where this process can create a child.
Failures raise a ClassifiedError (plan Table 4) carrying the OS-derived
code β the audit's manager.py:34 raising site β plus one aggregate
diagnostic log with the redacted per-candidate failures.
When the CONFIGURED directory fails but a fallback works, ``on_fallback``
receives the classified failure so the caller can report the relocation
instead of silently using a different profile.
"""
candidates = [configured]
if fallback != configured:
candidates.append(fallback)
failures: list[str] = []
classified: ClassifiedError | None = None
last_error: OSError | None = None
first_failure: ClassifiedError | None = None
for candidate in candidates:
probe: Path | None = None
file_probe: Path | None = None
try:
candidate.mkdir(parents=True, exist_ok=True)
probe = candidate / f".write-test-{uuid.uuid4().hex}"
probe.mkdir()
probe.rmdir()
# A directory probe alone is not enough: an ACL can permit
# CreateDirectory while denying CreateFile, and the app writes
# ordinary files (the task metadata, the browser profile). Probe
# a real file too, so such a root is rejected here instead of
# failing later as an unexplained write error.
file_probe = candidate / f".write-test-{uuid.uuid4().hex}.tmp"
file_probe.write_text("probe", encoding="utf-8")
file_probe.unlink()
if first_failure is not None and on_fallback is not None:
on_fallback(first_failure)
return candidate
except OSError as exc:
last_error = exc
classified = classify_os_error(
exc, path=candidate, operation="resolve writable browser storage directory"
)
if first_failure is None:
first_failure = classified
failures.append(f"{candidate}: {exc}")
if probe is not None and probe.exists():
try:
probe.rmdir()
except OSError:
logger.debug("Could not remove browser storage probe %s", probe, exc_info=True)
if file_probe is not None and file_probe.exists():
try:
file_probe.unlink()
except OSError:
logger.debug(
"Could not remove browser storage file probe %s",
file_probe,
exc_info=True,
)
if classified is None or last_error is None:
classified = ClassifiedError(UNKNOWN, operation="resolve writable browser storage directory")
err = ClassifiedError(
classified.code,
operation="resolve writable browser storage directory",
diagnostic_id=classified.diagnostic_id,
detail="No writable browser storage directory: " + "; ".join(failures),
)
write_diagnostic_log(err, last_error)
raise err from last_error
def _app_runtime_dir() -> Path:
"""Return a writable-by-default runtime root beside the backend source."""
return Path(__file__).resolve().parents[3] / ".browser-runtime"
class BrowserManager:
"""Manages Playwright browser instances and persistent contexts."""
def __init__(self) -> None:
self._playwright: Playwright | None = None
self._browser: Browser | None = None
# Per-channel browser cache for NON-default channels (Firefox + Chrome
# dual operation): the default channel keeps the legacy ``_browser``
# slot so existing fixtures/tests keep working; a session created with
# an explicit ``engine`` gets a browser keyed by that channel.
self._browsers: dict[str, Browser] = {}
# Engine each context was created with, so a session reusing a context
# reports the engine that context actually runs (never a made-up one).
self._context_engines: dict[str, str] = {}
self._contexts: dict[str, BrowserContext] = {}
self._pages: dict[str, Page] = {}
self._session_info: dict[str, SessionInfo] = {}
self._context_lock = asyncio.Lock()
self._runtime_dir: Path | None = None
self._browser_user_data_dir: Path | None = None
self._original_runtime_env: dict[str, str | None] | None = None
# OS-level profile locks this process holds (plan Chapter 6 item 2);
# released on clean shutdown β foreign/stale locks are never touched.
self._profile_locks: dict[str, ProfileLock] = {}
# Set when the CONFIGURED profile directory could not be used and the
# manager fell back to its own runtime profile. None when the
# configured profile is in use.
self._profile_root_notice: dict[str, Any] | None = None
# Session reaper: mark CREATED sessions with no activity > 10 min as STALLED
self._reaper_task: asyncio.Task | None = None
self._reaper_interval = 60 # seconds
self._stalled_threshold = 600 # 10 minutes in seconds
def profile_root_notice(self) -> dict[str, Any] | None:
"""Report the configured-profile failure, when there was one.
The fallback keeps the app running, but the user must know that their
own profile (and its logins) is not the one in use.
"""
return self._profile_root_notice
async def start(self) -> None:
"""Start Playwright after preparing writable browser runtime paths."""
if self._playwright is not None:
return
self._prepare_runtime()
try:
self._playwright = await async_playwright().start()
except Exception:
self._restore_runtime_environment()
raise
# Start session reaper: mark CREATED sessions with no activity > 10 min as STALLED
if self._reaper_task is None or self._reaper_task.done():
self._reaper_task = asyncio.create_task(self._run_session_reaper())
async def _run_session_reaper(self) -> None:
"""Periodically scan for stalled CREATED sessions and mark them as STALLED."""
while True:
try:
await asyncio.sleep(self._reaper_interval)
now = time.time()
for session_id, session in list(self._session_info.items()):
if session.status == SessionStatus.CREATED:
# If session was created > threshold seconds ago and never updated
if now - session.created_at > self._stalled_threshold:
session.status = SessionStatus.STALLED
session.error = f"Session stalled: no activity since creation (>{self._stalled_threshold // 60} min)"
session.updated_at = now
logger.warning(
"Session %s marked STALLED: created at %.0f, now %.0f, threshold %ds",
session_id, session.created_at, now, self._stalled_threshold
)
except asyncio.CancelledError:
break
except Exception:
logger.exception("Session reaper error")
async def stop_reaper(self) -> None:
"""Stop the session reaper task."""
if self._reaper_task and not self._reaper_task.done():
self._reaper_task.cancel()
try:
await self._reaper_task
except asyncio.CancelledError:
pass
def _prepare_runtime(self) -> None:
runtime_root = _resolve_writable_dir(_app_runtime_dir(), Path.cwd() / ".browser-runtime")
temp_dir = _resolve_writable_dir(runtime_root / "tmp", runtime_root / "tmp")
configured_profile = Path(settings.browser_user_data_dir).expanduser()
profile_fallback = runtime_root / "profiles"
notice: dict[str, Any] = {}
def _record_relocation(failure: ClassifiedError) -> None:
"""The configured profile was unusable: say so, loudly and usefully.
Falling back keeps the app working (that is what makes it work
under a restricted runtime), but the user's own profile - with
their logins - is then not used. That must be visible, with the
cause, the fix and a diagnostic id.
"""
active = profile_fallback
message = (
f"The configured browser profile directory {configured_profile} "
f"is not usable ({failure.code}: {failure.message or 'access denied'}). "
f"Dracull is using {active} instead, so any logins saved in the "
"configured profile are NOT available. Point BROWSER_USER_DATA_DIR at "
"a writable directory, or fix the permissions on the configured one, "
"to use it."
)
err = ClassifiedError(
failure.code,
message=message,
path=configured_profile,
operation="browser profile directory",
diagnostic_id=failure.diagnostic_id,
)
write_diagnostic_log(err)
notice.update(
{
"code": err.code,
"message": err.message,
"diagnostic_id": err.diagnostic_id,
# Redacted like every other user-visible path: the raw
# value would carry the Windows user name (and any
# secret-shaped path component) into the UI.
"configured_path": redact_path(configured_profile),
"active_path": redact_path(active),
}
)
logger.warning(
"Configured browser profile directory is not writable; using %s (%s)",
active,
err.code,
)
profile_root = _resolve_writable_dir(
configured_profile, profile_fallback, on_fallback=_record_relocation
)
self._runtime_dir = runtime_root
self._browser_user_data_dir = profile_root
self._profile_root_notice = notice or None
# Keep Playwright's browser cache beside the app. The inherited global
# cache can be writable to the shell but denied to the Python runtime.
# EXCEPTION: when the inherited PLAYWRIGHT_BROWSERS_PATH already ships
# browser payloads (Playwright base images bake /ms-playwright with the
# exact revisions the pinned driver expects β HF Spaces, CI containers),
# keep it: redirecting to an app-local empty cache made the launch die
# with BROWSER_NOT_INSTALLED even though the browsers were on disk.
inherited = os.environ.get("PLAYWRIGHT_BROWSERS_PATH")
inherited_has_browsers = False
if inherited:
try:
inherited_has_browsers = any(
entry.is_dir()
and (entry.name.startswith("chromium-") or entry.name.startswith("firefox-"))
for entry in Path(inherited).iterdir()
)
except OSError:
inherited_has_browsers = False
env_keys = ("TEMP", "TMP", "TMPDIR")
if inherited_has_browsers:
self._original_runtime_env = {key: os.environ.get(key) for key in env_keys}
logger.info("Using inherited Playwright browser cache at %s", inherited)
else:
self._original_runtime_env = {
key: os.environ.get(key)
for key in ("TEMP", "TMP", "TMPDIR", "PLAYWRIGHT_BROWSERS_PATH")
}
browser_cache = _resolve_writable_dir(
runtime_root / "playwright-browsers",
runtime_root / "playwright-browsers",
)
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(browser_cache)
for key in ("TEMP", "TMP", "TMPDIR"):
os.environ[key] = str(temp_dir)
def _restore_runtime_environment(self) -> None:
if self._original_runtime_env is None:
return
for key, value in self._original_runtime_env.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
self._original_runtime_env = None
@property
def browser_user_data_dir(self) -> Path:
"""Return the active profile root, including an environment fallback."""
return self._browser_user_data_dir or Path(settings.browser_user_data_dir).expanduser()
@property
def browser_artifacts_dir(self) -> Path:
"""Return the writable root for screenshots and other artifacts."""
return (self._runtime_dir or self.browser_user_data_dir.parent) / "screenshots"
def _browser_engine(self, engine: str | None = None) -> tuple[Any, dict[str, Any]]:
"""Resolve a channel to its Playwright engine + launch options.
``engine`` defaults to the configured global channel so existing
callers (and tests) keep their semantics; a session may pass an
explicit channel to run Firefox while the default stays Chrome (or
vice versa).
"""
if self._playwright is None:
raise RuntimeError("BrowserManager.start() must be called before use")
engine = (engine or settings.browser_channel).lower()
# chromium-family channels: the Playwright bundled engine ("chromium")
# or the real installed browsers ("chrome", "msedge") via Playwright
# channel discovery.
chromium_channels = {"chromium", "chrome", "msedge"}
if engine not in {*chromium_channels, "firefox", "webkit"}:
raise ValueError(f"Unsupported browser channel: {engine}")
if engine in chromium_channels:
browser_type = self._playwright.chromium
else:
browser_type = getattr(self._playwright, engine)
options: dict[str, Any] = {"headless": settings.browser_headless}
if engine in chromium_channels:
options["channel"] = engine
if engine == "firefox":
# Firefox's child-process sandbox cannot initialize in this
# restricted Windows runtime; scope the compatibility flags to
# Firefox instead of weakening the server process.
options["env"] = {**os.environ, **_FIREFOX_RUNTIME_ENV}
# A headed Firefox also needs its GPU subprocess β when that spawn
# is denied (diagnostic logs: SB::LA::SpawnTarget 0x80070005) the
# browser crashes mid-task with exit 0xC0000005. Headless runs the
# same engine without a compositor, so it stays the safe default;
# browser_firefox_force_headless=false restores headed mode.
if not settings.browser_headless and settings.browser_firefox_force_headless:
logger.warning(
"Firefox headed mode crashes when the GPU subprocess cannot "
"spawn; forcing headless (disable with "
"BROWSER_FIREFOX_FORCE_HEADLESS=false)."
)
options["headless"] = True
return browser_type, options
async def _get_or_create_browser(self, engine: str | None = None) -> Browser:
"""Get or create a browser instance for the requested channel."""
channel = (engine or settings.browser_channel).lower()
if channel == settings.browser_channel.lower():
# Default channel: legacy single-slot cache (fixtures seed it).
if self._browser is None:
browser_type, options = self._browser_engine(channel)
self._browser = await browser_type.launch(**options)
return self._browser
cached = self._browsers.get(channel)
if cached is None:
browser_type, options = self._browser_engine(channel)
cached = await browser_type.launch(**options)
self._browsers[channel] = cached
return cached
async def stop(self) -> None:
"""Stop browser and cleanup without releasing live-profile locks.
A profile lock is evidence that its context/browser may still own the
profile. It is therefore released only after that owner is confirmed
closed. If closing a context fails, the context and its lock remain
registered so the failure can be retried and the lock stays visible.
"""
first_error: Exception | None = None
closed_context_ids: set[str] = set()
for context_id, context in list(self._contexts.items()):
try:
await context.close()
except Exception as exc:
first_error = first_error or exc
logger.exception(
"Failed to close browser context %s; retaining its profile lock",
context_id,
)
continue
closed_context_ids.add(context_id)
browser_closed = False
if self._browser:
try:
await self._browser.close()
browser_closed = True
except Exception as exc:
first_error = first_error or exc
logger.exception(
"Failed to close browser; retaining profile locks it may own"
)
# Close every extra channel browser (Firefox next to Chrome, etc.)
extra_channels_closed: set[str] = set()
for channel, extra in list(self._browsers.items()):
try:
await extra.close()
extra_channels_closed.add(channel)
except Exception as exc:
first_error = first_error or exc
logger.exception(
"Failed to close %s browser; retaining profile locks it may own",
channel,
)
for channel in extra_channels_closed:
self._browsers.pop(channel, None)
if self._playwright:
try:
await self._playwright.stop()
except Exception as exc:
first_error = first_error or exc
logger.exception("Failed to stop Playwright")
# A successfully closed context confirms that its profile owner is
# gone. A successfully closed shared browser confirms all contexts it
# owns are gone. Everything else retains its lock and registry state.
confirmed_closed = closed_context_ids | (
set(self._contexts) if browser_closed else set()
)
for context_id in confirmed_closed:
self._contexts.pop(context_id, None)
lock = self._profile_locks.get(context_id)
if lock is None:
continue
if lock.release():
self._profile_locks.pop(context_id, None)
else:
logger.error(
"Could not release profile lock for closed context %s; "
"leaving the lock file in place as evidence",
context_id,
)
for session_id, session in list(self._session_info.items()):
if not session.context_id or session.context_id in confirmed_closed:
self._session_info.pop(session_id, None)
self._pages.pop(session_id, None)
if browser_closed or not self._browser:
self._browser = None
if not self._playwright or first_error is None:
self._playwright = None
self._browsers.clear()
self._context_engines.clear()
self._runtime_dir = None
self._browser_user_data_dir = None
self._restore_runtime_environment()
if first_error is not None:
raise first_error
await self.stop_reaper()
async def create_session(
self,
session_id: str,
context_id: str | None = None,
engine: str | None = None,
) -> SessionInfo:
"""Create a new browser session with persistent context.
``engine`` pins this session to a channel (``chrome`` or ``firefox``
among others) independent of the global default β the dual-browser
entry point. Reusing an existing ``context_id`` runs on that context's
original engine regardless of the requested one, and the reported
engine reflects that reality.
"""
requested = (engine or settings.browser_channel).lower()
if requested not in SUPPORTED_CHANNELS:
raise ValueError(f"Unsupported browser channel: {requested}")
async with self._context_lock:
# Get or create persistent context
if context_id and context_id in self._contexts:
context = self._contexts[context_id]
actual_engine = self._context_engines.get(context_id, requested)
else:
context_id = context_id or f"ctx_{uuid.uuid4().hex[:8]}"
actual_engine = requested
context = await self._create_persistent_context(
context_id, engine=actual_engine
)
self._contexts[context_id] = context
# Create new page
page = await context.new_page()
page.set_default_timeout(settings.browser_timeout)
self._pages[session_id] = page
# Create session info
session_info = SessionInfo(
session_id=session_id,
context_id=context_id,
status=SessionStatus.CREATED,
# D-1: epoch seconds β UI history filters / date rendering treat
# these as wall-clock time, not the loop's monotonic clock.
created_at=time.time(),
updated_at=time.time(),
tabs_count=len(context.pages),
engine=actual_engine,
)
self._session_info[session_id] = session_info
return session_info
async def _create_persistent_context(
self, context_id: str, engine: str | None = None
) -> BrowserContext:
"""Create a browser context, using a profile when supported.
The two audit-identified raising sites are classified here: the
per-context ``mkdir`` (profile operation β Table 4 profile codes) and
the browser launch (driver failure β BROWSER_LAUNCH_FAILED /
BROWSER_NOT_INSTALLED). Firefox uses a non-persistent context because
its Windows persistent launch path fails under this restricted runtime;
live sessions still keep tabs and cookies until the backend stops.
"""
user_data_dir = self.browser_user_data_dir / context_id
try:
user_data_dir.mkdir(parents=True, exist_ok=True)
except OSError as exc:
err = classify_os_error(
exc, path=user_data_dir, operation="create profile directory"
)
write_diagnostic_log(err, exc)
raise err from exc
# Single owner per profile (plan Chapter 6 item 2): the OS lock makes
# a second process fail classified instead of silently sharing a live
# profile β the audit reproduced that duplicate-launch success before
# this guard existed. Our own lock is released on any failure below.
channel = (engine or settings.browser_channel).lower()
lock = acquire_profile_lock(
user_data_dir, operation="launch persistent context"
)
try:
preflight_profile_dir(user_data_dir)
browser_type, options = self._browser_engine(channel)
try:
if channel == "firefox":
browser = await self._get_or_create_browser(channel)
context = await browser.new_context(
viewport={"width": 1280, "height": 720},
record_video_dir=(
str(user_data_dir / "videos")
if not settings.browser_headless
else None
),
)
else:
context = await browser_type.launch_persistent_context(
user_data_dir=str(user_data_dir),
**options,
viewport={"width": 1280, "height": 720},
record_video_dir=(
str(user_data_dir / "videos")
if not settings.browser_headless
else None
),
)
except Exception as exc:
operation = (
"launch_browser_context"
if channel == "firefox"
else "launch_persistent_context"
)
err = classify_launch_error(exc, path=user_data_dir, operation=operation)
write_diagnostic_log(err, exc)
raise err from exc
except BaseException:
lock.release() # our own lock only; foreign locks are never touched
raise
self._profile_locks[context_id] = lock
self._context_engines[context_id] = channel
# Playwright context objects are untyped at this boundary; keep the
# declared return type honest instead of leaking Any into callers.
return cast(BrowserContext, context)
async def get_page(self, session_id: str) -> Page | None:
"""Get the page for a session."""
return self._pages.get(session_id)
async def get_context(self, session_id: str) -> BrowserContext | None:
"""Get the context for a session."""
session = self._session_info.get(session_id)
if session and session.context_id:
return self._contexts.get(session.context_id)
return None
async def execute_step(
self,
session_id: str,
step: TaskStep,
) -> dict[str, Any]:
"""Execute a single task step."""
page = await self.get_page(session_id)
if not page:
raise ValueError(f"No page found for session {session_id}")
action = step.action
selector = step.selector
value = step.value
url = step.url
wait_for = step.wait_for
timeout = step.timeout or settings.browser_timeout
try:
if action == ActionType.NAVIGATE:
# Defense in depth: the task engine shares the same SSRF guard
# as the /api/browse routes β no file/ftp schemes, no
# loopback/private/reserved hosts (validated post-DNS).
from ..net_guard import (
policy_from_settings,
validate_public_http_url,
)
if not url:
raise ValueError("Navigate action requires url")
safe_url = validate_public_http_url(url, policy=policy_from_settings())
await page.goto(safe_url, wait_until="domcontentloaded", timeout=timeout)
return {"url": page.url, "title": await page.title()}
elif action == ActionType.CLICK:
if not selector:
raise ValueError("Click action requires selector")
await page.click(selector, timeout=timeout)
return {"clicked": selector}
elif action == ActionType.TYPE:
if not selector:
raise ValueError("Type action requires selector")
await page.fill(selector, value or "", timeout=timeout)
return {"typed": selector, "value": value}
elif action == ActionType.HOVER:
if not selector:
raise ValueError("Hover action requires selector")
await page.hover(selector, timeout=timeout)
return {"hovered": selector}
elif action == ActionType.SCROLL:
if value:
await page.evaluate(f"window.scrollBy(0, {value})")
else:
await page.evaluate("window.scrollBy(0, window.innerHeight)")
return {"scrolled": True}
elif action == ActionType.WAIT:
if wait_for:
await page.wait_for_selector(wait_for, timeout=timeout)
elif selector:
await page.wait_for_selector(selector, timeout=timeout)
else:
await asyncio.sleep(timeout / 1000)
return {"waited": True}
elif action == ActionType.EXTRACT:
if not selector:
raise ValueError("Extract action requires selector")
elements = await page.query_selector_all(selector)
data = []
for el in elements:
text = await el.inner_text()
data.append(text)
return {"extracted": data, "count": len(data)}
elif action == ActionType.SCREENSHOT:
screenshot = await page.screenshot(full_page=True, type="png")
import base64
return {"screenshot": base64.b64encode(screenshot).decode()}
elif action == ActionType.EXECUTE_JS:
if not value:
raise ValueError("Execute JS action requires script")
result = await page.evaluate(value)
return {"result": result}
elif action == ActionType.NEW_TAB:
new_page = await page.context.new_page()
new_session_id = f"{session_id}_tab_{uuid.uuid4().hex[:6]}"
self._pages[new_session_id] = new_page
return {"new_session_id": new_session_id}
elif action == ActionType.SWITCH_TAB:
if not value:
raise ValueError("Switch tab requires session_id")
target_page = self._pages.get(value)
if not target_page:
raise ValueError(f"Tab session {value} not found")
self._pages[session_id] = target_page
return {"switched_to": value}
elif action == ActionType.CLOSE_TAB:
await page.close()
return {"closed": True}
elif action == ActionType.BACK:
await page.go_back(timeout=timeout)
return {"back": True}
elif action == ActionType.FORWARD:
await page.go_forward(timeout=timeout)
return {"forward": True}
elif action == ActionType.REFRESH:
await page.reload(timeout=timeout)
return {"refreshed": True}
elif action == ActionType.SET_VIEWPORT:
width = step.metadata.get("width", 1280)
height = step.metadata.get("height", 720)
await page.set_viewport_size({"width": width, "height": height})
return {"viewport": {"width": width, "height": height}}
elif action == ActionType.GET_TEXT:
if not selector:
raise ValueError("Get text action requires selector")
text = await page.inner_text(selector)
return {"text": text}
elif action == ActionType.GET_ATTRIBUTE:
if not selector or not value:
raise ValueError("Get attribute requires selector and attribute name")
attr = await page.get_attribute(selector, value)
return {"attribute": attr}
elif action == ActionType.CHECK_EXISTS:
if not selector:
raise ValueError("Check exists requires selector")
exists = await page.query_selector(selector) is not None
return {"exists": exists}
elif action == ActionType.PRESS_KEY:
if not value:
raise ValueError("Press key requires key name")
await page.keyboard.press(value)
return {"pressed": value}
elif action == ActionType.FORM_SUBMIT:
# A form submit is a sensitive action, so HITL gates it. The
# target comes from the step's selector; metadata may override
# it with an explicit target selector.
target = step.metadata.get("target") or selector
if not target:
raise ValueError("Form submit requires a target selector")
await page.eval_on_selector(
target,
"el => el.requestSubmit ? el.requestSubmit() : el.submit()",
)
return {"submitted": target}
else:
raise ValueError(f"Unknown action: {action}")
except Exception as e:
# Capture a screenshot for debugging; failure is non-fatal. The
# bytes are written to disk so the image is actually available β
# capturing and discarding them helped nobody.
try:
shot = await page.screenshot(full_page=True, type="png")
shots_dir = self.browser_artifacts_dir
shots_dir.mkdir(parents=True, exist_ok=True)
shot_path = shots_dir / f"error_{session_id}_{int(time.time() * 1000)}.png"
shot_path.write_bytes(shot)
logger.info("Error screenshot saved to %s", shot_path)
except Exception:
logger.debug("Failed to capture error screenshot", exc_info=True)
raise RuntimeError(f"Step failed: {action.value} - {e!s}") from e
async def close_session(self, session_id: str) -> None:
"""Close a session and its page."""
page = self._pages.pop(session_id, None)
if page:
await page.close()
session = self._session_info.pop(session_id, None)
if session and session.context_id:
# Check if context has other pages
context = self._contexts.get(session.context_id)
if context and len(context.pages) == 0:
# Keep context for persistence
pass
async def list_sessions(self) -> list[SessionInfo]:
"""List all active sessions."""
return list(self._session_info.values())
async def get_session_status(self, session_id: str) -> SessionInfo | None:
"""Get session status."""
return self._session_info.get(session_id)
async def update_session_status(
self,
session_id: str,
status: SessionStatus,
current_task: str | None = None,
task_progress: float | None = None,
url: str | None = None,
error: str | None = None,
) -> None:
"""Update session status."""
session = self._session_info.get(session_id)
if session:
session.status = status
session.updated_at = time.time() # D-1: epoch seconds (see create_session)
if current_task is not None:
session.current_task = current_task
if task_progress is not None:
session.task_progress = task_progress
if url is not None:
session.url = url
if error is not None:
session.error = error
if session.context_id:
context = self._contexts.get(session.context_id)
if context:
session.tabs_count = len(context.pages)
# Context management methods
async def list_contexts(self) -> list[dict]:
"""List all persistent contexts."""
contexts = []
for context_id in self._contexts:
sessions_count = sum(1 for s in self._session_info.values() if s.context_id == context_id)
contexts.append({
"context_id": context_id,
"name": context_id,
"created_at": time.time(), # D-1: epoch seconds
"session_count": sessions_count,
})
return contexts
async def create_context(self, context_id: str, name: str) -> dict:
"""Create a new persistent context."""
# Same serialization as create_session (audit finding iii): the
# persistent-context launch must not interleave with concurrent
# session creation on the shared registry.
async with self._context_lock:
context = await self._create_persistent_context(context_id)
self._contexts[context_id] = context
return {"context_id": context_id, "name": name}
async def delete_context(self, context_id: str) -> bool:
"""Delete a persistent context after confirming its close succeeded.
Registry and lock removal happen only after ``context.close()`` returns
successfully. On failure both remain reachable, so the caller can
retry and the lock continues to protect a possibly-live profile.
"""
context = self._contexts.get(context_id)
if context is None:
return False
try:
await context.close()
except Exception:
logger.exception(
"Failed to close browser context %s; retaining it and its profile lock",
context_id,
)
raise
self._contexts.pop(context_id, None)
lock = self._profile_locks.pop(context_id, None)
if lock is not None:
lock.release() # our own lock; content-verified
return True
# Global browser manager instance
browser_manager = BrowserManager() |