97 lines
2.7 KiB
Python
97 lines
2.7 KiB
Python
"""Browser diagnostic capture utilities for action error debugging.
|
|
|
|
Provides utilities to capture screenshots, HTML snapshots, and console logs
|
|
when actions fail, enabling better debugging in headless/CI environments.
|
|
"""
|
|
|
|
import base64
|
|
from datetime import datetime, timezone
|
|
|
|
from playwright.async_api import Page
|
|
|
|
from guide.app.models.domain.models import DebugInfo
|
|
|
|
|
|
async def capture_screenshot(page: Page) -> str | None:
|
|
"""Capture page screenshot as base64-encoded PNG.
|
|
|
|
Args:
|
|
page: The Playwright page instance
|
|
|
|
Returns:
|
|
Base64-encoded PNG image data, or None if capture fails
|
|
"""
|
|
try:
|
|
screenshot_bytes = await page.screenshot()
|
|
return base64.b64encode(screenshot_bytes).decode("utf-8")
|
|
except Exception:
|
|
# Return None if screenshot fails (e.g., page already closed)
|
|
return None
|
|
|
|
|
|
async def capture_html(page: Page) -> str | None:
|
|
"""Capture page HTML content.
|
|
|
|
Args:
|
|
page: The Playwright page instance
|
|
|
|
Returns:
|
|
HTML page content, or None if capture fails
|
|
"""
|
|
try:
|
|
return await page.content()
|
|
except Exception:
|
|
# Return None if HTML capture fails (e.g., page already closed)
|
|
return None
|
|
|
|
|
|
async def capture_console_logs(_page: Page) -> list[str]:
|
|
"""Capture console messages logged during page lifecycle.
|
|
|
|
Note: This captures messages that were emitted during the page's
|
|
lifetime. To get comprehensive logs, attach listeners early in
|
|
the page lifecycle.
|
|
|
|
Args:
|
|
_page: The Playwright page instance
|
|
|
|
Returns:
|
|
List of console message strings (empty if none captured)
|
|
"""
|
|
# Playwright doesn't provide direct access to historical console logs,
|
|
# but we can provide a hook for attaching a console listener at page creation.
|
|
# For now, return empty list (see browser/client.py for listener attachment).
|
|
return []
|
|
|
|
|
|
async def capture_all_diagnostics(page: Page) -> DebugInfo:
|
|
"""Capture all diagnostic information (screenshot, HTML, logs).
|
|
|
|
Attempts to capture screenshot, HTML, and console logs. If any
|
|
capture fails (e.g., page closed), that field is set to None or empty.
|
|
|
|
Args:
|
|
page: The Playwright page instance
|
|
|
|
Returns:
|
|
DebugInfo with all captured diagnostic data
|
|
"""
|
|
screenshot = await capture_screenshot(page)
|
|
html = await capture_html(page)
|
|
logs = await capture_console_logs(page)
|
|
|
|
return DebugInfo(
|
|
screenshot_base64=screenshot,
|
|
html_content=html,
|
|
console_logs=logs,
|
|
error_timestamp=datetime.now(timezone.utc).isoformat(),
|
|
)
|
|
|
|
|
|
__all__ = [
|
|
"capture_screenshot",
|
|
"capture_html",
|
|
"capture_console_logs",
|
|
"capture_all_diagnostics",
|
|
]
|