e2e-web 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
e2e_web/browser.py ADDED
@@ -0,0 +1,735 @@
1
+ """Web-only engine over a borrowed synchronous Playwright Page."""
2
+
3
+ from contextlib import contextmanager, ExitStack
4
+ from pathlib import Path
5
+ from dataclasses import asdict
6
+ import hashlib
7
+ import json
8
+ import uuid
9
+ import time
10
+ from typing import Any
11
+ from urllib.parse import urljoin, urlsplit
12
+
13
+ from .actions import TAB_OPS, VISUAL_OPS, press_sequence, validate_action, validate_target
14
+ from .config import _ObservationSettings
15
+ from .errors import E2EError, StepTimeout
16
+ from .tabs import Tabs
17
+ from .types import Secret, ObservationConfig
18
+ from . import semantics
19
+ from ._utils import canonical
20
+
21
+
22
+ def navigation_url(value: str, base_url: str | None = None) -> str:
23
+ """Apply the agent navigation policy before handing a URL to Playwright."""
24
+ try:
25
+ if not value or any(ord(c) < 32 or ord(c) == 127 for c in value):
26
+ raise ValueError()
27
+ original = urlsplit(value)
28
+ if original.scheme in {"http", "https"} and not original.hostname:
29
+ raise ValueError()
30
+ url = urljoin(base_url or "", value)
31
+ parts = urlsplit(url)
32
+ if url == "about:blank":
33
+ return url
34
+ if parts.scheme not in {"http", "https"} or not parts.hostname:
35
+ raise ValueError()
36
+ parts.port # Validate malformed ports as well.
37
+ return url
38
+ except ValueError:
39
+ raise E2EError("POLICY_DENIED", "navigation requires a valid http/https URL or exact about:blank") from None
40
+
41
+
42
+ class BrowserEngine:
43
+ """Do not own or change the caller's Page/context default timeout."""
44
+
45
+ name = "playwright-web-v1"
46
+
47
+ def __init__(self, page: Any, *, base_url: str | None = None, upload_roots: tuple[Path, ...] = (),
48
+ observation: ObservationConfig | None = None, own_initial: bool = False):
49
+ self._tabs = Tabs(page, own_initial=own_initial)
50
+ self.base_url = base_url or page.url
51
+ if observation is None:
52
+ observation = ObservationConfig(**_ObservationSettings.resolve().model_dump())
53
+ self.observation = observation
54
+ limits = asdict(self.observation)
55
+ for key, value in limits.items():
56
+ low, high = (4096, 1048576) if key == 'max_bytes' else (1, 100000)
57
+ if type(value) is not int or not low <= value <= high:
58
+ raise E2EError('INVALID_ARGUMENT', f'invalid observation limit {key}')
59
+ if self.observation.max_depth > 8 or self.observation.max_frames > 100:
60
+ raise E2EError('INVALID_ARGUMENT', 'observation depth is at most 8 and frames at most 100')
61
+ self._observation_id = None
62
+ self._nodes = {}
63
+ self._scopes = {}
64
+ self._visual = None
65
+ self.upload_roots = tuple(Path(p).resolve() for p in upload_roots)
66
+
67
+ @property
68
+ def page(self):
69
+ return self._tabs.page
70
+
71
+ @property
72
+ def current_url(self) -> str:
73
+ return self.page.url
74
+
75
+ @property
76
+ def active_tab(self) -> int:
77
+ self._tabs.refresh()
78
+ return self._tabs.active
79
+
80
+ def resolve_navigation(self, value: str) -> str:
81
+ return navigation_url(value, self.base_url)
82
+
83
+ @staticmethod
84
+ def _semantic_matches(nodes, target):
85
+ matches = [node for node in nodes.values() if node['role'] == target['value']
86
+ and node['name'] == target['name']
87
+ and (not target.get('test_id') or node['test_id'] == target['test_id'])]
88
+ within = target.get('within')
89
+ if within is not None:
90
+ parents = [node['id'] for node in nodes.values()
91
+ if all(node[key] == value for key, value in within.items())]
92
+ if len(parents) != 1:
93
+ return []
94
+ matches = [node for node in matches
95
+ if any(parent['id'] == parents[0] for parent in semantics.ancestors(node, nodes))]
96
+ return matches
97
+
98
+ def target(self, descriptor: dict[str, Any], *, timeout: float = 3, within=None):
99
+ """Compile a replayable descriptor into a native Playwright Locator."""
100
+ end = time.monotonic() + timeout
101
+ target = validate_target(descriptor)
102
+ if target['by'] == 'ref':
103
+ if target['observation'] != self._observation_id or target['value'] not in self._nodes:
104
+ raise E2EError('NODE_STALE', 'reference is not in the latest observation')
105
+ node = self._nodes[target['value']]
106
+ scope = self._scopes[tuple(node['frame'])]
107
+ parent = self.page
108
+ for selector in node['frame']:
109
+ if not parent.locator(selector).evaluate(semantics.IN_ACTIVE_MODAL, timeout=self._remaining_ms(end)):
110
+ raise E2EError('NODE_STALE', 'observed iframe is now behind a modal dialog')
111
+ parent = parent.frame_locator(selector)
112
+ element = semantics.resolve(scope, node['id'], timeout=timeout)
113
+ if element is None or not element.evaluate(semantics.VISIBLE):
114
+ raise E2EError('NODE_STALE', 'observed node is detached or hidden')
115
+ current = element.evaluate(semantics.DESCRIBE)
116
+ if any(current[k] != node[k] for k in ('role', 'name', 'test_id', 'input_type')):
117
+ raise E2EError('NODE_STALE', 'observed node identity changed')
118
+ context = next((parent for parent in semantics.ancestors(node, self._nodes)
119
+ if parent['role'] in {'row', 'listitem'}), None)
120
+ if context and not element.evaluate(semantics.MATCHES_CONTEXT,
121
+ {key: context[key] for key in ('id', 'role', 'name', 'test_id')}):
122
+ raise E2EError('NODE_STALE', 'observed row or list item changed')
123
+ return element
124
+ scope = self.page
125
+ frames = target.get("frame", [])
126
+ for index, selector in enumerate([frames] if isinstance(frames, str) else frames):
127
+ if not scope.locator(selector).evaluate(semantics.IN_ACTIVE_MODAL, timeout=self._remaining_ms(end)):
128
+ raise E2EError('NODE_STALE', 'target iframe is behind a modal dialog')
129
+ if 'frame_identity' in target:
130
+ identity = scope.locator(selector).evaluate(semantics.FRAME_IDENTITY, timeout=timeout*1000)
131
+ if identity != target['frame_identity'][index]:
132
+ raise E2EError('NODE_STALE', 'recorded iframe identity changed')
133
+ duplicates = scope.locator('iframe').evaluate_all("(frames, identity) => frames.filter(el => ['id','name','src','title'].every(k => (el.getAttribute(k)||'') === identity[k])).length", identity)
134
+ if duplicates != 1:
135
+ raise E2EError('LOCATOR_AMBIGUOUS', 'recorded iframe identity is not unique')
136
+ scope = scope.frame_locator(selector)
137
+ if target['by'] == 'semantic':
138
+ result = semantics.scan(scope, max_nodes=self.observation.max_nodes,
139
+ max_elements=self.observation.max_elements, timeout=timeout,
140
+ root=within, replace=False)
141
+ matches = [node for node in self._semantic_matches({node['id']: node for node in result['nodes']}, target)
142
+ if node['id'] != result['root_id']]
143
+ if result['truncated']:
144
+ raise E2EError('NODE_STALE', 'relocation scan truncated; cannot prove uniqueness')
145
+ if len(matches) != 1:
146
+ raise E2EError('LOCATOR_AMBIGUOUS' if matches else 'LOCATOR_NOT_FOUND', 'semantic relocation must match one visible node')
147
+ remaining = end - time.monotonic()
148
+ if remaining <= 0:
149
+ raise StepTimeout('STEP_TIMEOUT', 'relocation deadline elapsed')
150
+ element = semantics.resolve(scope, matches[0]['id'], timeout=remaining, searched=True)
151
+ if element is None:
152
+ raise E2EError('NODE_STALE', 'relocated node detached')
153
+ return element
154
+ by, value, exact = target["by"], target["value"], target.get("exact", True)
155
+ if by == "role":
156
+ locator = scope.get_by_role(value, **({"name": target["name"], "exact": exact} if "name" in target else {}))
157
+ elif by == "text":
158
+ locator = scope.get_by_text(value, exact=exact)
159
+ elif by == "label":
160
+ locator = scope.get_by_label(value, exact=exact)
161
+ elif by == "placeholder":
162
+ locator = scope.get_by_placeholder(value, exact=exact)
163
+ elif by == "test_id":
164
+ locator = scope.get_by_test_id(value)
165
+ else:
166
+ locator = scope.locator(value)
167
+ if within is None:
168
+ return locator.nth(target["nth"]) if "nth" in target else locator
169
+ indices = locator.evaluate_all(semantics.DESCENDANTS, within)
170
+ if 'nth' in target:
171
+ indices = indices[target['nth']:target['nth'] + 1]
172
+ if len(indices) != 1:
173
+ raise E2EError('LOCATOR_AMBIGUOUS' if indices else 'LOCATOR_NOT_FOUND',
174
+ 'search target must match one element inside the container')
175
+ return locator.nth(indices[0])
176
+
177
+ def observe(self, *, timeout: float) -> dict[str, Any]:
178
+ """Build a bounded semantic subset across light, open and tracked closed DOM."""
179
+ end = time.monotonic() + timeout
180
+ self._observation_id = uuid.uuid4().hex
181
+ self._nodes = {}
182
+ self._scopes = {}
183
+ page = self.page
184
+ frames, all_nodes, queue = [], [], [(page, [], [])]
185
+ visited, truncated = 0, False
186
+ try:
187
+ while queue:
188
+ scope, path, identities = queue.pop(0)
189
+ remaining = end - time.monotonic()
190
+ if remaining <= 0:
191
+ raise StepTimeout('STEP_TIMEOUT', 'observation deadline elapsed')
192
+ count = self.observation.max_nodes - len(all_nodes)
193
+ elements = self.observation.max_elements - visited
194
+ if count <= 0 or elements <= 0:
195
+ truncated = True
196
+ break
197
+ try:
198
+ result = semantics.scan(scope, max_nodes=count, max_elements=elements, timeout=remaining)
199
+ except Exception:
200
+ if not path:
201
+ raise
202
+ frames.append(dict(selector=' >> '.join(path), frame=path, tree='<frame unavailable>'))
203
+ continue
204
+ visited += result['visited']
205
+ truncated |= result['truncated']
206
+ nodes = result['nodes']
207
+ self._scopes[tuple(path)] = scope
208
+ for node in nodes:
209
+ node['frame'] = path
210
+ node['frame_identity'] = identities
211
+ all_nodes.extend(nodes)
212
+ tree_lines, depths = [], {}
213
+ for node in nodes:
214
+ depth = depths.get(node['parent_id'], -1) + 1
215
+ depths[node['id']] = depth
216
+ if node.pop('native_option', False):
217
+ continue
218
+ indent = ' ' * min(depth, 8)
219
+ line = indent + '- ' + node['role'] + ' ' + json.dumps(node['name'], ensure_ascii=False)
220
+ if 'options' in node:
221
+ tree_lines.append(line + ':')
222
+ for option in node['options']:
223
+ tree_lines.append(indent + ' - option ' + json.dumps(option['name'], ensure_ascii=False)
224
+ + (' [selected]' if option['selected'] else '')
225
+ + (' [disabled]' if option['disabled'] else ''))
226
+ if node['options_truncated']:
227
+ tree_lines.append(indent + ' … (options truncated)')
228
+ else:
229
+ tree_lines.append(line + (': ' + node['value'] if node['value'] else '')
230
+ + (' [checked]' if node['checked'] else '')
231
+ + (' [selected]' if node['selected'] else ''))
232
+ tree = '\n'.join(tree_lines)
233
+ if not path:
234
+ main_tree = tree
235
+ else:
236
+ frames.append(dict(selector=' >> '.join(path), frame=path, tree=tree))
237
+ frame_locators = scope.locator('iframe')
238
+ indices = (frame_locators.evaluate_all(semantics.MODAL_FRAME_INDICES) if result['modal']
239
+ else range(frame_locators.count()))
240
+ children = len(indices)
241
+ if len(path) >= self.observation.max_depth:
242
+ truncated |= children > 0
243
+ continue
244
+ capacity = max(0, self.observation.max_frames - len(frames) - len(queue))
245
+ truncated |= children > capacity
246
+ for index in indices[:capacity]:
247
+ selector = f'iframe >> nth={index}'
248
+ identity = scope.locator(selector).evaluate(semantics.FRAME_IDENTITY, timeout=max(1, (end-time.monotonic())*1000))
249
+ queue.append((scope.frame_locator(selector), [*path, selector], [*identities, identity]))
250
+ title = page.title()
251
+ tabs = self._tabs.summary()
252
+ if page is not self.page:
253
+ raise E2EError('NODE_STALE', 'active tab changed during observation')
254
+ observation = dict(id=self._observation_id, url=page.url[:2048], title=title[:512],
255
+ viewport=page.viewport_size,
256
+ tree=locals().get('main_tree', ''), frames=frames, nodes=all_nodes,
257
+ truncated=truncated, visited=visited, **tabs)
258
+ # Account for the serialized envelope, not just individual text fields.
259
+ while len(canonical(observation).encode()) > self.observation.max_bytes:
260
+ observation['truncated'] = True
261
+ if observation['tree']:
262
+ observation['tree'] = observation['tree'][:len(observation['tree']) // 2]
263
+ elif observation['frames']:
264
+ observation['frames'].pop()
265
+ elif observation['nodes']:
266
+ observation['nodes'].pop()
267
+ elif observation['tabs']:
268
+ observation['tabs'].pop()
269
+ else:
270
+ raise E2EError('OBSERVATION_TOO_LARGE', 'observation metadata exceeds byte budget')
271
+ self._nodes = {n['id']: n for n in observation['nodes']}
272
+ self._observation_truncated = observation['truncated']
273
+ return observation
274
+ except E2EError:
275
+ raise
276
+ except Exception as exc:
277
+ raise self.translate(exc) from None
278
+
279
+ def record_action(self, action: dict) -> dict | None:
280
+ """Persist semantic anchors instead of document-local references."""
281
+ action = dict(action)
282
+ for key in ('target', 'to'):
283
+ target = action.get(key)
284
+ if target and target['by'] == 'ref':
285
+ if self._observation_truncated:
286
+ return None
287
+ node = self._nodes[target['value']]
288
+ descriptor = dict(by='semantic', value=node['role'], name=node['name'], test_id=node['test_id'])
289
+ scope = {n['id']: n for n in self._nodes.values() if n['frame'] == node['frame']}
290
+ if len(self._semantic_matches(scope, descriptor)) != 1:
291
+ for parent in semantics.ancestors(node, scope):
292
+ if not (parent['name'] or parent['test_id']):
293
+ continue
294
+ context_key = 'test_id' if parent['test_id'] else 'name'
295
+ descriptor['within'] = {'role': parent['role'], context_key: parent[context_key]}
296
+ if len(self._semantic_matches(scope, descriptor)) == 1:
297
+ break
298
+ else:
299
+ return None
300
+ if node['frame']:
301
+ descriptor.update(frame=node['frame'], frame_identity=node['frame_identity'])
302
+ action[key] = descriptor
303
+ return action
304
+
305
+ def _scroll_find(self, action, *, end):
306
+ target = action['target']
307
+ container = action.get('container')
308
+ page = self.page
309
+ handle = None
310
+ if container is not None:
311
+ frame = container.get('frame', [])
312
+ if container['by'] == 'ref':
313
+ node = self._nodes.get(container['value'])
314
+ frame = node['frame'] if node else []
315
+ frame = [frame] if isinstance(frame, str) else frame
316
+ requested = target.get('frame', frame)
317
+ if frame and 'frame' not in target:
318
+ target = dict(target, frame=frame)
319
+ element = self.target(container, timeout=max(0.001, end - time.monotonic()))
320
+ handle = (element.handle if isinstance(element, semantics.ElementTarget)
321
+ else element.element_handle(timeout=max(1, (end - time.monotonic()) * 1000)))
322
+
323
+ x, y = {'up': (0, -1), 'down': (0, 1), 'left': (-1, 0), 'right': (1, 0)}[action['direction']]
324
+ scroll_scope = page if handle is None else handle
325
+ stopped = False
326
+ try:
327
+ if handle is not None:
328
+ requested = [requested] if isinstance(requested, str) else requested
329
+ if frame != requested:
330
+ scope = self.page
331
+ for selector in requested:
332
+ scope = scope.frame_locator(selector)
333
+ document = scope.locator('html').element_handle(timeout=max(1, (end - time.monotonic()) * 1000))
334
+ try:
335
+ if document.owner_frame() != handle.owner_frame():
336
+ raise E2EError('INVALID_ARGUMENT', 'search target and container must be in the same frame')
337
+ finally:
338
+ document.dispose()
339
+ for attempt in range(action['steps'] + 1):
340
+ if page.is_closed():
341
+ raise E2EError('NODE_STALE', 'tab closed during scroll search')
342
+ remaining = end - time.monotonic()
343
+ if remaining <= 0:
344
+ raise StepTimeout('STEP_TIMEOUT', 'scroll search deadline elapsed')
345
+ try:
346
+ match = self.target(target, timeout=remaining, within=handle)
347
+ if match.is_visible() and (handle is None or match.evaluate(
348
+ semantics.CONTAINS, handle, timeout=max(1, (end - time.monotonic()) * 1000)
349
+ )):
350
+ match.scroll_into_view_if_needed(timeout=max(1, (end - time.monotonic()) * 1000))
351
+ return None
352
+ except E2EError as exc:
353
+ if attempt and exc.code == 'NODE_STALE':
354
+ raise E2EError('ACTION_FAILED', 'target became stale after scrolling') from None
355
+ if exc.code != 'LOCATOR_NOT_FOUND':
356
+ raise
357
+ if stopped or attempt == action['steps']:
358
+ break
359
+ position = scroll_scope.evaluate(semantics.SCROLL_STATE)
360
+ if handle is None:
361
+ size = page.viewport_size or page.evaluate('() => ({width: innerWidth, height: innerHeight})')
362
+ page.mouse.wheel(x * size['width'] * 0.8, y * size['height'] * 0.8)
363
+ else:
364
+ if not handle.evaluate('el => el.isConnected'):
365
+ raise E2EError('ACTION_FAILED', 'scroll container was detached during search')
366
+ handle.evaluate(semantics.SCROLL, dict(x=x, y=y, page=True))
367
+ # A virtual list can extend its scroll range after reaching its old end.
368
+ settle_end = min(end, time.monotonic() + 1)
369
+ while scroll_scope.evaluate(semantics.SCROLL_STATE) == position:
370
+ remaining = settle_end - time.monotonic()
371
+ if remaining <= 0:
372
+ stopped = True
373
+ break
374
+ time.sleep(min(0.05, remaining))
375
+ raise E2EError('LOCATOR_NOT_FOUND', 'bounded scroll search did not find target')
376
+ finally:
377
+ if handle is not None:
378
+ handle.dispose()
379
+
380
+ @staticmethod
381
+ def _remaining_ms(end):
382
+ remaining = end - time.monotonic()
383
+ if remaining <= 0:
384
+ raise StepTimeout('STEP_TIMEOUT', 'action deadline elapsed')
385
+ return max(1, remaining * 1000)
386
+
387
+ @contextmanager
388
+ def _element(self, target, *, end):
389
+ handle = (target.handle if isinstance(target, semantics.ElementTarget)
390
+ else target.element_handle(timeout=self._remaining_ms(end)))
391
+ try:
392
+ yield handle
393
+ finally:
394
+ handle.dispose()
395
+
396
+ def _select(self, target, value, *, end):
397
+ if isinstance(value, str):
398
+ return target.select_option(label=value, timeout=self._remaining_ms(end))
399
+ batch = isinstance(value, list)
400
+ choices = [{'label': option} if isinstance(option, str) else option
401
+ for option in (value if batch else [value])]
402
+ with self._element(target, end=end) as element, ExitStack() as handles:
403
+ result = element.evaluate_handle(semantics.SELECT_OPTIONS, dict(choices=choices, batch=batch))
404
+ handles.callback(result.dispose)
405
+ problem = result.evaluate('result => result.problem || null')
406
+ if problem:
407
+ code, message = {
408
+ 'not-select': ('ACTION_FAILED', 'select requires a native select element'),
409
+ 'not-multiple': ('ACTION_FAILED', 'a list of options requires a native multiple select'),
410
+ 'missing': ('LOCATOR_NOT_FOUND', 'a requested select option was not found'),
411
+ 'ambiguous': ('LOCATOR_AMBIGUOUS', 'a select option is ambiguous; use its value or index'),
412
+ 'disabled': ('ACTION_FAILED', 'a requested select option is disabled'),
413
+ }[problem]
414
+ raise E2EError(code, message)
415
+ select = result.get_property('select').as_element()
416
+ handles.callback(select.dispose)
417
+ if not choices:
418
+ return select.select_option(label=[], timeout=self._remaining_ms(end))
419
+ options = result.get_property('options')
420
+ handles.callback(options.dispose)
421
+ selected = list(options.get_properties().values())
422
+ for option in selected:
423
+ handles.callback(option.dispose)
424
+ return select.select_option(element=[option.as_element() for option in selected],
425
+ timeout=self._remaining_ms(end))
426
+
427
+ def _type_focused(self, value, *, replace, end):
428
+ frame = self.page.main_frame
429
+ while frame is not None:
430
+ self._remaining_ms(end)
431
+ handle = frame.evaluate_handle(semantics.FOCUSED_ELEMENT)
432
+ try:
433
+ element = handle.as_element()
434
+ if element is None:
435
+ break
436
+ frame = element.content_frame()
437
+ if frame is not None:
438
+ continue
439
+ kind = element.evaluate(semantics.FOCUSED_INPUT)
440
+ if kind is None:
441
+ break
442
+ if replace:
443
+ if kind != 'editable':
444
+ raise E2EError('ACTION_FAILED', 'replace requires a focused editable field')
445
+ return element.fill(value, timeout=self._remaining_ms(end))
446
+ return element.type(value, timeout=self._remaining_ms(end))
447
+ finally:
448
+ handle.dispose()
449
+ raise E2EError('ACTION_FAILED', 'no writable field or keyboard control has focus')
450
+
451
+ def _set_checked(self, target, checked, *, end):
452
+ with self._element(target, end=end) as element:
453
+ state = element.evaluate(semantics.CHECK_STATE)
454
+ current = element.is_checked()
455
+ if current == checked and not state['mixed']:
456
+ return None
457
+ if not checked and state['type'] == 'radio':
458
+ raise E2EError('ACTION_FAILED', 'choose another radio button to change a radio selection')
459
+ if current == checked and state['type'] == 'checkbox':
460
+ raise E2EError('ACTION_FAILED', 'clicking this mixed checkbox would reverse the requested state')
461
+ element.click(timeout=self._remaining_ms(end))
462
+ first = True
463
+ while True:
464
+ self._remaining_ms(end)
465
+ try:
466
+ state = element.evaluate(semantics.CHECK_STATE)
467
+ if not state['connected']:
468
+ if first:
469
+ return None
470
+ raise E2EError('ACTION_FAILED', 'checkable element was replaced before reaching the requested state')
471
+ if not state['mixed'] and element.is_checked() == checked:
472
+ return None
473
+ except Exception as exc:
474
+ detail = str(exc).lower()
475
+ if first and ('not attached to the dom' in detail or 'execution context was destroyed' in detail):
476
+ return None
477
+ raise
478
+ first = False
479
+ time.sleep(min(0.05, self._remaining_ms(end) / 1000))
480
+
481
+ def perform(self, action: dict[str, Any], *, timeout: float) -> Any:
482
+ """Dispatch only the validated portable action grammar."""
483
+ if not isinstance(action, dict) or action.get('op') != 'press' or 'times' not in action:
484
+ return self._perform(action, timeout=timeout)
485
+ end = time.monotonic() + timeout
486
+ for press in press_sequence(validate_action(action)):
487
+ self._perform(press, timeout=self._remaining_ms(end) / 1000)
488
+
489
+ @contextmanager
490
+ def _input_target(self, descriptor, *, timeout):
491
+ """Inspect and pin the same element that will receive the input."""
492
+ end = time.monotonic() + timeout
493
+ with ExitStack() as stack:
494
+ try:
495
+ target = self.target(descriptor, timeout=timeout)
496
+ element = stack.enter_context(self._element(target, end=end))
497
+ if not element.evaluate(semantics.IN_ACTIVE_MODAL):
498
+ raise E2EError('NODE_STALE', 'input target is behind a modal dialog')
499
+ one_time_code = element.evaluate('el => el.matches(\'[autocomplete~="one-time-code" i]\')')
500
+ except E2EError:
501
+ raise
502
+ except Exception as exc:
503
+ raise self.translate(exc) from None
504
+ yield semantics.ElementTarget(element), one_time_code
505
+
506
+ def _perform(self, action: dict[str, Any], *, timeout: float, input_target=None) -> Any:
507
+ action = validate_action(action)
508
+ end = time.monotonic() + timeout
509
+ op, ms = action["op"], max(1, timeout * 1000)
510
+ try:
511
+ if op in VISUAL_OPS:
512
+ return self._perform_visual(action, timeout=timeout)
513
+ if op == 'scroll_find':
514
+ return self._scroll_find(action, end=end)
515
+ if op == "navigate":
516
+ url = self.resolve_navigation(action["url"])
517
+ response = self.page.goto(url, wait_until="domcontentloaded", timeout=ms)
518
+ return {"url": self.page.url, "status": response.status if response else None}
519
+ if op in {"back", "forward", "reload"}:
520
+ method = {"back": "go_back", "forward": "go_forward", "reload": "reload"}[op]
521
+ response = getattr(self.page, method)(wait_until="domcontentloaded", timeout=ms)
522
+ return {"url": self.page.url, "status": response.status if response else None}
523
+ if op == 'resize_viewport':
524
+ self._visual = self._observation_id = None
525
+ self._remaining_ms(end)
526
+ size = dict(width=action['width'], height=action['height'])
527
+ self.page.set_viewport_size(size)
528
+ return size
529
+ if op in TAB_OPS:
530
+ self._remaining_ms(end)
531
+ if op == 'switch_tab':
532
+ self._tabs.switch(action['tab'])
533
+ else:
534
+ self._tabs.close(action['tab'])
535
+ self._visual = self._observation_id = None
536
+ return self._tabs.summary()
537
+ if op == "scroll" and "target" not in action:
538
+ return self.page.mouse.wheel(action["x"], action["y"])
539
+ if op == "wait":
540
+ if action["seconds"] >= timeout:
541
+ raise StepTimeout("STEP_TIMEOUT", "requested wait exceeds remaining timeout")
542
+ self.page.wait_for_timeout(action["seconds"] * 1000)
543
+ return None
544
+ if op in {"tool", "fill_secret"}:
545
+ raise E2EError("POLICY_DENIED", "harness must resolve tools and secrets")
546
+ if op == 'type' and 'target' not in action:
547
+ return self._type_focused(action['value'], replace=action.get('replace', False), end=end)
548
+ if op == 'press' and 'target' not in action:
549
+ self._remaining_ms(end)
550
+ return self.page.keyboard.press(action['value'])
551
+ target = self.target(action["target"], timeout=timeout) if input_target is None else input_target
552
+ remaining = end - time.monotonic()
553
+ if remaining <= 0:
554
+ raise StepTimeout('STEP_TIMEOUT', 'action deadline elapsed')
555
+ ms = remaining * 1000
556
+ if op == 'scroll':
557
+ return target.evaluate(semantics.SCROLL, dict(x=action['x'], y=action['y'], page=False), timeout=ms)
558
+ if op == 'scroll_to':
559
+ return target.scroll_into_view_if_needed(timeout=ms)
560
+ if op == "upload":
561
+ paths = [Path(p).expanduser().resolve() for p in action["value"]]
562
+ if any(not p.is_file() or not any(p.is_relative_to(root) for root in self.upload_roots) for p in paths):
563
+ raise E2EError("POLICY_DENIED", "upload path is not a file under an explicit upload root")
564
+ files = [str(p) for p in paths]
565
+ if target.evaluate("""el => {
566
+ const input = el.closest('label')?.control || el;
567
+ return input.matches('input[type=file]');
568
+ }""", timeout=ms):
569
+ return target.set_input_files(files, timeout=max(1, (end - time.monotonic()) * 1000))
570
+ with self.page.expect_file_chooser(timeout=max(1, (end - time.monotonic()) * 1000)) as chooser:
571
+ target.click(timeout=max(1, (end - time.monotonic()) * 1000))
572
+ return chooser.value.set_files(files, timeout=max(1, (end - time.monotonic()) * 1000))
573
+ if op == "drag":
574
+ destination = self.target(action['to'], timeout=remaining)
575
+ if hasattr(target, 'drag_to') and action['to']['by'] not in {'ref', 'semantic'}:
576
+ return target.drag_to(destination, timeout=ms)
577
+ target.scroll_into_view_if_needed(timeout=ms)
578
+ destination.scroll_into_view_if_needed(timeout=ms)
579
+ start, finish = target.bounding_box(), destination.bounding_box()
580
+ if not start or not finish:
581
+ raise E2EError('NODE_STALE', 'drag target is no longer visible')
582
+ self.page.mouse.move(start['x']+start['width']/2, start['y']+start['height']/2)
583
+ self.page.mouse.down()
584
+ try:
585
+ self.page.mouse.move(finish['x']+finish['width']/2, finish['y']+finish['height']/2, steps=10)
586
+ finally:
587
+ self.page.mouse.up()
588
+ return None
589
+ if op == "select":
590
+ return self._select(target, action['value'], end=end)
591
+ if op in {'check', 'uncheck'}:
592
+ return self._set_checked(target, op == 'check', end=end)
593
+ if op in {"fill", "type", "press"}:
594
+ method = {"fill": "fill", "type": "press_sequentially", "press": "press"}[op]
595
+ return getattr(target, method)(action["value"], timeout=ms)
596
+ if op in {'click', 'double_click', 'right_click', 'long_press'}:
597
+ method = target.dblclick if op == 'double_click' else target.click
598
+ options = {}
599
+ if 'modifiers' in action:
600
+ options['modifiers'] = action['modifiers']
601
+ if op == 'right_click':
602
+ options['button'] = 'right'
603
+ if op == 'long_press':
604
+ if ms <= 500:
605
+ raise StepTimeout('STEP_TIMEOUT', 'remaining timeout is too short for a long press')
606
+ options['delay'] = 500
607
+ return method(timeout=ms, **options)
608
+ return getattr(target, op)(timeout=ms)
609
+ except E2EError:
610
+ raise
611
+ except Exception as exc:
612
+ raise self.translate(exc) from None
613
+
614
+ def screenshot(self, *, timeout: float) -> bytes:
615
+ """Capture pixels only when the harness has allowed secret-safe vision."""
616
+ return self.page.screenshot(timeout=max(1, timeout * 1000), scale='css')
617
+
618
+ def capture_vision(self, *, timeout: float):
619
+ """Issue a one-use screenshot token with CSS-pixel coordinates."""
620
+ end = time.monotonic() + timeout
621
+ data = self.screenshot(timeout=timeout)
622
+ # Initial canvas compositing can settle after the first capture.
623
+ for _ in range(2):
624
+ remaining = end - time.monotonic()
625
+ if remaining <= 0:
626
+ raise StepTimeout('STEP_TIMEOUT', 'screenshot deadline elapsed')
627
+ next_image = self.screenshot(timeout=remaining)
628
+ same = next_image == data
629
+ data = next_image
630
+ if same:
631
+ break
632
+ size = self.page.evaluate('({width:innerWidth,height:innerHeight})')
633
+ self._visual = dict(id=uuid.uuid4().hex, digest=hashlib.sha256(data).hexdigest(),
634
+ url=self.page.url, **size)
635
+ return data, {k: self._visual[k] for k in ('id', 'width', 'height')}
636
+
637
+ @contextmanager
638
+ def _at_point(self, x, y, *, end):
639
+ page = self.page
640
+ frame, point = page.main_frame, dict(x=x, y=y)
641
+ with ExitStack() as stack:
642
+ for _ in range(self.observation.max_depth + 1):
643
+ semantics.install(frame, timeout=self._remaining_ms(end) / 1000)
644
+ handle = frame.evaluate_handle(semantics.ELEMENT_AT, point)
645
+ stack.callback(handle.dispose)
646
+ element = handle.as_element()
647
+ child = element.content_frame() if element is not None else None
648
+ if child is None:
649
+ yield element
650
+ return
651
+ point = element.evaluate(semantics.FRAME_POINT, point)
652
+ if point is None:
653
+ break
654
+ frame = child
655
+ yield None
656
+
657
+ def _perform_visual(self, action, *, timeout):
658
+ end = time.monotonic() + timeout
659
+ visual = self._visual
660
+ self._visual = None
661
+ if not visual or action['screenshot'] != visual['id'] or self.page.url != visual['url']:
662
+ raise E2EError('NODE_STALE', 'coordinate action requires the latest screenshot')
663
+ for x, y in [(action['x'], action['y'])] + ([(action['to_x'], action['to_y'])] if action['op'] == 'drag_at' else []):
664
+ if x >= visual['width'] or y >= visual['height']:
665
+ raise E2EError('POLICY_DENIED', 'coordinate is outside the captured viewport')
666
+ current = self.screenshot(timeout=timeout)
667
+ if hashlib.sha256(current).hexdigest() != visual['digest']:
668
+ raise E2EError('NODE_STALE', 'screen changed since screenshot; observe again')
669
+ self._remaining_ms(end)
670
+ op = action['op']
671
+ if op in {'select_at', 'press_at'} or (op == 'type_at' and action.get('replace')):
672
+ with self._at_point(action['x'], action['y'], end=end) as element:
673
+ if op == 'select_at':
674
+ if element is None or not element.evaluate("el => el.matches('select')"):
675
+ raise E2EError('LOCATOR_NOT_FOUND', 'no native select at screenshot point')
676
+ return self._select(semantics.ElementTarget(element), action['value'], end=end)
677
+ if op == 'type_at':
678
+ if element is None or element.evaluate(semantics.FOCUSED_INPUT) != 'editable':
679
+ raise E2EError('LOCATOR_NOT_FOUND', 'no editable input at screenshot point')
680
+ return element.fill(action['value'], timeout=self._remaining_ms(end))
681
+ if element is None:
682
+ raise E2EError('LOCATOR_NOT_FOUND', 'no interactive area at screenshot point')
683
+ if element.evaluate('el => el.tabIndex >= 0 || el.isContentEditable'):
684
+ return element.press(action['value'], timeout=self._remaining_ms(end))
685
+ self._remaining_ms(end)
686
+ self.page.mouse.click(action['x'], action['y'])
687
+ self._remaining_ms(end)
688
+ return self.page.keyboard.press(action['value'])
689
+ if op == 'hover_at':
690
+ self.page.mouse.move(action['x'], action['y'])
691
+ elif op == 'drag_at':
692
+ self.page.mouse.move(action['x'], action['y'])
693
+ self.page.mouse.down()
694
+ try:
695
+ self.page.mouse.move(action['to_x'], action['to_y'], steps=10)
696
+ finally:
697
+ self.page.mouse.up()
698
+ else:
699
+ self.page.mouse.click(action['x'], action['y'])
700
+ if op == 'type_at':
701
+ self.page.keyboard.insert_text(action['value'])
702
+
703
+ def fill_secret(self, descriptor: dict[str, Any], secret: Secret, *, timeout: float) -> None:
704
+ """Authorize the current sink before resolving a secret into a field."""
705
+ end = time.monotonic() + timeout
706
+
707
+ def remaining():
708
+ seconds = end - time.monotonic()
709
+ if seconds <= 0:
710
+ raise StepTimeout("STEP_TIMEOUT", "secret fill deadline elapsed")
711
+ return seconds * 1000
712
+
713
+ try:
714
+ target = self.target(descriptor, timeout=timeout)
715
+ editable_kind = target.evaluate("""el => el.isContentEditable || el.tagName === 'TEXTAREA' ||
716
+ (el.tagName === 'INPUT' && !['button','submit','reset','checkbox','radio','file',
717
+ 'image','range','color','hidden'].includes(el.type))""", timeout=remaining())
718
+ if not editable_kind or not target.is_enabled(timeout=remaining()) or not target.is_editable(timeout=remaining()):
719
+ raise E2EError("POLICY_DENIED", "secret target must be enabled and editable")
720
+ if secret.purpose == "password" and target.get_attribute("type", timeout=remaining()) != "password":
721
+ raise E2EError("POLICY_DENIED", "password secrets require a password field")
722
+ target.fill(secret.value, timeout=remaining())
723
+ except E2EError:
724
+ raise
725
+ except Exception as exc:
726
+ raise self.translate(exc) from None
727
+
728
+ @staticmethod
729
+ def translate(exc: Exception) -> E2EError:
730
+ """Classify browser failures without persisting potentially sensitive messages."""
731
+ if "strict mode violation" in str(exc):
732
+ return E2EError("LOCATOR_AMBIGUOUS", "locator matched multiple elements")
733
+ if "Timeout" in type(exc).__name__:
734
+ return StepTimeout("STEP_TIMEOUT", "browser operation timed out")
735
+ return E2EError("ACTION_FAILED", "browser operation failed")