"""The workflow runner: executes WorkflowSpec steps through the tool executor. Every step goes through the SAME deterministic pipeline as a chat tool call (validation -> risk gate -> URL policy -> connectivity -> timeout), because the default executor IS ``tools.executor.execute_tool``. The runner adds the orchestration layer on top: - ``{{var}}`` substitution from CLI ``--var`` flags and earlier ``save`` captures - ``find`` resolution: click/type/select_option steps that target "the textbox called Search" instead of a brittle numeric index, resolved against the latest observe envelope - post-condition assertions (``expect_ok`` / ``expect``) so a workflow fails when the browser did not do what was asked - a JSON run report with per-step envelopes and timings Both drivers speak the same language: the Playwright driver is the ``ChatBrowserSession`` the chat loop already uses; the Selenium driver (``selenium_driver.SeleniumWorkflowDriver``) implements the same envelope shape on top of the real installed Chrome/Firefox via WebDriver. """ from __future__ import annotations import time from collections.abc import Awaitable, Callable from dataclasses import dataclass, field from datetime import UTC, datetime from typing import Any from .models import WorkflowSpec, WorkflowStep, matches, resolve_path, substitute # async (browser, tool, args) -> envelope Executor = Callable[[Any, str, dict[str, Any]], Awaitable[dict[str, Any]]] @dataclass class StepReport: index: int label: str tool: str ok: bool seconds: float envelope: dict[str, Any] = field(default_factory=dict) error: str | None = None def to_dict(self) -> dict[str, Any]: return { "index": self.index, "label": self.label, "tool": self.tool, "ok": self.ok, "seconds": round(self.seconds, 3), "error": self.error, "envelope": self.envelope, } @dataclass class WorkflowReport: workflow: str ok: bool started_at: str finished_at: str variables: dict[str, Any] steps: list[StepReport] def to_dict(self) -> dict[str, Any]: return { "workflow": self.workflow, "ok": self.ok, "started_at": self.started_at, "finished_at": self.finished_at, "variables": self.variables, "steps": [s.to_dict() for s in self.steps], } class WorkflowFailure(RuntimeError): """A workflow could not run (bad spec/variables) or a step failed its gate.""" class WorkflowRunner: """Execute a workflow against a browser session (Playwright or Selenium).""" def __init__(self, executor: Executor | None = None) -> None: if executor is None: from ..tools.executor import execute_tool executor = execute_tool self._execute = executor async def run( self, browser: Any, spec: WorkflowSpec, variables: dict[str, Any] | None = None, ) -> WorkflowReport: vars_all: dict[str, Any] = dict(variables or {}) steps: list[StepReport] = [] # The latest observe envelope for find resolution. A snapshot is only # valid while it is the CURRENT one for the active tab, so it is reset # on every navigation and re-filled by the next observe step. last_observe: dict[str, Any] | None = None workflow_ok = True started_clock = datetime.now(UTC) for i, step in enumerate(spec.steps): started = time.monotonic() try: args, expect = self._prepare_args(step, vars_all, last_observe) envelope = await self._execute(browser, step.tool, args) except WorkflowFailure as exc: # A find that matches nothing (or a missing observe) is a step # failure like any other — it gets a report row, not an abort. envelope = { "ok": False, "tool": step.tool, "error": {"code": "WORKFLOW_STEP_ERROR", "message": str(exc)}, } expect = step.expect except Exception as exc: # noqa: BLE001 — one failing step is one report row envelope = { "ok": False, "tool": step.tool, "error": {"code": "WORKFLOW_STEP_ERROR", "message": str(exc)}, } expect = step.expect seconds = time.monotonic() - started self._capture(step, envelope, vars_all) if str(envelope.get("tool")) == "observe" and envelope.get("ok"): last_observe = envelope if step.tool in {"navigate", "tab_open", "tab_select", "tab_close"}: # Any navigation or tab switch invalidates a snapshot (the # executor returns STALE_ELEMENT for actions on it). last_observe = None label = step.name or step.tool passed = self._passed(step, envelope, expect) report = StepReport( index=i, label=label, tool=step.tool, ok=passed, seconds=seconds, envelope=envelope, error=None if passed else _first_error_text(envelope), ) steps.append(report) if not passed: # expect_ok=False marks the step as allowed to fail: the report # row shows ok=false but the workflow stays green. With # continue_on_error the remaining steps run AND the workflow # reports failure. Otherwise the run stops here. if not step.expect_ok: pass elif step.continue_on_error: workflow_ok = False else: workflow_ok = False break return WorkflowReport( workflow=spec.name, ok=workflow_ok, started_at=started_clock.isoformat(), finished_at=datetime.now(UTC).isoformat(), variables=dict(vars_all), steps=steps, ) # ── step preparation ───────────────────────────────────────────────────── def _prepare_args( self, step: WorkflowStep, variables: dict[str, Any], last_observe: dict[str, Any] | None, ) -> tuple[dict[str, Any], dict[str, Any]]: args = substitute(dict(step.args), variables) # expect values carry variables too (e.g. {"data.url": "{{url1}}"}). expect = substitute(dict(step.expect), variables) if step.find is not None: index, snapshot_id = self._resolve_find(step, last_observe) args.setdefault("index", index) args.setdefault("snapshot_id", snapshot_id) return args, expect def _resolve_find( self, step: WorkflowStep, last_observe: dict[str, Any] | None, ) -> tuple[int, str]: """Match the find spec against the latest observe's element list.""" if last_observe is None: raise WorkflowFailure( f"step '{step.name or step.tool}' uses 'find' but no observe ran " "before it — add an observe step" ) if step.find is None: # defensive: callers gate on step.find before calling raise WorkflowFailure( f"step '{step.name or step.tool}' resolved find without a find spec" ) role_want = str(step.find.get("role", "")).lower() text_want = str(step.find.get("text", "")).lower() elements = last_observe.get("data", {}).get("elements") or [] for element in elements: role = str(element.get("role", "")).lower() name = str(element.get("accessible_name", "")).lower() if role_want and role_want not in role: continue if text_want and text_want not in name: continue snapshot_id = last_observe.get("data", {}).get("snapshot_id", "") return int(element.get("index")), str(snapshot_id) raise WorkflowFailure( f"step '{step.name or step.tool}' found no element matching " f"find={step.find} in the latest observe " f"({len(elements)} elements) — adjust the find spec" ) # ── result handling ────────────────────────────────────────────────────── def _passed( self, step: WorkflowStep, envelope: dict[str, Any], expect: dict[str, Any] | None = None, ) -> bool: """A step passed when its envelope is ok AND every expect path matches.""" if not envelope.get("ok", False): return False for path, expected in (expect if expect is not None else step.expect).items(): try: actual = resolve_path(envelope, path) except KeyError: return False if not matches(actual, expected): return False return True def _capture( self, step: WorkflowStep, envelope: dict[str, Any], variables: dict[str, Any], ) -> None: for var, path in step.save.items(): try: variables[var] = resolve_path(envelope, path) except KeyError: # Leave the variable unset; a later {{var}} raises a clear # undefined-variable error instead of storing a silent None. pass def _first_error_text(envelope: dict[str, Any]) -> str | None: error = envelope.get("error") if isinstance(error, dict): return str(error.get("message") or error.get("code") or "unknown error") # ok=true envelope that failed an expect post-condition (or a bare # ok=false without a structured error). return "step failed its expect post-condition"