"""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()