@capagents/forgeqe 2.9.9 → 2.10.0

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 (54) hide show
  1. package/dist/forgeqe.js +1640 -1581
  2. package/dist/web/assets/{Agent-B0R4tnqF.js → Agent-B_mG1pww.js} +1 -1
  3. package/dist/web/assets/{ApiTests-CqWPHWCs.js → ApiTests-C2QIp_tG.js} +1 -1
  4. package/dist/web/assets/{Browse-DlbTQPA8.js → Browse-zQoOQXpA.js} +2 -2
  5. package/dist/web/assets/{Chat-DtI3dgGs.js → Chat-BtLEKYY8.js} +1 -1
  6. package/dist/web/assets/{CommandPalette-BTI3Q3sc.js → CommandPalette-BgQORiKD.js} +1 -1
  7. package/dist/web/assets/{Compare-BMcHYq3I.js → Compare-DQNg3ldO.js} +1 -1
  8. package/dist/web/assets/{Cost-BcZ6gC9M.js → Cost-T0NH8ymc.js} +1 -1
  9. package/dist/web/assets/{Data-Cbl35RTK.js → Data-CqKsrslC.js} +1 -1
  10. package/dist/web/assets/{Desktop-D4JLSUnE.js → Desktop-CgDXi3lX.js} +1 -1
  11. package/dist/web/assets/{DesktopReview-vyosGOyC.js → DesktopReview-C-gW_gli.js} +1 -1
  12. package/dist/web/assets/{Evidence-MDaV4ttv.js → Evidence-1pipN6K6.js} +1 -1
  13. package/dist/web/assets/{Explore-yjmJHnzH.js → Explore-lG_kobPj.js} +1 -1
  14. package/dist/web/assets/{Features-kXt6Um2p.js → Features-BIrW3AiQ.js} +1 -1
  15. package/dist/web/assets/{Flags-CdLXiacX.js → Flags-sG1vr7NU.js} +1 -1
  16. package/dist/web/assets/{Flaky-BZx54uo3.js → Flaky-ChKBXlcW.js} +1 -1
  17. package/dist/web/assets/{Impact-_t7bwCwP.js → Impact-D5a5fyc2.js} +1 -1
  18. package/dist/web/assets/{Jobs-D4PIAcdO.js → Jobs-B52pIZUx.js} +1 -1
  19. package/dist/web/assets/{KindPage-CGfjoezZ.js → KindPage-BFoKPj7l.js} +1 -1
  20. package/dist/web/assets/{Migration-OGOnRmUX.js → Migration-DbuzD_s4.js} +1 -1
  21. package/dist/web/assets/{Product-DycPE2MI.js → Product-DiH61j0X.js} +1 -1
  22. package/dist/web/assets/{Production-DqnrcSfn.js → Production-8h5LixDt.js} +1 -1
  23. package/dist/web/assets/{Quality-C__pEYpt.js → Quality-CI5n8b_k.js} +1 -1
  24. package/dist/web/assets/{Readiness-j22NEcwR.js → Readiness-D4n4HSlW.js} +1 -1
  25. package/dist/web/assets/{Record-D7h6g_aw.js → Record-O8LOzHLo.js} +1 -1
  26. package/dist/web/assets/{Regression-ByBOHx96.js → Regression-DbShD6ji.js} +1 -1
  27. package/dist/web/assets/{Reports-BGs_YnwI.js → Reports-IdoUvtaW.js} +1 -1
  28. package/dist/web/assets/{Response-DWF22-5i.js → Response-BRVM9mW_.js} +1 -1
  29. package/dist/web/assets/{RunDiff-YxrBVtxF.js → RunDiff-uQoK3Q6q.js} +1 -1
  30. package/dist/web/assets/{Runs-CP3CgO6s.js → Runs-BhDgzDo4.js} +1 -1
  31. package/dist/web/assets/{TestCases-BzuM4M4t.js → TestCases-DQ2oWXt2.js} +1 -1
  32. package/dist/web/assets/{TestData-CRmYpEgE.js → TestData-D-ZdmHVa.js} +1 -1
  33. package/dist/web/assets/{TestDebt-D3I2zyGE.js → TestDebt-_jer4Dmy.js} +1 -1
  34. package/dist/web/assets/{Tosca-jVIQnyZv.js → Tosca-DOT6-53c.js} +1 -1
  35. package/dist/web/assets/{WhatsNew-EKniIJ6W.js → WhatsNew-DU5k6dz6.js} +1 -1
  36. package/dist/web/assets/{dataParts-DRO6c2Kb.js → dataParts-BzuL6pAo.js} +1 -1
  37. package/dist/web/assets/{fold-D9yUIbTt.js → fold-DZYvcIP0.js} +1 -1
  38. package/dist/web/assets/{frame--ur6lpMR.js → frame-Bjxy1jvq.js} +2 -2
  39. package/dist/web/assets/{index-GLMqsotN.js → index-DH21lIE7.js} +4 -4
  40. package/dist/web/assets/{logos-CdIbTq_J.js → logos-Co26FM0G.js} +1 -1
  41. package/dist/web/assets/{palette-D5_w8xup.js → palette-CitkMCod.js} +1 -1
  42. package/dist/web/assets/{qualityParts-BPBFzuHH.js → qualityParts-DADI5Fqn.js} +1 -1
  43. package/dist/web/assets/{rows-BVHC-HKz.js → rows-BqT7fknl.js} +1 -1
  44. package/dist/web/assets/{thread-B4g66SWA.js → thread-iRsceqhM.js} +1 -1
  45. package/dist/web/assets/{usePageChat-BU6VEv0K.js → usePageChat-BCrPoTyS.js} +1 -1
  46. package/dist/web/index.html +2 -2
  47. package/package.json +1 -1
  48. package/py/forgeqe_engine/browser.py +29 -0
  49. package/py/forgeqe_engine/capture.py +2 -2
  50. package/py/forgeqe_engine/dynamic.py +8 -0
  51. package/py/forgeqe_engine/memory.py +33 -2
  52. package/py/forgeqe_engine/recordsession.py +167 -19
  53. package/py/forgeqe_engine/webrecord.py +80 -0
  54. package/py/forgeqe_engine/webrecord_page.py +118 -8
@@ -139,6 +139,33 @@ def _sha(text: str, n: int) -> str:
139
139
  return hashlib.sha1(text.encode("utf-8")).hexdigest()[:n]
140
140
 
141
141
 
142
+ # Classes a page sets for a state, not for what an element is: the item under the pointer or chosen (active, selected,
143
+ # current, highlighted), a menu or panel open or shown, a field focused or with an error. They move between elements, so
144
+ # a locator never names one: `div.item.active` finds whichever item is active on the run.
145
+ STATE_CLASS = r"^(?:is-|has-|js-)|^(?:active|selected|current|focus(?:ed)?|focus-visible|hover(?:ed)?|highlight(?:ed)?|open(?:ed)?|show(?:n|ing)?|visible|hidden|in|fade|expanded|collapsed|checked|disabled|invalid|valid|error|loading|loaded|ready|on|off)$|[-_](?:active|selected|current|focus(?:ed)?|hover(?:ed)?|highlight(?:ed)?|open(?:ed)?|expanded|collapsed|checked|disabled)$"
146
+ _STATE_CLASS = re.compile(STATE_CLASS, re.I)
147
+
148
+
149
+ def state_class(value: str) -> bool:
150
+ """Whether a class says a state the element is in (active, selected, is-open), not what it is."""
151
+ return bool(_STATE_CLASS.search(value or ""))
152
+
153
+
154
+ # A name longer than this is matched by its start (a search result's whole text is the name of its link).
155
+ MAX_ROLE_NAME = 80
156
+ ROLE_NAME_START = 40
157
+
158
+
159
+ def name_start(name: str) -> str:
160
+ """The first words of a long name, at most ROLE_NAME_START characters: enough to tell one result from the next."""
161
+ out = ""
162
+ for word in name.split():
163
+ if out and len(out) + 1 + len(word) > ROLE_NAME_START:
164
+ break
165
+ out = f"{out} {word}" if out else word[:ROLE_NAME_START]
166
+ return out.rstrip(" ,;:-–—|/")
167
+
168
+
142
169
  def looks_generated(value: str) -> bool:
143
170
  """Framework-generated ids and hashes change between builds or page loads."""
144
171
  return any(p.search(value or "") for p in _GENERATED)
@@ -249,7 +276,7 @@ def element_facts(node: Any) -> Dict[str, Any]:
249
276
  cls = filter_dynamic_classes(cls)
250
277
  except Exception:
251
278
  pass
252
- classes = [c for c in cls.split() if _css_ident(c) and not looks_generated(c)]
279
+ classes = [c for c in cls.split() if _css_ident(c) and not looks_generated(c) and not state_class(c)]
253
280
  return {
254
281
  "tag": tag,
255
282
  "role": role,
@@ -301,6 +328,10 @@ def candidate_locators(f: Dict[str, Any]) -> List[Dict[str, Any]]:
301
328
  # The name has an icon character: match its words, with any icon or space around them.
302
329
  pattern = f"^\\W*{_js_regex(plain)}\\W*$"
303
330
  add("role_pattern", f"{role}|{pattern}", f"page.getByRole({_q(role)}, {{ name: /{pattern}/ }})", role=role, name=name)
331
+ elif role in ROLES and plain and len(name) > MAX_ROLE_NAME and playwright_role_ok(tag, a, role) and len(name_start(plain)) >= 8:
332
+ # A long name (a search result's whole text): by how it starts; the rest (a distance, a price) is data.
333
+ pattern = f"^\\W*{_js_regex(name_start(plain))}"
334
+ add("role_pattern", f"{role}|{pattern}", f"page.getByRole({_q(role)}, {{ name: /{pattern}/ }})", role=role, name=name)
304
335
  if a.get("name"):
305
336
  css = f"{tag}[name={_q(a['name'])}]"
306
337
  add("name", a["name"], f"page.locator({_q(css)})", css=css)
@@ -323,7 +354,7 @@ def candidate_locators(f: Dict[str, Any]) -> List[Dict[str, Any]]:
323
354
  text = strip_icons(f.get("text") or (name if tag not in FORM_TAGS else ""))
324
355
  if text and len(text) <= 60 and tag not in FORM_TAGS:
325
356
  add("text", text, f"page.getByText({_q(text)}, {{ exact: true }})")
326
- classes = f.get("classes") or []
357
+ classes = [c for c in f.get("classes") or [] if not state_class(c)]
327
358
  if classes:
328
359
  css = tag + "".join(f".{c}" for c in classes[:2])
329
360
  add("css", css, f"page.locator({_q(css)})", css=css)
@@ -19,6 +19,7 @@ Events: ``log``, ``steps`` (the whole list, after each change), ``call`` (one mo
19
19
  from __future__ import annotations
20
20
 
21
21
  import asyncio
22
+ import contextlib
22
23
  import json
23
24
  import logging
24
25
  import os
@@ -30,7 +31,7 @@ from types import SimpleNamespace
30
31
  from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
31
32
 
32
33
  from .capture import capture_element, locate_check
33
- from .memory import BASE, KEPT_ATTRS, candidate_locators, confidence, looks_generated, within_locator
34
+ from .memory import BASE, KEPT_ATTRS, candidate_locators, confidence, looks_generated, state_class, within_locator
34
35
  from . import dynamic
35
36
  from .webrecord import CAPTCHA_FRAMES, MAX_UPLOAD_FILES, Target, WebRecorder, auto_name, captcha_of, describe, keep_upload, upload_path
36
37
  from .webrecord_page import recorder_js
@@ -45,6 +46,9 @@ logger = logging.getLogger("forgeqe_engine.record")
45
46
  Emit = Callable[[Dict[str, Any]], None]
46
47
 
47
48
  CDP_TIMEOUT = 5.0
49
+ # While a browser dialog is open the page's scripts wait for the person's answer, and so does a call into the page: it is
50
+ # waited for (up to this long) rather than given up after CDP_TIMEOUT.
51
+ DIALOG_WAIT = 600.0
48
52
  # A step's picture of the page: taken this long after the step, once the page has answered it; at most this many.
49
53
  SHOT_SETTLE = 0.7
50
54
  MAX_SHOTS = 400
@@ -170,6 +174,13 @@ class RecordSession:
170
174
  # The page's own API calls after each step (method, path, status), for checks of them in the review.
171
175
  self.calls: Dict[int, List[Dict[str, Any]]] = {}
172
176
  self._requests: Dict[str, str] = {}
177
+ # The browser was closed once the recording stopped (release_browser), and its facts read just before.
178
+ self.released = False
179
+ self.profile: Optional[Dict[str, Any]] = None
180
+ # Sessions with a browser dialog open, how many have opened, and what each asked (to record with its answer).
181
+ self._dialogs: set = set()
182
+ self._dialog_count = 0
183
+ self._asked: Dict[str, Dict[str, Any]] = {}
173
184
  # video.mp4 of the tab being recorded (payload ``video``), following the tester from tab to tab; paused with them.
174
185
  self.video: Any = None
175
186
  self._video_sid: Optional[str] = None
@@ -177,12 +188,39 @@ class RecordSession:
177
188
  # -- the browser ----------------------------------------------------------------------------------------------
178
189
 
179
190
  async def send(self, method: str, params: Optional[Dict[str, Any]] = None, sid: Optional[str] = None) -> Dict[str, Any]:
191
+ if self.client is None:
192
+ raise RuntimeError("the recording's browser is closed")
180
193
  domain, name = method.split(".", 1)
181
194
  fn = getattr(getattr(self.client.send, domain), name)
182
195
  kw: Dict[str, Any] = {"params": params} if params is not None else {}
183
196
  if sid:
184
197
  kw["session_id"] = sid
185
- return await asyncio.wait_for(fn(**kw), timeout=CDP_TIMEOUT) or {}
198
+ call = asyncio.ensure_future(fn(**kw))
199
+ waited = 0.0
200
+ while True:
201
+ seen = self._dialog_count
202
+ done, _ = await asyncio.wait({call}, timeout=CDP_TIMEOUT)
203
+ if done:
204
+ return call.result() or {}
205
+ waited += CDP_TIMEOUT
206
+ # A dialog open now, or one that opened meanwhile: the page waits for the person, and the call with it.
207
+ if (self._dialogs or self._dialog_count != seen) and waited < DIALOG_WAIT:
208
+ continue
209
+ call.cancel()
210
+ raise asyncio.TimeoutError()
211
+
212
+ def _dialog(self, kind: str) -> Callable[[Any, Optional[str]], None]:
213
+ """A dialog opening or closing: known at once (calls into the page wait while one is open), and queued to record."""
214
+ def handler(event: Any, session_id: Optional[str] = None) -> None:
215
+ key = session_id or ""
216
+ if kind == "dialog_open":
217
+ self._dialogs.add(key)
218
+ self._dialog_count += 1
219
+ else:
220
+ self._dialogs.discard(key)
221
+ self.queue.put_nowait((kind, event, session_id))
222
+
223
+ return handler
186
224
 
187
225
  def _queue(self, kind: str) -> Callable[[Any, Optional[str]], None]:
188
226
  def handler(event: Any, session_id: Optional[str] = None) -> None:
@@ -195,7 +233,7 @@ class RecordSession:
195
233
  from cdp_use.client import CDPClient
196
234
 
197
235
  from . import brand
198
- from .browser import browser_name, local_launch_candidates, start_local_browser
236
+ from .browser import browser_name, leave_dialogs, local_launch_candidates, start_local_browser
199
237
  from .logins import load_sessions, parse_logins, text_envs, use_logins
200
238
 
201
239
  logins = parse_logins(self.payload.get("logins"))
@@ -209,7 +247,7 @@ class RecordSession:
209
247
  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"))]
210
248
  self.browser, self.launch = await start_local_browser(
211
249
  candidates,
212
- make=lambda kw: Browser(**kw),
250
+ make=lambda kw: leave_dialogs(Browser(**kw)),
213
251
  on_fallback=lambda failed, nxt, reason: self.log(f"{browser_name(failed)} did not start ({reason}); trying {browser_name(nxt)}", "warn"),
214
252
  )
215
253
  self.client = CDPClient(self.browser.cdp_url)
@@ -222,6 +260,8 @@ class RecordSession:
222
260
  reg.Page.frameNavigated(self._queue("navigated"))
223
261
  reg.Page.navigatedWithinDocument(self._queue("navigated_same"))
224
262
  reg.Page.frameRequestedNavigation(self._queue("requested"))
263
+ reg.Page.javascriptDialogOpening(self._dialog("dialog_open"))
264
+ reg.Page.javascriptDialogClosed(self._dialog("dialog_closed"))
225
265
  reg.Network.requestWillBeSent(self._queue("request"))
226
266
  reg.Network.responseReceived(self._queue("response"))
227
267
  await self.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True})
@@ -259,16 +299,40 @@ class RecordSession:
259
299
  if str(getattr(self.browser, "cdp_url", "") or "").startswith(("http://127.0.0.1:", "ws://127.0.0.1:", "http://localhost:", "ws://localhost:")):
260
300
  self.emit({"type": "browser", "cdp": self.browser.cdp_url})
261
301
 
262
- async def close(self) -> None:
263
- from .browser import _shutdown_browser_instance
302
+ async def release_browser(self) -> None:
303
+ """
304
+ The recording is over: its browser closes now, before what is left (the model's look at the values, the video
305
+ made from its pictures, the run's files), which needs none, so the window goes when the tester stops. The video's
306
+ pictures stop coming first, and the browser's facts for the run are read while it is still there.
307
+ """
308
+ from .browser import _shutdown_browser_instance, browser_profile
264
309
 
265
- await self._finish_video()
266
- if self.client is not None:
310
+ if self.released:
311
+ return
312
+ self.released = True
313
+ sid, self._video_sid = self._video_sid, None
314
+ if self.video is not None and sid and sid in self.pages:
315
+ with contextlib.suppress(Exception):
316
+ await self.send("Page.stopScreencast", {}, sid)
317
+ if self.browser is not None and self.profile is None:
267
318
  try:
268
- await self.client.stop()
319
+ self.profile = await asyncio.wait_for(browser_profile(self.browser, self.launch), timeout=8)
269
320
  except Exception:
270
- pass
321
+ self.profile = {}
322
+ # Nothing is sent to the page any more (the panel, a log line): it is going.
323
+ self.pages.clear()
324
+ self.frames.clear()
325
+ client, self.client = self.client, None
326
+ if client is not None:
327
+ with contextlib.suppress(Exception):
328
+ await client.stop()
329
+ started = time.monotonic()
271
330
  await _shutdown_browser_instance(self.browser)
331
+ logger.info("record: the browser closed %.1f s after the recording stopped", time.monotonic() - started)
332
+
333
+ async def close(self) -> None:
334
+ await self.release_browser()
335
+ await self._finish_video()
272
336
 
273
337
  # -- the loop -------------------------------------------------------------------------------------------------
274
338
 
@@ -345,13 +409,37 @@ class RecordSession:
345
409
  self._requests[str(event["requestId"])] = str((event.get("request") or {}).get("method") or "GET")
346
410
  elif kind == "response":
347
411
  self._response(event, sid)
412
+ elif kind == "dialog_open":
413
+ if len(self._asked) > 100:
414
+ self._asked.clear()
415
+ self._asked[sid or ""] = {"kind": str(event.get("type") or ""), "message": event.get("message")}
416
+ elif kind == "dialog_closed":
417
+ self._dialog_closed(event, sid)
348
418
  elif kind == "cmd":
349
419
  await self.command(event)
350
420
  except Exception as ex:
351
- logger.warning("record: %s not handled: %s", kind, ex)
352
- logger.debug("record: details", exc_info=True)
421
+ if "Session with given id not found" in str(ex) or "No target with given id" in str(ex):
422
+ # A frame or tab that closed before it was reached (an ad's frame, often): nothing to record there.
423
+ logger.debug("record: %s gone before it was reached: %s", kind, ex)
424
+ else:
425
+ logger.warning("record: %s not handled: %s", kind, ex)
426
+ logger.debug("record: details", exc_info=True)
353
427
  await self._follow_video()
354
428
 
429
+ def _dialog_closed(self, event: Dict[str, Any], sid: Optional[str]) -> None:
430
+ """The person answered a dialog of a tab or one of its frames: a step with what it asked and their answer."""
431
+ asked = self._asked.pop(sid or "", None)
432
+ rec = self.rec
433
+ tab = sid if sid in self.pages else (self.frames.get(sid or "") or {}).get("page")
434
+ if asked is None or rec is None or tab not in self.pages:
435
+ return
436
+ accept = event.get("result") is True
437
+ msg = rec.on_dialog(asked["kind"], asked["message"], accept, event.get("userInput") if accept else None)
438
+ logger.debug("record: a %s was answered %s", asked["kind"], "OK" if accept else "Cancel")
439
+ if msg:
440
+ self.active = tab
441
+ self._changed(msg)
442
+
355
443
  def _response(self, event: Dict[str, Any], sid: Optional[str]) -> None:
356
444
  method = self._requests.pop(str(event.get("requestId") or ""), None)
357
445
  rec = self.rec
@@ -443,6 +531,13 @@ class RecordSession:
443
531
  page["frame"] = frame.get("id") or page.get("frame")
444
532
  page["ctx"] = None
445
533
  url = str(frame.get("url") or "")
534
+ # A page loaded in the tab the video follows: Chrome drops a screencast when the tab moves to another
535
+ # process (the first page of a site, often), so it is asked for again.
536
+ if self.video is not None and sid == self._video_sid:
537
+ try:
538
+ await self.send("Page.startScreencast", dict(VIDEO_SCREENCAST), sid)
539
+ except Exception as ex:
540
+ logger.debug("record: no screencast of the page: %s", ex)
446
541
  how = await self._how(sid, page)
447
542
  renderer = page.pop("renderer", False)
448
543
  if page.pop("initial", False) or (page.get("opener") and not page.get("seen")):
@@ -525,7 +620,7 @@ class RecordSession:
525
620
  provider = named if named in {n for n, _ in CAPTCHA_FRAMES} else ""
526
621
  if not provider:
527
622
  return
528
- if provider and kind in ("click", "dblclick", "fill", "select", "press", "captcha"):
623
+ if provider and kind in ("click", "dblclick", "fill", "select", "press", "captcha", "drag"):
529
624
  msg = rec.on_captcha(provider)
530
625
  if msg:
531
626
  self._changed(msg)
@@ -553,6 +648,13 @@ class RecordSession:
553
648
  t = await target(data)
554
649
  hover = await target(data["hover"]) if isinstance(data.get("hover"), dict) else None
555
650
  msg = rec.on_click(t, hover=hover)
651
+ elif kind == "drag":
652
+ # An element moved: the one taken and, when it was let go on another, that one (each with a point in it).
653
+ if not isinstance(data.get("source"), dict):
654
+ return
655
+ src = await target(data["source"])
656
+ to = await target(data["target"]) if isinstance(data.get("target"), dict) else None
657
+ msg = rec.on_drag(src, to, drag_offset(data.get("offset")))
556
658
  elif kind == "dblclick":
557
659
  msg = rec.on_dblclick(await target(data))
558
660
  elif kind == "fill":
@@ -665,6 +767,11 @@ class RecordSession:
665
767
  # counted them at the event, so its count stands in for a check that never finished.
666
768
  if not (not any(l.get("verified") for l in live.locators) and any(l.get("verified") for l in fallback.locators)):
667
769
  target = live
770
+ # Hidden since the event (a list of results that closes on the click): a locator by its name or text
771
+ # finds nothing now, so only its place (XPath) checks out. The page script counted them while it showed.
772
+ if target is live and _best_kind(fallback) > _best_kind(live) and not await self._shows(sid, int(backend)):
773
+ logger.debug("record: the element is hidden since the event: its locators as the page script counted them")
774
+ target = fallback
668
775
  # None of its own locators unique: the one anchored on its container (the page script counted it), where there is one.
669
776
  anchored = within_locator(data.get("anchor"))
670
777
  if anchored and not any(l.get("verified") and l.get("matches") == 1 and l.get("type") in STRONG_ALONE for l in target.locators):
@@ -672,6 +779,17 @@ class RecordSession:
672
779
  target = Target(target.url, target.facts, locs, target.frames, closed_shadow=target.closed_shadow)
673
780
  return await self._steady(sid, target, data.get("matches") if isinstance(data.get("matches"), dict) else {}, ctx=ctx)
674
781
 
782
+ async def _shows(self, sid: str, backend: int) -> bool:
783
+ """Whether an element shows on the page now (it has a box); True when it cannot tell."""
784
+ try:
785
+ el = ((await self.send("DOM.resolveNode", {"backendNodeId": backend}, sid)).get("object") or {}).get("objectId")
786
+ if not el:
787
+ return True
788
+ r = await self.send("Runtime.callFunctionOn", {"objectId": el, "functionDeclaration": "function() { return this.getClientRects().length > 0; }", "returnByValue": True}, sid)
789
+ return (r.get("result") or {}).get("value") is not False
790
+ except Exception:
791
+ return True
792
+
675
793
  async def _in_closed_shadow(self, sid: str, backend: int) -> bool:
676
794
  """
677
795
  Whether an element is inside a shadow root the page asked for closed (open_shadow_js opened it): the hosts are
@@ -720,7 +838,8 @@ class RecordSession:
720
838
  if kind not in ("role", "text", "label", "title", "alt"):
721
839
  continue
722
840
  role, _, name = str(loc.get("value") or "").partition("|") if kind == "role" else ("", "", str(loc.get("value") or ""))
723
- if not dynamic.is_dynamic(name):
841
+ # A control named only by a time of day (a slot in a time picker: "15:00") is the same choice on every run.
842
+ if not dynamic.is_dynamic(name) or dynamic.time_of_day(name):
724
843
  continue
725
844
  loc.update(verified=False, live_data=True)
726
845
  loc["confidence"] = max(1, int((loc.get("confidence") or 30) * 0.3))
@@ -1323,10 +1442,12 @@ class RecordSession:
1323
1442
  ok = recorded > 0
1324
1443
  goal = self.name or auto_name(steps, self.start_url)
1325
1444
  summary = f"Recorded by hand: {rec.summary()}" if ok else "Nothing was recorded after opening the start page."
1326
- try:
1327
- profile = await browser_profile(self.browser, self.launch)
1328
- except Exception:
1329
- profile = {}
1445
+ profile = self.profile
1446
+ if profile is None:
1447
+ try:
1448
+ profile = await browser_profile(self.browser, self.launch)
1449
+ except Exception:
1450
+ profile = {}
1330
1451
  yaml_path, _ = save_browser_use_run_yaml(self.out_dir, goal, success=ok, summary=summary, session_id=None, compact_steps=steps, live_trace_source="recorded")
1331
1452
  params = [s["param"] for s in steps if s.get("param")]
1332
1453
  trace = ["### Task", "", goal, "", "---", "", "## Result", "", summary, "", *[f"{i + 1}. {describe(s)}" + (f" \n note: {s['note']}" if s.get("note") else "") for i, s in enumerate(steps)]]
@@ -1380,10 +1501,20 @@ def _count(loc: Dict[str, Any], counted: Dict[str, Any]) -> Optional[int]:
1380
1501
  n = attrs.get("id")
1381
1502
  elif kind in ("placeholder", "title", "alt"):
1382
1503
  n = attrs.get(kind)
1504
+ elif kind == "css" and counted.get("css_sel") is not None and counted.get("css_sel") != loc.get("css"):
1505
+ # Counted for another selector (a class the page script kept that ForgeQE leaves out): not this one's count.
1506
+ n = None
1383
1507
  elif kind in ("name", "href", "css", "text", "role", "label"):
1384
1508
  n = counted.get(kind)
1385
1509
  elif kind == "xpath":
1386
1510
  n = 1
1511
+ elif kind == "role_pattern" and isinstance(counted.get("role_names"), list):
1512
+ # By how a long name starts: counted in the names of the others with that role, sent at the event.
1513
+ try:
1514
+ rx = re.compile(str(loc.get("value") or "").partition("|")[2])
1515
+ except re.error:
1516
+ return None
1517
+ n = sum(1 for x in counted["role_names"][:400] if isinstance(x, str) and rx.search(x))
1387
1518
  else:
1388
1519
  n = None
1389
1520
  return n if isinstance(n, int) and n >= 0 else None
@@ -1419,6 +1550,15 @@ OPEN_SHADOW_JS = r"""(() => {
1419
1550
  })()"""
1420
1551
 
1421
1552
 
1553
+ def drag_offset(raw: Any) -> Optional[Dict[str, int]]:
1554
+ """How far a drag moved the pointer, as the page script reported it: two whole numbers within a page's size, else None."""
1555
+ if not isinstance(raw, dict):
1556
+ return None
1557
+ x, y = raw.get("x"), raw.get("y")
1558
+ ok = lambda v: isinstance(v, int) and not isinstance(v, bool) and -20000 <= v <= 20000 # noqa: E731
1559
+ return {"x": x, "y": y} if ok(x) and ok(y) and (x or y) else None
1560
+
1561
+
1422
1562
  def click_position(raw: Any) -> Optional[Dict[str, int]]:
1423
1563
  """Where in a canvas a click landed, as the page script reported it: two whole numbers within a page's size, else None."""
1424
1564
  if not isinstance(raw, dict):
@@ -1478,6 +1618,11 @@ def clean_frame(raw: Any) -> Dict[str, Any]:
1478
1618
  return out
1479
1619
 
1480
1620
 
1621
+ def _best_kind(t: Target) -> float:
1622
+ """How good a target's best checked locator is, by its kind (BASE): -1 when none is checked."""
1623
+ return max((BASE.get(str(l.get("type")), 0) for l in t.locators if l.get("verified")), default=-1)
1624
+
1625
+
1481
1626
  def fallback_target(url: str, facts: Dict[str, Any], counted: Optional[Dict[str, Any]] = None) -> Target:
1482
1627
  """
1483
1628
  A target from the facts the page script read, for an element the page took away before ForgeQE could look at it.
@@ -1490,7 +1635,7 @@ def fallback_target(url: str, facts: Dict[str, Any], counted: Optional[Dict[str,
1490
1635
  "name": " ".join(str(facts.get("name") or "").split())[:120],
1491
1636
  "text": " ".join(str(facts.get("text") or "").split())[:120],
1492
1637
  "attributes": {k: str(v) for k, v in (facts.get("attributes") or {}).items() if k in KEPT_ATTRS and v},
1493
- "classes": [c for c in facts.get("classes") or [] if isinstance(c, str) and not looks_generated(c)][:4],
1638
+ "classes": [c for c in facts.get("classes") or [] if isinstance(c, str) and not looks_generated(c) and not state_class(c)][:4],
1494
1639
  "xpath": str(facts.get("xpath") or ""),
1495
1640
  "stable_hash": None,
1496
1641
  }
@@ -1563,6 +1708,9 @@ async def record_web(payload: Dict[str, Any], emit: Emit, commands: asyncio.Queu
1563
1708
  else:
1564
1709
  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).")
1565
1710
  await s.run(float(payload.get("max_seconds") or MAX_SECONDS))
1711
+ # Stopped: the browser closes at once; the rest is saving.
1712
+ await s.release_browser()
1713
+ s.log("Recording stopped; the browser is closed. Saving it…")
1566
1714
  await s.review_values()
1567
1715
  s._render()
1568
1716
  return await s.finish()
@@ -38,6 +38,9 @@ NAV_CAUSED_SECONDS = 1.5
38
38
  DOUBLE_CLICK_SECONDS = 0.5
39
39
  MAX_TEXT = 200
40
40
  EXPECT_KINDS = ("text", "visible", "hidden", "value", "checked", "url", "title", "intent")
41
+ # Browser dialogs a step can answer (Page.javascriptDialogOpening's types); a dialog's message is kept one line, clipped.
42
+ DIALOG_KINDS = ("alert", "confirm", "prompt", "beforeunload")
43
+ MAX_DIALOG_MESSAGE = 300
41
44
  # Keys recorded inside a text field; any other key there is typing.
42
45
  FIELD_KEYS = ("Enter", "Escape")
43
46
  AUTOCOMPLETE_KEYS = ("ArrowDown", "ArrowUp")
@@ -283,6 +286,14 @@ def describe(step: Dict[str, Any]) -> str:
283
286
  return f"wait for {label}"
284
287
  if op == "captcha":
285
288
  return f"solve the {step.get('provider') or 'CAPTCHA'} (a person; a test turns it off)"
289
+ if op == "dialog":
290
+ return dialog_words(step)
291
+ if op == "drag":
292
+ to = step.get("to") if isinstance(step.get("to"), dict) else None
293
+ if to:
294
+ return f"drag {label} onto {to.get('label') or 'element'}"
295
+ off = step.get("offset") if isinstance(step.get("offset"), dict) else {}
296
+ return f"drag {label} by {off.get('x', 0)},{off.get('y', 0)}"
286
297
  if op == "upload":
287
298
  names = list(step.get("files") or []) + [os.path.basename(f) for f in step.get("run_files") or []]
288
299
  return f"{'drop' if step.get('drop') else 'upload'} {', '.join(names)} {'onto' if step.get('drop') else 'into'} {label}"
@@ -306,6 +317,26 @@ def describe(step: Dict[str, Any]) -> str:
306
317
  return op
307
318
 
308
319
 
320
+ def dialog_message(raw: Any) -> str:
321
+ """A dialog's message as a step keeps it: page text, one line, clipped (never markup or a command)."""
322
+ text = " ".join(str(raw or "").split())
323
+ return text if len(text) <= MAX_DIALOG_MESSAGE else text[: MAX_DIALOG_MESSAGE - 1] + "…"
324
+
325
+
326
+ def dialog_words(step: Dict[str, Any]) -> str:
327
+ """A dialog step in words: what the page asked and how it was answered."""
328
+ kind, ok = step.get("kind"), bool(step.get("accept"))
329
+ said = f" {step['message']!r}" if step.get("message") else ""
330
+ if kind == "beforeunload":
331
+ return "leave the page when it asks" if ok else "stay on the page when it asks"
332
+ if kind == "alert":
333
+ return f"close the alert{said}"
334
+ if kind == "prompt" and ok:
335
+ given = f"${step['text_env']}" if step.get("text_env") else repr(step.get("text") or "")
336
+ return f"answer the prompt{said} with {given}"
337
+ return f"answer the {kind}{said} with {'OK' if ok else 'Cancel'}"
338
+
339
+
309
340
  @dataclass
310
341
  class WebRecorder:
311
342
  start_url: str
@@ -389,6 +420,49 @@ class WebRecorder:
389
420
  self._add({"op": "captcha", "provider": provider, "page": page_id(self.url) or self.url})
390
421
  return describe(self.steps[-1])
391
422
 
423
+ def on_dialog(self, kind: str, message: Any, accept: bool, text: Any = None) -> Optional[str]:
424
+ """
425
+ A browser dialog the page showed (an alert, a confirm, a prompt, or "leave this page?") and how the person answered
426
+ it: OK or Cancel, and a prompt's typed text. The step comes after the one that made the page ask; a replay answers
427
+ the dialog the same way when that step runs. Its message is page text: kept as data, one line.
428
+ """
429
+ if self.paused or kind not in DIALOG_KINDS:
430
+ return None
431
+ self._last_action = self.clock()
432
+ self._last_click = None
433
+ step: Dict[str, Any] = {"op": "dialog", "kind": kind, "message": dialog_message(message), "accept": bool(accept), "page": page_id(self.url) or self.url}
434
+ if kind == "prompt" and accept:
435
+ value = _clip(" ".join(str(text or "").split()))
436
+ env = next((k for k, v in self.login_values.items() if v and value == v), None)
437
+ if env:
438
+ step.update(text="", text_env=env)
439
+ else:
440
+ var = next((k for k, v in self.variables.items() if v and value == v), None)
441
+ step["text"] = "{{%s}}" % var if var else value
442
+ self._add(step)
443
+ return describe(step)
444
+
445
+ def on_drag(self, t: Target, to: Optional[Target], offset: Optional[Dict[str, int]]) -> Optional[str]:
446
+ """
447
+ An element the tester dragged: `t` the one taken (its position the point it was taken by), `to` the one it was let
448
+ go on (with the point), none when that is the same element (a slider's thumb, a pin that moves with the pointer),
449
+ and `offset` how far the pointer moved. A replay drags it with the mouse onto `to`, or by `offset`.
450
+ """
451
+ if self.paused:
452
+ return None
453
+ self._last_action = self.clock()
454
+ self._last_click = None
455
+ step = element_step("drag", t)
456
+ if to is not None and not _same_element(t, to):
457
+ dst = element_step("drag", to)
458
+ step["to"] = {k: dst[k] for k in ("label", "best_locator", "position", "shadow", "locators", "locator", "frame", "frames") if dst.get(k)}
459
+ if offset:
460
+ step["offset"] = dict(offset)
461
+ if "to" not in step and "offset" not in step:
462
+ return None
463
+ self._add(step)
464
+ return describe(step)
465
+
392
466
  def on_dblclick(self, t: Target) -> Optional[str]:
393
467
  """The browser's own double-click event: the two clicks before it on the element become one double-click."""
394
468
  if self.paused:
@@ -738,6 +812,12 @@ def _name_hint(facts: Dict[str, Any]) -> str:
738
812
  return str(facts.get("name") or "") if facts.get("tag") in ("input", "select", "textarea") else ""
739
813
 
740
814
 
815
+ def _same_element(a: Target, b: Target) -> bool:
816
+ """Whether two targets are the same element: the same page, frames and best locator (wherever in it)."""
817
+ best = lambda t: (t.locators[0].get("type"), t.locators[0].get("value")) if t.locators else (None, None) # noqa: E731
818
+ return (a.url, a.frames, best(a)) == (b.url, b.frames, best(b))
819
+
820
+
741
821
  def _same(step: Dict[str, Any], t: Target) -> bool:
742
822
  """Whether a recorded step acted on target `t`: the same page and the same best locator."""
743
823
  locs = step.get("locators") or []