@capagents/forgeqe 2.10.0 → 2.10.1

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.
Files changed (55) hide show
  1. package/dist/docs-site/docs/search.js +1 -1
  2. package/dist/docs-site/docs/web-app/index.html +6 -2
  3. package/dist/forgeqe.js +1749 -1693
  4. package/dist/web/assets/{Agent-B_mG1pww.js → Agent-DQeWzsWG.js} +1 -1
  5. package/dist/web/assets/{ApiTests-C2QIp_tG.js → ApiTests-DrQBxtra.js} +1 -1
  6. package/dist/web/assets/{Browse-zQoOQXpA.js → Browse-CXqsKgMN.js} +2 -2
  7. package/dist/web/assets/{Chat-BtLEKYY8.js → Chat-rChaK9vu.js} +1 -1
  8. package/dist/web/assets/{CommandPalette-BgQORiKD.js → CommandPalette-LNTJ2Pie.js} +1 -1
  9. package/dist/web/assets/{Compare-DQNg3ldO.js → Compare-CP24uSyS.js} +1 -1
  10. package/dist/web/assets/{Cost-T0NH8ymc.js → Cost-Cz6F4MAu.js} +1 -1
  11. package/dist/web/assets/{Data-CqKsrslC.js → Data-RSpfLC9W.js} +1 -1
  12. package/dist/web/assets/{Desktop-CgDXi3lX.js → Desktop-C0VftUUl.js} +1 -1
  13. package/dist/web/assets/{DesktopReview-C-gW_gli.js → DesktopReview-BTYnwZKB.js} +1 -1
  14. package/dist/web/assets/{Evidence-1pipN6K6.js → Evidence-DxfTgGLn.js} +1 -1
  15. package/dist/web/assets/{Explore-lG_kobPj.js → Explore-BKAnJ0AP.js} +1 -1
  16. package/dist/web/assets/{Features-BIrW3AiQ.js → Features-YYcKT5mB.js} +1 -1
  17. package/dist/web/assets/{Flags-sG1vr7NU.js → Flags-B23vWmDR.js} +1 -1
  18. package/dist/web/assets/{Flaky-ChKBXlcW.js → Flaky-kuhde8PW.js} +1 -1
  19. package/dist/web/assets/{Impact-D5a5fyc2.js → Impact-DetuURYY.js} +1 -1
  20. package/dist/web/assets/{Jobs-B52pIZUx.js → Jobs-BTiCqtr9.js} +1 -1
  21. package/dist/web/assets/{KindPage-BFoKPj7l.js → KindPage-BbL7COME.js} +1 -1
  22. package/dist/web/assets/{Migration-DbuzD_s4.js → Migration-CPv7gDC-.js} +1 -1
  23. package/dist/web/assets/{Product-DiH61j0X.js → Product-DcrBguCI.js} +1 -1
  24. package/dist/web/assets/{Production-8h5LixDt.js → Production-N11W9Ckr.js} +1 -1
  25. package/dist/web/assets/{Quality-CI5n8b_k.js → Quality-DzXW1cvp.js} +1 -1
  26. package/dist/web/assets/{Readiness-D4n4HSlW.js → Readiness-BbHO8wa2.js} +1 -1
  27. package/dist/web/assets/Record-P7TKcE5d.js +2 -0
  28. package/dist/web/assets/{Regression-DbShD6ji.js → Regression-BOSQ2Pxp.js} +1 -1
  29. package/dist/web/assets/{Reports-IdoUvtaW.js → Reports-BA1VdwoC.js} +1 -1
  30. package/dist/web/assets/{Response-BRVM9mW_.js → Response-0i0ww7OC.js} +1 -1
  31. package/dist/web/assets/{RunDiff-uQoK3Q6q.js → RunDiff-D-4tB7Is.js} +1 -1
  32. package/dist/web/assets/{Runs-BhDgzDo4.js → Runs-DW7dZh2j.js} +1 -1
  33. package/dist/web/assets/{TestCases-DQ2oWXt2.js → TestCases-BfPkdwR6.js} +1 -1
  34. package/dist/web/assets/{TestData-D-ZdmHVa.js → TestData-DRoJc7Me.js} +1 -1
  35. package/dist/web/assets/{TestDebt-_jer4Dmy.js → TestDebt-ly8BsLSJ.js} +1 -1
  36. package/dist/web/assets/{Tosca-DOT6-53c.js → Tosca-CzrCAhEs.js} +1 -1
  37. package/dist/web/assets/{WhatsNew-DU5k6dz6.js → WhatsNew-Cd8D1O1X.js} +1 -1
  38. package/dist/web/assets/{dataParts-BzuL6pAo.js → dataParts-DzHf4K4-.js} +1 -1
  39. package/dist/web/assets/{fold-DZYvcIP0.js → fold-CyU-Mjqe.js} +1 -1
  40. package/dist/web/assets/{frame-Bjxy1jvq.js → frame-DUo0M0VF.js} +2 -2
  41. package/dist/web/assets/index-Bv3atkwB.js +67 -0
  42. package/dist/web/assets/{logos-Co26FM0G.js → logos-cftOc5MX.js} +1 -1
  43. package/dist/web/assets/{palette-CitkMCod.js → palette-D_SCreF2.js} +1 -1
  44. package/dist/web/assets/{qualityParts-DADI5Fqn.js → qualityParts-50E_QRTX.js} +1 -1
  45. package/dist/web/assets/{rows-BqT7fknl.js → rows-JZ5MvdCQ.js} +1 -1
  46. package/dist/web/assets/{thread-iRsceqhM.js → thread-CrExMoMY.js} +1 -1
  47. package/dist/web/assets/{usePageChat-BCrPoTyS.js → usePageChat-DpnA7edC.js} +1 -1
  48. package/dist/web/index.html +2 -2
  49. package/docs/WEB_APP.md +6 -2
  50. package/package.json +1 -1
  51. package/py/forgeqe_engine/recordsession.py +107 -4
  52. package/py/forgeqe_engine/webrecord.py +85 -2
  53. package/py/forgeqe_engine/webrecord_page.py +81 -5
  54. package/dist/web/assets/Record-O8LOzHLo.js +0 -2
  55. package/dist/web/assets/index-DH21lIE7.js +0 -66
@@ -33,7 +33,7 @@ from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
33
33
  from .capture import capture_element, locate_check
34
34
  from .memory import BASE, KEPT_ATTRS, candidate_locators, confidence, looks_generated, state_class, within_locator
35
35
  from . import dynamic
36
- from .webrecord import CAPTCHA_FRAMES, MAX_UPLOAD_FILES, Target, WebRecorder, auto_name, captcha_of, describe, keep_upload, upload_path
36
+ from .webrecord import CAPTCHA_FRAMES, MAX_UPLOAD_FILES, Target, WebRecorder, auto_name, captcha_of, describe, download_name, keep_upload, upload_path
37
37
  from .webrecord_page import recorder_js
38
38
 
39
39
 
@@ -127,6 +127,9 @@ class RecordSession:
127
127
  self.emit = emit
128
128
  self.start_url = str(payload.get("start_url") or "").strip()
129
129
  self.out_dir = Path(str(payload.get("out_dir") or "."))
130
+ self.downloads = self.out_dir / "downloads"
131
+ # Downloads begun and not yet finished, by Chrome's id: what the page called the file.
132
+ self._downloading: Dict[str, str] = {}
130
133
  self.name = " ".join(str(payload.get("name") or "").split())[:200]
131
134
  self.leader = {**DEFAULT_LEADER, **(payload.get("leader") or {})}
132
135
  self.queue: asyncio.Queue = asyncio.Queue()
@@ -174,6 +177,9 @@ class RecordSession:
174
177
  # The page's own API calls after each step (method, path, status), for checks of them in the review.
175
178
  self.calls: Dict[int, List[Dict[str, Any]]] = {}
176
179
  self._requests: Dict[str, str] = {}
180
+ # Sites that asked for the browser's own sign-in (basic auth), by origin: the saved login that signs in there.
181
+ self.logins: List[Any] = []
182
+ self.http_auth: Dict[str, Dict[str, str]] = {}
177
183
  # The browser was closed once the recording stopped (release_browser), and its facts read just before.
178
184
  self.released = False
179
185
  self.profile: Optional[Dict[str, Any]] = None
@@ -238,6 +244,7 @@ class RecordSession:
238
244
 
239
245
  logins = parse_logins(self.payload.get("logins"))
240
246
  use_logins(logins)
247
+ self.logins = logins
241
248
  login_values = {env: os.environ.get(env, "") for env in text_envs() if os.environ.get(env)}
242
249
  login_passwords = {",".join(l.hosts()): l.password_env for l in logins if l.password_env}
243
250
  self.rec = WebRecorder(self.start_url, self.name, login_values=login_values, login_passwords=login_passwords, clock=time.monotonic, case_steps=self.case_steps)
@@ -247,7 +254,8 @@ class RecordSession:
247
254
  candidates = [{**c, "storage_state": stored} if stored else c for c in local_launch_candidates(headless=False, choice=self.payload.get("local_browser"), method=self.payload.get("launch"), port=self.payload.get("attach_port"))]
248
255
  self.browser, self.launch = await start_local_browser(
249
256
  candidates,
250
- make=lambda kw: leave_dialogs(Browser(**kw)),
257
+ # Its downloads go to the recording's own folder, and the library downloads nothing by itself (a PDF).
258
+ make=lambda kw: leave_dialogs(Browser(**{**kw, "downloads_path": str(self.downloads), "auto_download_pdfs": False})),
251
259
  on_fallback=lambda failed, nxt, reason: self.log(f"{browser_name(failed)} did not start ({reason}); trying {browser_name(nxt)}", "warn"),
252
260
  )
253
261
  self.client = CDPClient(self.browser.cdp_url)
@@ -262,9 +270,17 @@ class RecordSession:
262
270
  reg.Page.frameRequestedNavigation(self._queue("requested"))
263
271
  reg.Page.javascriptDialogOpening(self._dialog("dialog_open"))
264
272
  reg.Page.javascriptDialogClosed(self._dialog("dialog_closed"))
273
+ reg.Browser.downloadWillBegin(self._queue("download_begin"))
274
+ reg.Browser.downloadProgress(self._queue("download_progress"))
265
275
  reg.Network.requestWillBeSent(self._queue("request"))
266
276
  reg.Network.responseReceived(self._queue("response"))
267
277
  await self.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True})
278
+ # A file the page downloads lands in the recording's downloads/ folder, and this connection is told of it.
279
+ self.downloads.mkdir(parents=True, exist_ok=True)
280
+ try:
281
+ await self.send("Browser.setDownloadBehavior", {"behavior": "allow", "downloadPath": str(self.downloads.resolve()), "eventsEnabled": True})
282
+ except Exception as ex:
283
+ logger.warning("record: downloads are not watched: %s", ex)
268
284
  if self.llm is None and self.payload.get("llm") and (self.payload["llm"].get("provider") or "") != "mock":
269
285
  try:
270
286
  from .llm import _build_llm, _time_llm_calls
@@ -322,6 +338,15 @@ class RecordSession:
322
338
  # Nothing is sent to the page any more (the panel, a log line): it is going.
323
339
  self.pages.clear()
324
340
  self.frames.clear()
341
+ # The browser ForgeQE started is asked to close itself, every window of it, whatever started its process
342
+ # (on Windows the process a library started is not always the one that shows the window). A browser the
343
+ # tester started and ForgeQE only connected to (browser.launch: attach) is left open.
344
+ if self.client is not None and self.launch.get("_via") != "attach":
345
+ try:
346
+ await asyncio.wait_for(self.client.send.Browser.close(), timeout=5)
347
+ except Exception as ex:
348
+ # It closes before it answers, often: the connection ends instead of a reply.
349
+ logger.debug("record: Browser.close: %s", ex)
325
350
  client, self.client = self.client, None
326
351
  if client is not None:
327
352
  with contextlib.suppress(Exception):
@@ -409,6 +434,12 @@ class RecordSession:
409
434
  self._requests[str(event["requestId"])] = str((event.get("request") or {}).get("method") or "GET")
410
435
  elif kind == "response":
411
436
  self._response(event, sid)
437
+ elif kind == "download_begin":
438
+ if len(self._downloading) > 50:
439
+ self._downloading.clear()
440
+ self._downloading[str(event.get("guid") or "")] = str(event.get("suggestedFilename") or "")
441
+ elif kind == "download_progress":
442
+ self._download_progress(event)
412
443
  elif kind == "dialog_open":
413
444
  if len(self._asked) > 100:
414
445
  self._asked.clear()
@@ -426,6 +457,49 @@ class RecordSession:
426
457
  logger.debug("record: details", exc_info=True)
427
458
  await self._follow_video()
428
459
 
460
+ def _download_progress(self, event: Dict[str, Any]) -> None:
461
+ """A download finished (a step: the file, after the step that started it) or was cancelled (said, not a step)."""
462
+ state = event.get("state")
463
+ if state not in ("completed", "canceled"):
464
+ return
465
+ name = self._downloading.pop(str(event.get("guid") or ""), None)
466
+ rec = self.rec
467
+ if name is None or rec is None:
468
+ return
469
+ if state == "canceled":
470
+ self.log(f"A download was cancelled: {download_name(name) or 'a file'} (not a step)", "warn")
471
+ return
472
+ size = event.get("receivedBytes") if isinstance(event.get("receivedBytes"), int) else None
473
+ msg = rec.on_download(name, size)
474
+ if msg:
475
+ self._changed(msg)
476
+
477
+ def _http_auth(self, event: Dict[str, Any]) -> None:
478
+ """
479
+ A page that answered 401 asking for the browser's own sign-in (basic or digest): the person types it in the
480
+ browser's box, which the recorder never sees. What is kept is the site's origin and the saved login whose sites
481
+ hold it, by its variables' names, so a replay signs in there; with none, the person is told to save one.
482
+ """
483
+ res = event.get("response") or {}
484
+ if int(res.get("status") or 0) != 401:
485
+ return
486
+ headers = {str(k).lower(): str(v) for k, v in (res.get("headers") or {}).items()}
487
+ if not re.match(r"\s*(basic|digest)\b", headers.get("www-authenticate", ""), re.I):
488
+ return
489
+ origin = http_origin(str(res.get("url") or ""))
490
+ if not origin or origin in self.http_auth or len(self.http_auth) >= 10:
491
+ return
492
+ from urllib.parse import urlparse
493
+
494
+ host = urlparse(origin).hostname or ""
495
+ login = next((l for l in self.logins if l.username_env and l.password_env and any(host == h or host.endswith("." + h) for h in l.hosts())), None)
496
+ if login is None:
497
+ self.http_auth[origin] = {"origin": origin}
498
+ self.log(f"{host} asks for the browser's own sign-in. Save a login for it (forgeqe login, with its username and password) so a replay can sign in.", "warn")
499
+ return
500
+ self.http_auth[origin] = {"origin": origin, "login": login.name, "username_env": login.username_env, "password_env": login.password_env}
501
+ self.log(f"{host} asks for the browser's own sign-in: a replay signs in with the saved login {login.name}.")
502
+
429
503
  def _dialog_closed(self, event: Dict[str, Any], sid: Optional[str]) -> None:
430
504
  """The person answered a dialog of a tab or one of its frames: a step with what it asked and their answer."""
431
505
  asked = self._asked.pop(sid or "", None)
@@ -441,6 +515,8 @@ class RecordSession:
441
515
  self._changed(msg)
442
516
 
443
517
  def _response(self, event: Dict[str, Any], sid: Optional[str]) -> None:
518
+ if event.get("type") == "Document":
519
+ self._http_auth(event)
444
520
  method = self._requests.pop(str(event.get("requestId") or ""), None)
445
521
  rec = self.rec
446
522
  if not method or rec is None or not rec.steps or self.paused or event.get("type") not in ("XHR", "Fetch"):
@@ -647,7 +723,7 @@ class RecordSession:
647
723
  if kind == "click":
648
724
  t = await target(data)
649
725
  hover = await target(data["hover"]) if isinstance(data.get("hover"), dict) else None
650
- msg = rec.on_click(t, hover=hover)
726
+ msg = rec.on_click(t, hover=hover, right=data.get("button") == "right")
651
727
  elif kind == "drag":
652
728
  # An element moved: the one taken and, when it was let go on another, that one (each with a point in it).
653
729
  if not isinstance(data.get("source"), dict):
@@ -668,6 +744,16 @@ class RecordSession:
668
744
  msg = await self._uploaded(sid, data, ctx, target)
669
745
  elif kind == "unsupported":
670
746
  msg = rec.on_unsupported(str(data.get("action") or "action"), str(data.get("reason") or ""))
747
+ elif kind == "scroll":
748
+ # The page, or a box that scrolls on its own, scrolled by the person: by screens, up or down.
749
+ pages = data.get("pages")
750
+ if not isinstance(pages, (int, float)) or isinstance(pages, bool) or not 0 < pages <= 50:
751
+ return
752
+ box = await target(data["box"]) if isinstance(data.get("box"), dict) else None
753
+ msg = rec.on_scroll(data.get("down") is not False, float(pages), box)
754
+ elif kind == "hover":
755
+ # The hover command: what the pointer is on, kept as a step (what it shows can be checked after it).
756
+ msg = rec.on_hover(await target(data))
671
757
  elif kind == "pick":
672
758
  # Picked here: a pick waiting in the tab's other frames (or the page) is over.
673
759
  await self._cancel_picks(tab, but=(sid, ctx))
@@ -918,6 +1004,9 @@ class RecordSession:
918
1004
  assert rec is not None
919
1005
  t = await target(data)
920
1006
  text = str(data.get("text") or "")
1007
+ # What only a hover shows (a tooltip, a hover card): hovering its element first, as the tester did.
1008
+ if isinstance(data.get("hover"), dict):
1009
+ rec.on_hover(await target(data["hover"]), inferred=True)
921
1010
  if purpose == "variable":
922
1011
  return rec.add_capture(t, text)
923
1012
  if purpose == "wait":
@@ -1432,6 +1521,9 @@ class RecordSession:
1432
1521
  rec = self.rec
1433
1522
  assert rec is not None
1434
1523
  self.out_dir.mkdir(parents=True, exist_ok=True)
1524
+ # No file was downloaded: no empty downloads/ folder in the recording.
1525
+ with contextlib.suppress(OSError):
1526
+ self.downloads.rmdir()
1435
1527
  video = await self._finish_video()
1436
1528
  # The recorder's own working fields (an element's facts) stay out of the run.
1437
1529
  steps = [
@@ -1477,6 +1569,7 @@ class RecordSession:
1477
1569
  "secrets": list(rec.secrets),
1478
1570
  "skipped": list(rec.skipped),
1479
1571
  "signed_in": bool(self.payload.get("signed_in")),
1572
+ **({"http_auth": list(self.http_auth.values())} if self.http_auth else {}),
1480
1573
  **({"work_dir": str(self.payload["work_dir"])} if any(s.get("op") == "upload" for s in steps) and self.payload.get("work_dir") else {}),
1481
1574
  **({"case_id": self.case_id, "case_gaps": rec.case_gaps()} if rec.case_steps else {}),
1482
1575
  },
@@ -1550,6 +1643,16 @@ OPEN_SHADOW_JS = r"""(() => {
1550
1643
  })()"""
1551
1644
 
1552
1645
 
1646
+ def http_origin(url: str) -> str:
1647
+ """A web address's origin (scheme, host and port), http(s) only, with no user or password in it; "" for any other."""
1648
+ from urllib.parse import urlparse
1649
+
1650
+ u = urlparse(url or "")
1651
+ if u.scheme not in ("http", "https") or not u.hostname or u.username or u.password:
1652
+ return ""
1653
+ return f"{u.scheme}://{u.netloc.lower()}"
1654
+
1655
+
1553
1656
  def drag_offset(raw: Any) -> Optional[Dict[str, int]]:
1554
1657
  """How far a drag moved the pointer, as the page script reported it: two whole numbers within a page's size, else None."""
1555
1658
  if not isinstance(raw, dict):
@@ -1704,7 +1807,7 @@ async def record_web(payload: Dict[str, Any], emit: Emit, commands: asyncio.Queu
1704
1807
  await s.start()
1705
1808
  await s.open()
1706
1809
  if s.payload.get("panel") == "badge":
1707
- s.log(f"Recording in the browser. Do the steps; you choose the checks and the test data when you stop. In the page, {leader_label(s.leader)} then P pauses, Z undoes, S stops.")
1810
+ s.log(f"Recording in the browser. Do the steps; you choose the checks and the test data when you stop. In the page, {leader_label(s.leader)} then H keeps a hover on what the pointer is on, P pauses, Z undoes, S stops.")
1708
1811
  else:
1709
1812
  s.log(f"Recording in the browser. Do the steps; the Recorder panel is in the page. {leader_label(s.leader)} then a letter adds a check, a variable, a note (S stops).")
1710
1813
  await s.run(float(payload.get("max_seconds") or MAX_SECONDS))
@@ -267,7 +267,8 @@ def describe(step: Dict[str, Any]) -> str:
267
267
  if op in ("click", "dblclick", "hover"):
268
268
  pos = step.get("position") if isinstance(step.get("position"), dict) else None
269
269
  at = f" at {pos.get('x')},{pos.get('y')}" if pos else ""
270
- return f"{'double-click' if op == 'dblclick' else op} {label}{at}"
270
+ verb = "double-click" if op == "dblclick" else "right-click" if step.get("button") == "right" else op
271
+ return f"{verb} {label}{at}"
271
272
  if op == "input":
272
273
  if step.get("text_env"):
273
274
  return f"type ${step['text_env']} into {label}"
@@ -288,6 +289,12 @@ def describe(step: Dict[str, Any]) -> str:
288
289
  return f"solve the {step.get('provider') or 'CAPTCHA'} (a person; a test turns it off)"
289
290
  if op == "dialog":
290
291
  return dialog_words(step)
292
+ if op == "scroll":
293
+ where = f" in {label}" if step.get("locators") else ""
294
+ return f"scroll {'down' if step.get('down', True) else 'up'} {step.get('pages', 1)} screen{'s' if step.get('pages', 1) != 1 else ''}{where}"
295
+ if op == "download":
296
+ changes = " (its name changes; matched by its pattern)" if step.get("file_pattern") else ""
297
+ return f"the file {step.get('file')!r} downloads{changes}"
291
298
  if op == "drag":
292
299
  to = step.get("to") if isinstance(step.get("to"), dict) else None
293
300
  if to:
@@ -317,6 +324,19 @@ def describe(step: Dict[str, Any]) -> str:
317
324
  return op
318
325
 
319
326
 
327
+ MAX_FILE_NAME = 200
328
+
329
+
330
+ def download_name(raw: Any) -> str:
331
+ """
332
+ A downloaded file's name as a step keeps it: the page's suggestion, its last part only (never a folder), one line
333
+ of plain characters, clipped; "" for none. It is data: a replay compares it, and saves the file by its own name.
334
+ """
335
+ name = re.split(r"[\\/]", str(raw or ""))[-1]
336
+ name = "".join(ch for ch in name if ch.isprintable()).strip().strip(".")
337
+ return name[:MAX_FILE_NAME]
338
+
339
+
320
340
  def dialog_message(raw: Any) -> str:
321
341
  """A dialog's message as a step keeps it: page text, one line, clipped (never markup or a command)."""
322
342
  text = " ".join(str(raw or "").split())
@@ -388,11 +408,20 @@ class WebRecorder:
388
408
  self._add({"op": "navigate", "url": url})
389
409
  return f"open {url}"
390
410
 
391
- def on_click(self, t: Target, *, hover: Optional[Target] = None) -> Optional[str]:
411
+ def on_click(self, t: Target, *, hover: Optional[Target] = None, right: bool = False) -> Optional[str]:
392
412
  if self.paused:
393
413
  return None
394
414
  at = self.clock()
395
415
  self._last_action = at
416
+ if right:
417
+ # A right-click (the page's own context menu): never half of a double-click.
418
+ self._last_click = None
419
+ if hover is not None and hover.key != t.key:
420
+ prev = self.steps[-1]
421
+ if not (prev.get("op") == "hover" and _same(prev, hover)):
422
+ self._add({**element_step("hover", hover), "inferred": True})
423
+ self._add({**element_step("click", t), "button": "right"})
424
+ return describe(self.steps[-1])
396
425
  last = self._last_click
397
426
  if last is not None and last[0] == t.key and at - last[1] <= DOUBLE_CLICK_SECONDS and self.steps[-1].get("op") == "click":
398
427
  self.steps[-1] = {**self.steps[-1], "op": "dblclick"}
@@ -406,6 +435,39 @@ class WebRecorder:
406
435
  self._last_click = (t.key, at)
407
436
  return describe(self.steps[-1])
408
437
 
438
+ def on_scroll(self, down: bool, pages: float, box: Optional[Target] = None) -> Optional[str]:
439
+ """
440
+ The page (or `box`, a list that scrolls on its own) scrolled by the person, by screens: one step for scrolls
441
+ one after another the same way in the same place. A replay scrolls as far, so what loads on a scroll loads.
442
+ """
443
+ if self.paused or not 0 < pages <= 50:
444
+ return None
445
+ self._last_action = self.clock()
446
+ self._last_click = None
447
+ prev = self.steps[-1]
448
+ same_place = (box is None and not prev.get("locators")) or (box is not None and _same(prev, box))
449
+ if prev.get("op") == "scroll" and bool(prev.get("down", True)) == down and same_place:
450
+ prev["pages"] = round(min(50.0, float(prev.get("pages") or 0) + pages), 1)
451
+ return describe(prev)
452
+ step: Dict[str, Any] = {**(element_step("scroll", box) if box is not None else {"op": "scroll", "page": page_id(self.url) or self.url}), "down": down, "pages": round(pages, 1)}
453
+ self._add(step)
454
+ return describe(step)
455
+
456
+ def on_hover(self, t: Target, *, inferred: bool = False) -> Optional[str]:
457
+ """
458
+ A hover kept as a step: by the hover command (the element the pointer is on), or before a check of what only a
459
+ hover shows (`inferred`). Once: never right after the same hover.
460
+ """
461
+ if self.paused:
462
+ return None
463
+ prev = self.steps[-1]
464
+ if prev.get("op") == "hover" and _same(prev, t):
465
+ return None
466
+ self._last_action = self.clock()
467
+ self._last_click = None
468
+ self._add({**element_step("hover", t), **({"inferred": True} if inferred else {})})
469
+ return describe(self.steps[-1])
470
+
409
471
  def on_captcha(self, provider: str) -> Optional[str]:
410
472
  """
411
473
  Something done in a CAPTCHA: one `captcha` step for it, however many clicks it took (the checkbox, the pictures,
@@ -420,6 +482,27 @@ class WebRecorder:
420
482
  self._add({"op": "captcha", "provider": provider, "page": page_id(self.url) or self.url})
421
483
  return describe(self.steps[-1])
422
484
 
485
+ def on_download(self, name: Any, size: Optional[int] = None) -> Optional[str]:
486
+ """
487
+ A file the page downloaded after the step before (an "Export CSV" button): a step that checks a file of that
488
+ name arrives, by a pattern when part of the name changes on each run (a date, an id), and is not empty.
489
+ """
490
+ if self.paused:
491
+ return None
492
+ file = download_name(name)
493
+ if not file:
494
+ return None
495
+ self._last_action = self.clock()
496
+ self._last_click = None
497
+ step: Dict[str, Any] = {"op": "download", "file": file, "page": page_id(self.url) or self.url}
498
+ pattern = dynamic.pattern_of(file, anchored=True)
499
+ if pattern:
500
+ step["file_pattern"] = pattern
501
+ if isinstance(size, int) and not isinstance(size, bool) and size >= 0:
502
+ step["bytes"] = size
503
+ self._add(step)
504
+ return describe(step)
505
+
423
506
  def on_dialog(self, kind: str, message: Any, accept: bool, text: Any = None) -> Optional[str]:
424
507
  """
425
508
  A browser dialog the page showed (an alert, a confirm, a prompt, or "leave this page?") and how the person answered
@@ -23,6 +23,7 @@ COMMAND_KEYS = (
23
23
  ("w", "wait", "wait for an element"),
24
24
  ("d", "data", "last typed value is test data"),
25
25
  ("n", "note", "add a note"),
26
+ ("h", "hover", "hover the element under the pointer"),
26
27
  ("p", "pause", "pause / resume"),
27
28
  ("z", "undo", "undo last step"),
28
29
  ("s", "stop", "stop recording"),
@@ -504,11 +505,18 @@ RECORDER_JS = r"""(() => {
504
505
  // What shows soon after a press (a click's doing: a list of results, the fields a choice opens) is not a hover's.
505
506
  let pressedAt = 0;
506
507
  window.addEventListener('pointerdown', (ev) => { if (ev.isTrusted && !ours(ev)) pressedAt = Date.now(); }, true);
508
+ // Any element the pointer is on (an info icon, an abbreviation): what shows while it rests there is its tooltip or
509
+ // hover card. Kept apart ("loose") from a menu's trigger: a check of what it shows starts with hovering it.
510
+ let pointed = null;
507
511
  const onReveal = (list) => {
508
- if (!hovered || Date.now() - hovered.at > 1500 || Date.now() - pressedAt < 1500) return;
512
+ if (Date.now() - pressedAt < 1500) return;
513
+ const by = hovered && Date.now() - hovered.at <= 1500 ? hovered : null;
514
+ const loose = !by && pointed && Date.now() - pointed.at <= 1500 ? pointed : null;
515
+ if (!by && !loose) return;
516
+ const at = (by || loose).el;
509
517
  for (const m of list) {
510
518
  const n = m.type === 'childList' ? [...m.addedNodes].find((x) => x.nodeType === 1) : m.target;
511
- if (n && n.nodeType === 1 && !deepContains(n, hovered.el) && n !== host) revealed.push({ by: hovered.el, root: n, at: Date.now() });
519
+ if (n && n.nodeType === 1 && !deepContains(n, at) && n !== host && !deepContains(n, host)) revealed.push({ by: at, root: n, at: Date.now(), ...(loose ? { loose: true } : {}) });
512
520
  }
513
521
  if (revealed.length > 50) revealed.splice(0, revealed.length - 50);
514
522
  };
@@ -529,20 +537,51 @@ RECORDER_JS = r"""(() => {
529
537
  for (const type of ['mouseover', 'focusin', 'pointerdown']) window.addEventListener(type, (ev) => { if (ev.isTrusted && !ours(ev)) watchRoots(ev); }, true);
530
538
  window.addEventListener('mouseover', (ev) => {
531
539
  if (!ev.isTrusted || picking || ours(ev)) return;
540
+ const p = deep(ev);
541
+ if (p && p.nodeType === 1 && (!pointed || p !== pointed.el)) pointed = { el: p, at: Date.now() };
532
542
  const t = deepClosest(deep(ev), TRIGGER);
533
543
  if (t && (!hovered || t !== hovered.el)) hovered = { el: t, at: Date.now() };
534
544
  }, true);
535
545
  // Showing on the page now: a menu's trigger a person still points at, not one gone with its list.
536
546
  const shows = (e) => { const r = e.getBoundingClientRect(); if (r.width < 1 || r.height < 1) return false; const cs = getComputedStyle(e); return cs.visibility !== 'hidden' && cs.display !== 'none'; };
547
+ // The hover command: a step that hovers what the pointer is on now (what shows then can be checked after it).
548
+ const hoverNow = () => {
549
+ if (paused) return;
550
+ const e = pointed && pointed.el;
551
+ if (!e || !e.isConnected || e === document.documentElement || e === document.body || e.tagName === 'IFRAME') {
552
+ say([[0, 'Point at the element to hover first, then press the keys']], 4000);
553
+ return;
554
+ }
555
+ if (dirty) flush();
556
+ send({ kind: 'hover', ...describeEl(hoverable(e)) });
557
+ };
558
+ // The element a hover is kept for: the control around what the pointer is on, else the nearest one a tooltip names
559
+ // (aria-describedby, a title, a test id, an id, a label), else that element.
560
+ const hoverable = (e) => {
561
+ for (let x = e, i = 0; x && x.nodeType === 1 && i <= 4 && x !== document.body; x = up(x), i++) {
562
+ if (actionable(x) || x.hasAttribute('aria-describedby') || x.hasAttribute('title') || x.hasAttribute('data-tooltip') || named(x)) return x;
563
+ }
564
+ return e;
565
+ };
566
+ // What a check of an element that shows only on a hover (a tooltip, a hover card) hovers first: the element the
567
+ // pointer rested on when it showed, still on the page.
568
+ const hoverForCheck = (c) => {
569
+ for (let i = revealed.length - 1; i >= 0; i--) {
570
+ const r = revealed[i];
571
+ if (deepContains(r.root, c) && r.by !== c && !deepContains(r.by, c) && r.by.isConnected && shows(r.by) && Date.now() - r.at < 60000) return hoverable(r.by);
572
+ }
573
+ return null;
574
+ };
537
575
  const hoverFor = (c) => {
538
576
  for (let i = revealed.length - 1; i >= 0; i--) {
539
577
  const r = revealed[i];
540
- if (deepContains(r.root, c) && r.by !== c && !deepContains(r.by, c) && r.by.isConnected && shows(r.by) && Date.now() - r.at < 60000) return r.by;
578
+ if (!r.loose && deepContains(r.root, c) && r.by !== c && !deepContains(r.by, c) && r.by.isConnected && shows(r.by) && Date.now() - r.at < 60000) return r.by;
541
579
  }
542
580
  for (let e = up(c), i = 0; e && e !== document.body && i < 8; e = up(e), i++) {
543
581
  if (!e.matches(MENU)) continue;
544
582
  const owner = up(e);
545
- if (!owner || !owner.matches(':hover')) continue;
583
+ // A menu placed straight in the page (a context menu, a popup): its siblings are the page, not its trigger.
584
+ if (!owner || owner === document.body || owner === document.documentElement || !owner.matches(':hover')) continue;
546
585
  const trig = [...owner.children].find((x) => x !== e && !deepContains(x, c) && (x.matches(TRIGGER) || (x.querySelector && x.querySelector('a, button'))));
547
586
  if (trig) return trig.matches(TRIGGER) ? trig : trig.querySelector('a, button');
548
587
  }
@@ -609,7 +648,8 @@ RECORDER_JS = r"""(() => {
609
648
  const purpose = picking.purpose;
610
649
  endPick();
611
650
  if (!e) return;
612
- send({ kind: 'pick', purpose, ...describeEl(e), text: shown(e), password: isPassword(e), checked: 'checked' in e ? !!e.checked : null, field: e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.tagName === 'SELECT' });
651
+ const h = hoverForCheck(e);
652
+ send({ kind: 'pick', purpose, ...describeEl(e), text: shown(e), password: isPassword(e), checked: 'checked' in e ? !!e.checked : null, field: e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.tagName === 'SELECT', ...(h ? { hover: describeEl(h) } : {}) });
613
653
  return;
614
654
  }
615
655
  if (paused) return;
@@ -624,6 +664,41 @@ RECORDER_JS = r"""(() => {
624
664
  const h = hoverFor(c);
625
665
  send({ kind: 'click', ...describeEl(c), field: isField(c), ...(h ? { hover: describeEl(h) } : {}), ...where(c, ev) });
626
666
  }, true);
667
+ // ---- scrolls: the page, or a box that scrolls on its own (a list that loads more at its end), by the person's wheel
668
+ // or keys (never one the page made: an anchor, its own script). One step when it settles, if it went half a screen.
669
+ const SCROLL_KEYS = new Set(['PageDown', 'PageUp', 'ArrowDown', 'ArrowUp', 'End', 'Home', ' ']);
670
+ let scrollBy = 0, scrolled = null;
671
+ window.addEventListener('wheel', (ev) => { if (ev.isTrusted && !ours(ev)) scrollBy = Date.now(); }, { capture: true, passive: true });
672
+ window.addEventListener('keydown', (ev) => { if (ev.isTrusted && !ours(ev) && SCROLL_KEYS.has(ev.key) && !isField(deep(ev))) scrollBy = Date.now(); }, true);
673
+ const scrollTop = (box) => (box ? box.scrollTop : (document.scrollingElement || document.documentElement).scrollTop);
674
+ const endScroll = () => {
675
+ const s = scrolled;
676
+ scrolled = null;
677
+ if (!s || paused || picking) return;
678
+ const height = s.box ? s.box.clientHeight : innerHeight;
679
+ const dy = scrollTop(s.box) - s.top;
680
+ if (!height || Math.abs(dy) < height / 2) return;
681
+ if (s.box && !s.box.isConnected) return;
682
+ send({ kind: 'scroll', down: dy > 0, pages: Math.round(Math.abs(dy) / height * 10) / 10, ...(s.box ? { box: describeEl(s.box) } : {}) });
683
+ };
684
+ window.addEventListener('scroll', (ev) => {
685
+ if (!ev.isTrusted || paused || picking || Date.now() - scrollBy > 1500) return;
686
+ const t = ev.target;
687
+ const box = !t || t === document || t === document.documentElement || t === document.body || t.nodeType !== 1 ? null : t;
688
+ if (box && (box === host || ours(ev))) return;
689
+ if (scrolled && scrolled.box !== box) { clearTimeout(scrolled.timer); endScroll(); }
690
+ if (!scrolled) scrolled = { box, top: scrollTop(box) - 0, timer: 0 };
691
+ clearTimeout(scrolled.timer);
692
+ scrolled.timer = setTimeout(endScroll, 700);
693
+ }, true);
694
+ // A right-click (a page's own context menu): a click with the right button, on the control it was on.
695
+ window.addEventListener('contextmenu', (ev) => {
696
+ if (!ev.isTrusted || picking || ours(ev) || paused || ev.button !== 2) return;
697
+ const c = control(deep(ev));
698
+ if (!c || c === document.documentElement || c === document.body) return;
699
+ if (dirty) flush();
700
+ send({ kind: 'click', button: 'right', ...describeEl(c), ...where(c, ev) });
701
+ }, true);
627
702
  window.addEventListener('dblclick', (ev) => {
628
703
  if (!ev.isTrusted || picking || ours(ev) || paused) return;
629
704
  const c = control(deep(ev));
@@ -759,6 +834,7 @@ RECORDER_JS = r"""(() => {
759
834
  ev.preventDefault(); ev.stopImmediatePropagation();
760
835
  tip.style.display = 'none';
761
836
  const hit = CFG.commands.find(([k]) => k === ev.key.toLowerCase());
837
+ if (hit && hit[1] === 'hover') { hoverNow(); return true; }
762
838
  if (hit) { if (dirty) flush(); picks(hit[1]); send({ kind: 'command', cmd: hit[1] }); }
763
839
  return true;
764
840
  }