"""Driver instrumentation — the one genuinely per-language piece. Every Selenium command (driver- *and* element-level, since element methods delegate to ``self._parent.execute``) funnels through ``WebDriver.execute(driver_command, params)``. Wrapping that single chokepoint captures the whole command stream from one place — cleaner than the JS adapter's prototype patching. The patch target is injected so the module imports and unit-tests without selenium present; ``install`` defaults to the real selenium class. """ from __future__ import annotations import logging import os import sys import threading import weakref from typing import Any, Dict, List, Optional from . import ( assertions, bidi, bidi_preload, capture_timing, element_locators, frames, interceptor_network, page_resources, performance, read_value_locators, secret_redaction, wait_tracking, ) from ._contract import MAPPED_COMMANDS, READ_ONLY_COMMANDS, SCREENCAST_POLL_INTERVAL_MS from .assert_tracer import ScriptAssertionTracer from .capturer import SessionCapturer from .cdp_screencast import start_push_screencast from .collector_source import reset_cache as reset_collector_cache from .device import driver_is_native_app, native_platform, restore_browser_focus from .element_scripts import reset_cache as reset_element_scripts_cache from .page_scripts import reset_cache as reset_page_scripts_cache from .per_test_capture import PerTestCapture from .constants import ( BIDI_CAPABILITY, DEFAULT_TEST_TITLE, ENV_BIDI, EXECUTE_SCRIPT_COMMANDS, LOGGER_NAME, NAVIGATION_COMMANDS, SKIP_COMMANDS, SKIP_STACK_FRAMES, ) from .output_dir import resolve_adapter_output_dir from .screencast import ScreencastRecorder from .snapshot import ( SnapshotCapturer, collector_source_text, start_snapshot_capture, ) from .sources import read_source from .types import ( ActionSnapshot, ElementScriptsResponse, PageScriptsResponse, Viewport, ) from .utils import call_source, now_ms # Operational logging — surfaced in the dashboard Console (the 'runner' stream). _log = logging.getLogger(f"{LOGGER_NAME}.instrumentation") # Marks the adapter's OWN execute_script calls (snapshot inject/readback) so # patched_execute skips capturing them as user commands. _internal = threading.local() # User-file sources already sent (once per file per run), kept so a newly learned password can redact them. _sources_sent: Dict[str, str] = {} _skip_frames_cache: Optional[tuple] = None class _SkipScreencast(Exception): """Control-flow marker: no recorder for this session. Named rather than a branch so the reason lands in one place with the other bring-up failures.""" def _skip_frames() -> tuple: """Call-source skip fragments: the adapter package + the REAL selenium library dir (resolved from selenium.__file__), cached. Resolving the actual package dir avoids skipping a user test file whose path merely contains 'selenium' (e.g. examples/selenium/...).""" global _skip_frames_cache if _skip_frames_cache is None: try: import selenium extra = (os.path.dirname(os.path.abspath(selenium.__file__)) + os.sep,) except Exception: # noqa: BLE001 — narrow fallback if selenium isn't importable extra = (f"{os.sep}selenium{os.sep}webdriver{os.sep}",) _skip_frames_cache = tuple(SKIP_STACK_FRAMES) + extra return _skip_frames_cache def _internal_active() -> bool: return getattr(_internal, "active", False) # When a test framework (the pytest plugin) reports the suite tree, the adapter # must NOT also synthesize a default one. The plugin flips this in its configure. _external_suites = False def set_external_suites(value: bool = True) -> None: """Tell the adapter a test framework owns the suite tree (suppresses the default single-session suite used for plain scripts).""" global _external_suites _external_suites = value if value: # The framework's own assertion hooks are better than line tracing: they # report real operands for every assertion rather than the subset that is # safe to read, and cost nothing per line. stop_assertion_tracing() def _entry_script() -> Optional[str]: """The file whose `assert` statements are the user's own. ``__main__.__file__`` rather than ``sys.argv[0]``: they agree for ``python login.py``, but argv[0] is whatever launched the process — a runner stub, or ``-c`` — while ``__main__`` is always the module actually executing. """ main = sys.modules.get("__main__") return getattr(main, "__file__", None) or (sys.argv[0] if sys.argv else None) def start_assertion_tracing(capturer: SessionCapturer) -> bool: """Watch the entry script's `assert` statements. True when tracing started. Plain scripts only — see `assert_tracer` for why a passing assert is otherwise invisible, and for what this declines to do. """ if _state.get("assert_tracer") is not None: return False def report(*, passed, source, operands, location, error) -> None: # noqa: ANN001 op, left, right = operands if operands else (None, None, None) if error is not None: # The teardown path reports the failure that ends the run; without # this it would report this same assertion a second time. _state["assertion_reported"] = True now = now_ms() try: capturer.capture_command( command=assertions.assert_command(op), args=[source] if source else [], result=assertions.collapsed_result( passed=passed, op=op, left=left, right=right, message=str(error) if error is not None else None, ), error=error, start_time=now, call_source=location, selector=assertions.comparison_target(operands), ) except Exception as exc: # noqa: BLE001 — capture must never break the run _log.debug("could not record an assertion: %s", exc) tracer = ScriptAssertionTracer(report, _entry_script()) if not tracer.install(): return False _state["assert_tracer"] = tracer return True def stop_assertion_tracing() -> None: tracer = _state.pop("assert_tracer", None) if tracer is not None: tracer.uninstall() def _send_default_suite(capturer: SessionCapturer, state: str) -> None: """Report the run as a single suite/test named after the entry script, so a plain-script run (no test framework) still shows in the TESTS tree. No-op if a framework is reporting suites.""" if _external_suites: return entry = os.path.abspath(sys.argv[0]) if sys.argv and sys.argv[0] else "" suite_title = os.path.basename(entry) or "Selenium session" ds = _state.get("default_suite") start = ds["start"] if ds else now_ms() _state["default_suite"] = {"start": start} end = start if state == "running" else now_ms() # Named the way the pytest plugin names a real test: the file is the suite, # the test carries its own name, and fullTitle joins the two. test_uid = f"{entry or suite_title}::{DEFAULT_TEST_TITLE}" # The synthetic test is what a script's commands belong to, so the trace # gets one group rather than none — the same uid the tree reports, or the # exporter would open a group the viewer cannot name. capturer.test_uid = test_uid test = frames.test_stats( uid=test_uid, title=DEFAULT_TEST_TITLE, full_title=f"{suite_title} › {DEFAULT_TEST_TITLE}", parent=suite_title, state=state, file=entry, start_ms=start, end_ms=end, ) suite = frames.suite_stats( uid=entry or suite_title, title=suite_title, file=entry, start_ms=start, tests=[test], state=state, end_ms=(None if state == "running" else end), ) capturer.send_suites([suite]) def _guarded_execute_script(driver: Any) -> Any: """An ``execute_script`` that runs WITHOUT command capture — for the adapter's own snapshot injection/readback, which must never show up in the Actions timeline (the getTraceData/inject scripts are not user commands).""" try: ref: Any = weakref.ref(driver) except TypeError: # not weak-referenceable; the closure holds it directly ref = lambda: driver # noqa: E731 def run(script: str, *args: Any) -> Any: live = ref() if live is None: # driver gone; nothing left to read the page with return None _internal.active = True try: return live.execute_script(script, *args) finally: _internal.active = False return run def _note_typed_input( driver: Any, capturer: SessionCapturer, orig_execute: Any, driver_command: str, params: Any ) -> None: """Before an element's send_keys runs, read its field type, so a password is redacted from its own row on. Through the unpatched ``execute``, so the read records no row. A newly learned password re-sends the sources already sent, which the backend replaces by path, so neither the Source tab nor the archive keeps a literal sent before it. """ if driver_command != "sendKeysToElement" or not isinstance(params, dict) or driver_is_native_app(driver): return def read_type() -> Any: reply = orig_execute(driver, "getElementProperty", {"id": params.get("id"), "name": "type"}) return reply.get("value") if isinstance(reply, dict) else reply learned = secret_redaction.note_typed_input( params.get("text", params.get("value")), read_type, session=getattr(driver, "session_id", None) ) if learned and _sources_sent: capturer.send_sources(dict(_sources_sent)) def _capture_source(capturer: SessionCapturer, call_src: Optional[str]) -> None: """Send the source of the file a command's ``callSource`` points at (once). Keyed by the exact ``callSource`` path so the Source tab always matches — and works for any runner (plain script or pytest), not just the plugin. Guarded: source capture must never break the user's test.""" if not call_src: return path = call_src.rsplit(":", 1)[0] # strip the trailing ":line" if not path: return # Screencast output lands next to the (first) test file, not the cwd. if _state.get("output_dir") is None: _state["output_dir"] = resolve_adapter_output_dir(test_file_path=path) if path in _sources_sent: return try: text = read_source(path) except Exception: # noqa: BLE001 return if text is None: return _sources_sent[path] = text capturer.send_sources({path: text}) # Selenium command names that change the document — after these we drain the # page-side mutation buffer so the snapshot iframe stays current. _state: dict = { "installed": False, "cls": None, "orig": None, # Capture state keyed by the DRIVER that owns it, weakly: # {driver: {"session_id": sid, "screencast": rec, "snapshot": cap}} # The driver is the owner; the session id is a label on that state which can # be stale or absent, so keying on the id forced a guess about which session # a quit belonged to. Weak keys also let an abandoned driver be collected # instead of holding its recorder open for the rest of the run. "sessions": weakref.WeakKeyDictionary(), "output_dir": None, # test-results dir beside the test file (see output_dir.py) "default_suite": None, # synthesized suite for non-framework (script) runs # Set by enable()'s excepthook when an exception reaches top level. The # synthetic suite's final state reads this rather than assuming success. "run_failed": False, # Trace mode. Set by install(). "trace": False, # Capture the page's element tree per action, for the trace's A11y tab. "a11y": False, # The page-side scripts, fetched from the backend once per run. "element_scripts": None, "page_scripts": None, # One per action that returned elements; sent before the export. "action_snapshots": [], # Record a dense filmstrip into the trace. Only meaningful in trace mode; # the recorder runs in live mode regardless, for the dashboard video. "filmstrip": False, # Frames kept from every session's recorder as it finalizes, because that # is the only moment they are reachable. Run-scoped: a run may replace its # driver, and the filmstrip is the whole run. "filmstrip_frames": [], # Re-armed per test by reset_test_capture(). "test": PerTestCapture(), } def _take_screenshot(driver: Any) -> Optional[str]: """One base64 PNG of the current page on the MAIN thread — no background thread, so we never touch the Selenium session concurrently. Reused for both the command entry (per-command snapshot view) and the screencast frame. Best-effort: a transient failure (mid-navigation, dead session) returns None and never breaks the test. ``screenshot`` is in SKIP_COMMANDS, so this doesn't appear in the Actions timeline.""" fn = getattr(driver, "get_screenshot_as_base64", None) if not callable(fn): return None try: shot = fn() except Exception: # noqa: BLE001 — transient; skip this frame return None return shot if isinstance(shot, str) and shot else None def _backend_origin(capturer: SessionCapturer) -> Optional[tuple]: """``(host, port)`` of the connected backend, which serves the collector. None when the transport does not expose one, so injection falls back to the monorepo path rather than failing.""" tx = getattr(capturer, "_tx", None) host = getattr(tx, "host", None) port = getattr(tx, "port", None) return (host, port) if host and port else None def _stop_push_screencast(entry: dict) -> None: """End the browser's frame stream for one driver. Never raises.""" push = entry.pop("screencast_push", None) if push is None: return try: push.stop() _log.info("screencast: %d frame(s) streamed from the browser", push.frame_count) except Exception as exc: # noqa: BLE001 — teardown must not raise _log.debug("stopping the push screencast threw: %s", exc) def _attach_performance( capturer: SessionCapturer, driver: Any, row: dict, params: Any ) -> None: """Ask the page for its navigation timings and replace the row with them. Only the page can answer this, so the row goes out twice: once when the command completes, and again enriched. Read on THIS thread immediately after the command rather than after a settle — selenium's navigation returns after the load event, so the entries are already there, and a sleep here would be a real delay in the user's test rather than the detached await the JS adapters can afford. A read that lands too early anyway carries no `navigation` entry and is discarded. """ scripts = _state.get("page_scripts") if row is None or not scripts or driver_is_native_app(driver): return try: payload = _guarded_execute_script(driver)(scripts["capturePerformance"]) except Exception as exc: # noqa: BLE001 — capture must never break the test _log.debug("performance capture failed: %s", exc) return if not performance.apply_performance_data( row, payload, performance.navigated_url(params) ): return try: capturer.send_replace_command(row["timestamp"], row) except Exception as exc: # noqa: BLE001 _log.debug("could not replace the navigation row: %s", exc) def action_snapshots() -> List[ActionSnapshot]: """Per-action element trees captured this run, oldest first.""" return list(_state["action_snapshots"]) def set_element_scripts(scripts: Optional[ElementScriptsResponse]) -> None: """Hand over the page-side scripts fetched from the backend. Without them `_capture_action_snapshot` is a no-op, which is the state on a backend too old to serve them.""" _state["element_scripts"] = scripts def set_page_scripts(scripts: Optional[PageScriptsResponse]) -> None: """Hand over the collector and performance scripts fetched from the backend. Without them a session gets no snapshot capturer and no navigation timings, which is the state on a backend too old to serve them.""" _state["page_scripts"] = scripts def screencast_frames() -> list: """Every frame this run's recorders buffered, in time order. Two sources, because a frame is only reachable from one of them at a time: * sessions that already quit — kept as they finalized, since `_finalize_screencast` pops the recorder off the entry and `sessions` is keyed weakly by a driver about to be collected; * sessions still live — read straight off their recorder, because an export can run before the last driver quits, and `uninstall` then stops those recorders without keeping anything. Sorted rather than concatenated: sessions are appended in quit order, and a replaced session can finish after a later one started. """ frames: list = list(_state["filmstrip_frames"]) for entry in list(_state.get("sessions", {}).values()): recorder = entry.get("screencast") if recorder is None: continue try: frames.extend(recorder.frames) except Exception as exc: # noqa: BLE001 — a poorer filmstrip, not a failed run _log.debug("could not read a live recorder's frames: %s", exc) frames.sort(key=lambda f: f.get("timestamp", 0)) return frames def resolved_output_dir() -> Optional[str]: """The ``test-results`` dir this run resolved from its first test file, or None if no command carried a user call source. Screencast videos already write here; a trace belongs beside them rather than in the cwd, which for a runner invoked from a repo root is the repo root. Cleared by ``uninstall``, so a caller tearing a run down must read it before that rather than after. """ return _state.get("output_dir") # The atoms Selenium's own WebElement methods run as scripts, tagged with a # leading comment; the command each one stands for. _ATOM_SCRIPT_COMMANDS = { "/* submitForm */": "submit", "/* getAttribute */": "getElementAttribute", "/* isDisplayed */": "isDisplayed", } def _page_trees_enabled(driver: Any) -> bool: if not _state["a11y"] or not _state.get("element_scripts"): return False return not driver_is_native_app(driver) def _capture_due(command: str, awaiting_initial_frame: bool) -> bool: """Mirrors core's `TestCapture.queue` gate: a known read skips unless it is the test's first mapped command.""" if command not in READ_ONLY_COMMANDS: return True return awaiting_initial_frame and command in MAPPED_COMMANDS def _takes_capture(command: str) -> bool: """Whether this command takes the per-action capture, its screenshot included.""" return _state["trace"] and _capture_due(command, _state["test"].awaiting_initial_frame) def _capture_timer( driver: Any, command: str, poll: Any ) -> Optional[capture_timing.CaptureTimer]: """A timer for this command's capture, only in trace mode with timing switched on.""" if not _state["trace"] or not capture_timing.enabled(): return None trigger = "action" if wait_tracking.parent_of(poll) is None else "wait-poll" return capture_timing.CaptureTimer(command, trigger, driver_is_native_app(driver)) def _capture_action_snapshot( driver: Any, command: str, timestamp: int, shot: Optional[str], timer: Optional[capture_timing.CaptureTimer] = None, ) -> Optional[ActionSnapshot]: """Record one trace capture: its screenshot, plus the page's element trees where a page has them.""" if not _state["trace"]: return None snapshot: ActionSnapshot = {"timestamp": timestamp, "command": command} if shot: snapshot["screenshot"] = shot if _page_trees_enabled(driver): _read_page_trees(driver, snapshot, timer) elif _state["a11y"] and driver_is_native_app(driver): _read_native_tree(driver, snapshot, timer) if snapshot.keys() <= {"timestamp", "command"}: return None _state["action_snapshots"].append(snapshot) return snapshot def _read_page_trees( driver: Any, snapshot: ActionSnapshot, timer: Optional[capture_timing.CaptureTimer], ) -> None: scripts = _state["element_scripts"] # Guarded, or each read lands back in the execute hook as an `executeScript` row. run = _guarded_execute_script(driver) # Two reads, two panes: `elements` carries the interactable boxes, the # accessibility tree becomes the A11y tab's text. Capturing only the first # left that tab reporting "no accessibility snapshot for this command" with # 39 element files sitting in the same archive. for key, script in ( ("elements", scripts["elements"]), ("accessibilityTree", scripts["accessibilityTree"]), ): try: value = ( timer.read(key, run, f"return {script}") if timer else run(f"return {script}") ) except Exception as exc: # noqa: BLE001 — a missing pane, not a failed run _log.debug("%s read failed: %s", key, exc) continue if isinstance(value, list) and value: snapshot[key] = value def _read_native_tree( driver: Any, snapshot: ActionSnapshot, timer: Optional[capture_timing.CaptureTimer], ) -> None: """The raw page source, which the backend turns into the element list and A11y text.""" source = timer.read("pageSource", _read_page_source, driver) if timer else _read_page_source(driver) if source is None: return snapshot["pageSource"] = source platform = native_platform(getattr(driver, "capabilities", None)) if platform is not None: snapshot["platform"] = platform def _read_page_source(driver: Any) -> Optional[str]: # Marked internal: `page_source` routes back through `execute` and would render a row. _internal.active = True try: source = driver.page_source except Exception as exc: # noqa: BLE001 — a missing pane, not a failed run _log.debug("page source read failed: %s", exc) return None finally: _internal.active = False return source if isinstance(source, str) and source else None def _maybe_capture_action_snapshot( driver: Any, command: str, timestamp: int, shot: Optional[str], timer: Optional[capture_timing.CaptureTimer] = None, ) -> None: """Capture on every command that is not a known read, and on a test's first mapped command as its initial frame. Reads and waits inherit the capture before them.""" initial = _state["test"].awaiting_initial_frame and command in MAPPED_COMMANDS _note_final_frame_driver(driver) if not _takes_capture(command): return if initial: _state["test"].awaiting_initial_frame = False _state["test"].last_captured_ts = timestamp _state["test"].final_frame_driver = weakref.ref(driver) snapshot = _capture_action_snapshot(driver, command, timestamp, shot, timer) if not initial or _state["test"].initial_frame_retried: return if snapshot is None or "screenshot" not in snapshot: _state["test"].initial_frame_retried = True _state["test"].awaiting_initial_frame = True def _capture_command(driver_command: str, params: Any) -> str: """The command a script-run atom stands for: Selenium's `WebElement` methods reach `execute` as marked scripts, not as the command they perform.""" script = params.get("script") if isinstance(params, dict) else None if isinstance(script, str): for marker, command in _ATOM_SCRIPT_COMMANDS.items(): if script.startswith(marker): return command return driver_command def _final_frame_stamp( rows: List[tuple], test_started_ms: int, last_captured_ts: Optional[int] ) -> Optional[tuple]: """Mirrors core's `finalFrameStamp`: the (command, timestamp) the end-of-test capture replaces, or None when no row follows the last capture.""" in_test = [row for row in rows if row[1] >= test_started_ms] if not in_test: return None if last_captured_ts is None or last_captured_ts < test_started_ms: return in_test[-1] if not any(ts > last_captured_ts for _, ts in in_test): return None at_or_before = [row for row in in_test if row[1] <= last_captured_ts] owner = at_or_before[-1] if at_or_before else in_test[0] return (owner[0], last_captured_ts) def _note_final_frame_driver(driver: Any) -> None: """Until a capture is taken, the test's stamp belongs to the driver that ran its latest row.""" if _state["test"].last_captured_ts is None: _state["test"].final_frame_driver = weakref.ref(driver) def _capture_final_frame(driver: Any) -> bool: if not _state["trace"]: return False stamp = _final_frame_stamp( _state["test"].rows, _state["test"].started_ms, _state["test"].last_captured_ts ) if stamp is None: return False command, timestamp = stamp timer = ( capture_timing.CaptureTimer(command, "final", driver_is_native_app(driver)) if capture_timing.enabled() else None ) try: # Frames are screenshot-backed: panes merged over an earlier image would pair two documents. shot = timer.read("screenshot", _take_screenshot, driver) if timer else _take_screenshot(driver) if not shot: return False snapshot = _capture_action_snapshot(driver, command, timestamp, shot, timer) or { "timestamp": timestamp, "command": command, "screenshot": shot, } superseded: dict = {} for kept in _state["action_snapshots"]: if kept["timestamp"] == timestamp and kept is not snapshot: superseded.update(kept) _state["action_snapshots"][:] = [ kept for kept in _state["action_snapshots"] if kept["timestamp"] != timestamp ] _state["action_snapshots"].append({**superseded, **snapshot}) _state["test"].last_captured_ts = timestamp entry = _session_entry(driver) if entry is not None: _add_screencast_frame(entry, shot) return True finally: if timer: timer.finish() def capture_final_frame(driver: Any = None) -> None: """Replace the test's last capture with the page the test ended on, when reads followed it. The last page-changing command can return before its navigation commits, so its capture shows the page it left; the reads after it saw the new one. Once per test: the call report and the driver's quit both reach here. Only the driver that owns the stamp acts, so another session quitting mid-test neither captures from nor consumes the test's one final frame. """ if _state["test"].final_frame_taken: return owner_ref = _state["test"].final_frame_driver owner = owner_ref() if owner_ref is not None else None if owner is None or (driver is not None and driver is not owner): return try: if _capture_final_frame(owner): _state["test"].final_frame_taken = True except Exception as exc: # noqa: BLE001 — a missing end frame, not a failed run _log.debug("final frame capture failed: %s", exc) def settle_page_resources(capturer: SessionCapturer) -> None: """Finish every live session's stylesheet and font reads before a test's archive is cut.""" for entry in list(_state["sessions"].values()): page_resources.settle(lambda entry=entry: _flush_page_collector(capturer, entry)) def reset_test_capture() -> None: """Re-arm the initial frame and start the row ledger for the test about to start.""" _state["test"].reset(now_ms()) def _begin_screencast_run(entry: Optional[dict], shot: Optional[str] = None) -> None: """Let a pushed stream start keeping frames. Idempotent, never raises. Called once a command has COMPLETED, so the first frame kept is of a page the test actually produced. The per-command recorder needs no equivalent — it only ever buffers a screenshot the hook already took — but a pushed stream sends frames the browser chose to send, starting with the blank page that precedes the first navigation. ``shot`` seeds the stream with that command's own screenshot. Chrome sends frames only when something composites, so a stream opened on a page that has finished painting may send nothing until the test next changes it; the seed is what makes the video start here rather than at that next change. It is one frame at the moment the gate opens, not the per-command interleaving that `_add_screencast_frame` deliberately skips while streaming. """ push = (entry or {}).get("screencast_push") if push is None: return try: push.begin_run(seed=shot) except Exception as exc: # noqa: BLE001 — never break the test _log.debug("screencast begin_run threw: %s", exc) def _add_screencast_frame(entry: dict, shot: Optional[str]) -> None: """Buffer an already-captured screenshot as a frame of ITS OWN session. Skipped while the browser is streaming: the pushed frames already cover the timeline, and interleaving a per-command shot would duplicate it at a slightly different moment. The screenshot is still taken — the command ROW carries it — so this only decides what the video is made of. """ recorder = entry.get("screencast") if recorder is None or not shot or entry.get("screencast_push") is not None: return try: if recorder.add_frame(shot): entry["last_frame_ms"] = now_ms() except Exception as exc: # noqa: BLE001 — never break the test _log.warning("screencast add_frame threw: %s", exc) def _session_entry(driver: Any) -> Optional[dict]: """The capture state of a driver that has started a session, or None.""" try: return _state.get("sessions", {}).get(driver) except TypeError: # unhashable driver: it never had an entry return None def _filmstrip_frame_due(entry: Optional[dict], poll: Any) -> bool: """Without a pushed stream the screenshots are the filmstrip, so a wait poll or a paced read still owes a frame.""" if not _state["trace"] or entry is None: return False if entry.get("screencast") is None or entry.get("screencast_push") is not None: return False if poll is not None: return True return now_ms() - entry.get("last_frame_ms", 0) >= SCREENCAST_POLL_INTERVAL_MS def _refresh_snapshot(capturer: SessionCapturer, entry: dict) -> None: """After a command, keep the snapshot current: re-inject the collector if the page navigated (self-healing — a click can submit a form and wipe it), then drain the mutation buffer. Called after every command, not just explicit navigations, so the initial full-document snapshot is captured even if it wasn't ready the instant the navigation returned.""" snapshot = entry.get("snapshot") if snapshot is None: return try: snapshot.inject() # no-op if already present; re-installs after navigation except Exception as exc: # noqa: BLE001 — never break the test _log.warning("snapshot re-inject threw: %s", exc) _flush_page_collector(capturer, entry) def _flush_page_collector(capturer: SessionCapturer, entry: dict) -> None: """Drain the page-side buffer and forward it; a no-op if the collector was never injected, and never breaks the user's test. The network half goes only while BiDi is not serving the session: BiDi lists every request with its headers, and the page's view of the same requests would list each twice (as the selenium-devtools adapter also withholds it). Serving means delivering, not subscribed: Appium's shim accepts the subscription and sends nothing, and there, as on Safari, the page's view is the only network capture there is.""" snapshot: SnapshotCapturer | None = entry.get("snapshot") if snapshot is None: return try: payload = snapshot.pull_trace() except Exception as exc: # noqa: BLE001 — capture must never break the test _log.warning("mutation flush threw: %s", exc) return if payload.mutations: capturer.send_mutations(payload.mutations) # Debug, not info: this fires after every command. It is the only signal # that DOM replay is actually receiving anything — the panel being empty # otherwise looks the same whether the collector never loaded or the # page simply did not change. _log.debug("captured %d DOM mutation(s)", len(payload.mutations)) if payload.network_requests and not bidi.network_serving(entry.get("network")): capturer.send_network_requests(payload.network_requests) capturer.send_page_resources(payload.page_resources, payload.resource_re_reads) def _enable_bidi_capability(params: Any) -> None: """Request BiDi at session creation by injecting ``webSocketUrl`` into the newSession capabilities — the one point (before the session exists) where we can. This makes console/network capture work out-of-box, matching the JS adapters. Opt out with ``DEVTOOLS_BIDI=0``. Never blocks a session.""" if os.environ.get(ENV_BIDI, "").strip().lower() in ("0", "false", "no", "off"): return try: caps = params.get("capabilities") if isinstance(params, dict) else None if not isinstance(caps, dict): return always = caps.get("alwaysMatch") if not isinstance(always, dict): always = {} caps["alwaysMatch"] = always always.setdefault(BIDI_CAPABILITY, True) except Exception: # noqa: BLE001 — capability injection is best-effort pass def _close_entry(capturer: SessionCapturer, entry: dict, replaced: bool = False) -> None: """Drain and encode one driver's capture, attributed to the session it was recorded under.""" # Before the encode: a frame still arriving would land after the buffer was # read, and the browser keeps sending until it is told to stop. _stop_push_screencast(entry) _flush_page_collector(capturer, entry) page_resources.settle(lambda: _flush_page_collector(capturer, entry)) poller = entry.pop("interceptor", None) # A replaced session's driver now addresses the new one, which knows nothing of the old listener. if not replaced: interceptor_network.forward(capturer, poller) entry["snapshot"] = None _finalize_screencast(capturer, entry["session_id"], entry) summary = bidi.network_summary(entry.get("network")) if summary: _log.info(summary) def _finalize_screencast( capturer: SessionCapturer, session_id: str, entry: dict ) -> None: """Encode and forward one session's recording, attributed to that session rather than to whichever session happens to be current.""" recorder = entry.pop("screencast", None) if recorder is None: return # Take the buffer BEFORE anything else. This is the last moment it exists: # the entry drops its recorder on the line above, and `sessions` is keyed # weakly by a driver that quit and is about to be collected — so reading it # at export time, as this first did, always found nothing. if _state["filmstrip"]: try: _state["filmstrip_frames"].extend(recorder.frames) except Exception as exc: # noqa: BLE001 — a poorer filmstrip, not a failed run _log.debug("could not keep the filmstrip frames: %s", exc) if _state["trace"]: # No video in trace mode: the frames ARE the filmstrip, and a .webm is # a live-dashboard artifact with no dashboard to play it. Stopping # rather than finalizing is what skips the encode. recorder.stop() return try: info = recorder.finalize(session_id, output_dir=_state.get("output_dir")) except Exception as exc: # noqa: BLE001 _log.warning("screencast finalize threw: %s", exc) return if info is not None: capturer.send_screencast(**info, session_id=session_id) _log.info("screencast saved: %s", info.get("video_path")) def _driver_window(driver: Any) -> Optional[Viewport]: """The device window, for a session with no page to measure. Marked internal for the same reason the page read is guarded: selenium implements this as `getWindowRect`, which routes back through `execute` and would open every native run with a command row of our own making. """ _internal.active = True try: size = driver.get_window_size() except Exception as exc: # noqa: BLE001 — a default frame, not a failed run _log.debug("window size read failed: %s", exc) return None finally: _internal.active = False if not isinstance(size, dict): return None width, height = size.get("width"), size.get("height") if not isinstance(width, int) or not isinstance(height, int): return None if width <= 0 or height <= 0: return None # A native app is never scrolled or pinch-zoomed, so these are its true # values, as core's `fromWindow` sends them. return {"width": width, "height": height, "offsetLeft": 0, "offsetTop": 0, "scale": 1} def _viewport(driver: Any) -> Optional[Viewport]: """The page's own viewport, for the player's frame geometry. Without it the reader falls back to a hard-coded 1280x720 and the replay is framed at proportions the run never had. `window.innerWidth/Height` rather than `get_window_size`, which reports the OS window including its chrome — the service reads `window.visualViewport` for the same reason. Guarded, or the read lands back in the command hook as an `executeScript` row at the head of every run. A native app has no window to ask, so the driver's own window size is the only answer there — and without it such a run reached the player framed at 1280x720, which is a desktop browser's shape rather than a phone's. """ if driver_is_native_app(driver): return _driver_window(driver) run = _guarded_execute_script(driver) try: # `visualViewport`, matching the JS adapters: it is the only read that # carries the real scale and offsets, which `innerWidth` cannot express. size = run( "var v = window.visualViewport;" " if (!v) { return null }" " return [v.width, v.height, v.offsetLeft, v.offsetTop, v.scale]" ) except Exception as exc: # noqa: BLE001 — a default frame, not a failed run _log.debug("viewport read failed: %s", exc) return None if not isinstance(size, list) or len(size) != 5: return None width, height, offset_left, offset_top, scale = size if not isinstance(width, (int, float)) or not isinstance(height, (int, float)): return None if width <= 0 or height <= 0: return None return { "width": int(width), "height": int(height), "offsetLeft": offset_left if isinstance(offset_left, (int, float)) else 0, "offsetTop": offset_top if isinstance(offset_top, (int, float)) else 0, "scale": scale if isinstance(scale, (int, float)) and scale > 0 else 1, } def _ensure_session_setup(driver: Any, capturer: SessionCapturer) -> Optional[dict]: """Bring capture up for this driver, once, and return its state. Keyed by the driver, so two live drivers are independent and interleaved commands re-arm nothing: re-attaching BiDi would duplicate console and network events, and restarting the recorder and collector would truncate both. A driver whose session id changes has genuinely started a new session, so its own previous one is closed out first. This CANNOT run in the newSession branch: selenium assigns ``session_id`` / ``caps`` only *after* the newSession execute() returns, so at that point the driver has no session yet (BiDi caps missing, screenshots fail). By the first real command the driver is fully initialized. Each step is independently defensive — a BiDi or screencast failure is a logged no-op. """ session_id = getattr(driver, "session_id", None) if not session_id: return None # driver not ready yet; retry on the next command sessions = _state["sessions"] try: entry = sessions.get(driver) except TypeError: # unhashable driver: capture is skipped, never fatal _log.warning("driver is not hashable; capture disabled for it") return None if entry is not None: if entry["session_id"] == session_id: return entry _close_entry(capturer, entry, replaced=True) # same driver, new session entry = { "session_id": session_id, "screencast": None, "snapshot": None, "preloaded": False, } try: sessions[driver] = entry except TypeError: # not weak-referenceable _log.warning("driver cannot be tracked; capture disabled for it") return None capturer.ensure_metadata( session_id, getattr(driver, "caps", None), None, viewport=_viewport(driver) ) _log.info("session %s started", session_id) if not _state["trace"] and restore_browser_focus( getattr(driver, "caps", None), host=_executor_host(driver) ): _log.info("Safari brought back to the front (it delivers clicks only there)") _send_default_suite(capturer, "running") # tree entry for plain-script runs try: # Filled in as events arrive; reported once by _on_quit, because the # Network tab already lists every request as it happens. entry["network"] = {} if bidi.attach(driver, capturer, entry["network"]): _log.info("BiDi attached — capturing console + network") except Exception as exc: # noqa: BLE001 — capture must never break the test _log.warning("BiDi attach threw: %s", exc) entry["interceptor"] = interceptor_network.start( driver, _guarded_execute_script(driver) ) try: if _state["trace"] and not _state["filmstrip"]: # With no filmstrip the archive's frames are the per-command # screenshots alone, and the video is a live-dashboard artifact — # trace mode opens no dashboard, so a recorder here writes a .webm # nothing reads. raise _SkipScreencast recorder = ScreencastRecorder() recorder.start(driver) entry["screencast"] = recorder # Prefer the browser's own frame stream. It returns None on anything but # a Chromium driver with a reachable CDP endpoint, and then the # per-command screenshots the command hook already buffers are the # recording — so this is an upgrade, never a requirement. # Guarded: resolving the CDP target reads `driver.current_window_handle`, # and in selenium that property issues a real WebDriver command. Left # uncaptured it re-entered this hook as a user command — a # `w3cGetCurrentWindowHandle` row at the head of every run, and, because # session setup happens ON the first command, it BECAME the first # command. Its post-command screenshot is the page before the run: an # unpainted surface, which then led the video for the whole opening # navigation. Measured: a uniform frame (YMIN=YMAX=31) held 3.8s of a # 4.2s video. _internal.active = True try: push = start_push_screencast(driver, recorder.add_frame) finally: _internal.active = False entry["screencast_push"] = push if push is None: _log.info("screencast recording started (one frame per command)") except _SkipScreencast: _log.info("trace mode — skipping the screencast recording") except Exception as exc: # noqa: BLE001 _log.warning("screencast start threw: %s", exc) try: # Register the collector at document-start FIRST, while this runs before # the session's first command executes — a preload registered after a # navigation has already missed the document it needed to instrument. # Falls back to per-document `