File size: 10,516 Bytes
6eb6c4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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"