@capagents/forgeqe 2.9.8 → 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 (111) hide show
  1. package/HOW_TO_USE.md +90 -33
  2. package/dist/docs-site/docs/index.html +53 -4
  3. package/dist/docs-site/docs/search.js +1 -1
  4. package/dist/forgeqe.js +2042 -1892
  5. package/dist/web/assets/Agent-B_mG1pww.js +8 -0
  6. package/dist/web/assets/ApiTests-C2QIp_tG.js +10 -0
  7. package/dist/web/assets/Browse-zQoOQXpA.js +2 -0
  8. package/dist/web/assets/{Chat-DSlBwNAI.js → Chat-BtLEKYY8.js} +3 -3
  9. package/dist/web/assets/CommandPalette-BgQORiKD.js +1 -0
  10. package/dist/web/assets/{Compare-BI8IMq49.js → Compare-DQNg3ldO.js} +1 -1
  11. package/dist/web/assets/Cost-T0NH8ymc.js +1 -0
  12. package/dist/web/assets/{Data-CjnqjcAx.js → Data-CqKsrslC.js} +4 -4
  13. package/dist/web/assets/Desktop-CgDXi3lX.js +1 -0
  14. package/dist/web/assets/DesktopReview-C-gW_gli.js +1 -0
  15. package/dist/web/assets/Evidence-1pipN6K6.js +1 -0
  16. package/dist/web/assets/{Explore-Cc-1cTwG.js → Explore-lG_kobPj.js} +2 -2
  17. package/dist/web/assets/Features-BIrW3AiQ.js +1 -0
  18. package/dist/web/assets/{Flags-CICcBCkH.js → Flags-sG1vr7NU.js} +2 -2
  19. package/dist/web/assets/Flaky-ChKBXlcW.js +1 -0
  20. package/dist/web/assets/Impact-D5a5fyc2.js +3 -0
  21. package/dist/web/assets/Jobs-B52pIZUx.js +5 -0
  22. package/dist/web/assets/KindPage-BFoKPj7l.js +6 -0
  23. package/dist/web/assets/Migration-DbuzD_s4.js +2 -0
  24. package/dist/web/assets/Product-DiH61j0X.js +7 -0
  25. package/dist/web/assets/Production-8h5LixDt.js +1 -0
  26. package/dist/web/assets/Quality-CI5n8b_k.js +1 -0
  27. package/dist/web/assets/Readiness-D4n4HSlW.js +1 -0
  28. package/dist/web/assets/Record-O8LOzHLo.js +2 -0
  29. package/dist/web/assets/Regression-DbShD6ji.js +5 -0
  30. package/dist/web/assets/RelationGraph-D_ZVeOBh.js +1 -0
  31. package/dist/web/assets/Reports-IdoUvtaW.js +2 -0
  32. package/dist/web/assets/{Response-CaWPiZyx.js → Response-BRVM9mW_.js} +2 -2
  33. package/dist/web/assets/{RunDiff-BQKwTCbM.js → RunDiff-uQoK3Q6q.js} +1 -1
  34. package/dist/web/assets/Runs-BhDgzDo4.js +2 -0
  35. package/dist/web/assets/Steps-BDSeIznj.js +2 -0
  36. package/dist/web/assets/TestCases-DQ2oWXt2.js +1 -0
  37. package/dist/web/assets/TestData-D-ZdmHVa.js +2 -0
  38. package/dist/web/assets/TestDebt-_jer4Dmy.js +1 -0
  39. package/dist/web/assets/Tosca-DOT6-53c.js +3 -0
  40. package/dist/web/assets/{WhatsNew-CznfTEFM.js → WhatsNew-DU5k6dz6.js} +1 -1
  41. package/dist/web/assets/dataParts-BzuL6pAo.js +3 -0
  42. package/dist/web/assets/{families-B0QIuAe3.js → families-zlLgApNV.js} +1 -1
  43. package/dist/web/assets/filters-CflRmNDz.js +1 -0
  44. package/dist/web/assets/flowLayout-cXVJhLpH.js +1 -0
  45. package/dist/web/assets/{fold-HnodvJWj.js → fold-DZYvcIP0.js} +1 -1
  46. package/dist/web/assets/frame-Bjxy1jvq.js +4 -0
  47. package/dist/web/assets/index-DH21lIE7.js +66 -0
  48. package/dist/web/assets/index-DwUumNPZ.css +2 -0
  49. package/dist/web/assets/{logos-CNarWSPL.js → logos-Co26FM0G.js} +1 -1
  50. package/dist/web/assets/markdown-nTIj9lyp.js +10 -0
  51. package/dist/web/assets/{palette-B2YywN1k.js → palette-CitkMCod.js} +1 -1
  52. package/dist/web/assets/{parts-z_AE9U-M.js → parts-C53RxMcR.js} +1 -1
  53. package/dist/web/assets/{productParts-C4vc_bLJ.js → productParts-DK3ULNpv.js} +1 -1
  54. package/dist/web/assets/qualityParts-DADI5Fqn.js +1 -0
  55. package/dist/web/assets/{recordTest-GvGQjhR4.js → recordTest-CqxnF953.js} +1 -1
  56. package/dist/web/assets/{rows-7zDrF-Yp.js → rows-BqT7fknl.js} +1 -1
  57. package/dist/web/assets/{segmented-DANusepM.js → segmented-CAf_qz5Z.js} +1 -1
  58. package/dist/web/assets/{thread-BUBgX0xW.js → thread-iRsceqhM.js} +2 -2
  59. package/dist/web/assets/{usePageChat-DnOXyd_B.js → usePageChat-BCrPoTyS.js} +1 -1
  60. package/dist/web/index.html +5 -4
  61. package/docs/BUSINESS_ASSURANCE.md +105 -0
  62. package/docs/user-guide.html +53 -4
  63. package/package.json +1 -1
  64. package/prompts/README.md +3 -0
  65. package/prompts/brain.md +11 -0
  66. package/prompts/business-interview.md +43 -0
  67. package/prompts/business-persona.md +3 -1
  68. package/prompts/business-strategist.md +44 -0
  69. package/prompts/persona-own.md +47 -0
  70. package/py/forgeqe_engine/browser.py +29 -0
  71. package/py/forgeqe_engine/capture.py +2 -2
  72. package/py/forgeqe_engine/cli.py +5 -0
  73. package/py/forgeqe_engine/dynamic.py +8 -0
  74. package/py/forgeqe_engine/memory.py +33 -2
  75. package/py/forgeqe_engine/recordsession.py +301 -28
  76. package/py/forgeqe_engine/webrecord.py +80 -0
  77. package/py/forgeqe_engine/webrecord_page.py +136 -17
  78. package/dist/web/assets/Agent-D0jovbz1.js +0 -6
  79. package/dist/web/assets/ApiTests-CMMMApBR.js +0 -10
  80. package/dist/web/assets/Browse-Bimy9-t0.js +0 -2
  81. package/dist/web/assets/CommandPalette-D7NWAtOU.js +0 -1
  82. package/dist/web/assets/Cost-BV0JavsG.js +0 -1
  83. package/dist/web/assets/Desktop-Bu72INy4.js +0 -1
  84. package/dist/web/assets/DesktopReview-jDnb5Gfn.js +0 -1
  85. package/dist/web/assets/Evidence-CIlcAy5n.js +0 -1
  86. package/dist/web/assets/Features-CewFSOSI.js +0 -1
  87. package/dist/web/assets/Flaky-BrWbRajc.js +0 -1
  88. package/dist/web/assets/ForceGraph-BLYMwmyj.js +0 -1
  89. package/dist/web/assets/Impact-D7seby-G.js +0 -3
  90. package/dist/web/assets/Jobs-D7yPretO.js +0 -5
  91. package/dist/web/assets/KindPage-Cjt1s7Vd.js +0 -6
  92. package/dist/web/assets/Migration-CbCqOsJI.js +0 -2
  93. package/dist/web/assets/Product-CxXVrpoD.js +0 -7
  94. package/dist/web/assets/Production-D5jIe328.js +0 -1
  95. package/dist/web/assets/Quality-D3G8IKLZ.js +0 -1
  96. package/dist/web/assets/Readiness-B4Fy4Vln.js +0 -1
  97. package/dist/web/assets/Record-DLfODYjy.js +0 -2
  98. package/dist/web/assets/Regression-Daoc9Qvx.js +0 -5
  99. package/dist/web/assets/Reports-DEzDDoGF.js +0 -2
  100. package/dist/web/assets/Runs-BIUnN08h.js +0 -2
  101. package/dist/web/assets/Steps-DjR_K32c.js +0 -2
  102. package/dist/web/assets/TestCases-BZWiTLjC.js +0 -1
  103. package/dist/web/assets/TestData-D6YiouU4.js +0 -2
  104. package/dist/web/assets/TestDebt-COFagfQU.js +0 -1
  105. package/dist/web/assets/Tosca-B3sZ9uqe.js +0 -3
  106. package/dist/web/assets/dataParts-DpVitZdm.js +0 -3
  107. package/dist/web/assets/filters-mFECJpMB.js +0 -1
  108. package/dist/web/assets/frame-DiKY0GWx.js +0 -4
  109. package/dist/web/assets/index-HjX2EOmp.js +0 -75
  110. package/dist/web/assets/index-VgSzQGK8.css +0 -2
  111. package/dist/web/assets/qualityParts-jsPhayON.js +0 -1
@@ -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
@@ -55,31 +59,45 @@ VIDEO_SCREENCAST = {"format": "jpeg", "quality": 60, "maxWidth": 1920, "maxHeigh
55
59
  # What the page shows after a step, for the review to suggest checks from and to pick an element on the screenshot:
56
60
  # the address and title, the visible text (a leaf's own words, with its box) and the fields with their values, in the
57
61
  # viewport's coordinates. A password field's value is never read; the Recorder panel (forgeqe-recorder) is left out.
58
- SNAPSHOT_JS = r"""(() => {
59
- const vw = innerWidth, vh = innerHeight, out = { url: location.origin + location.pathname, title: document.title, w: vw, h: vh, texts: [], fields: [] };
62
+ # What the page showed after a step, for the review to pick a check from: its texts and labelled fields with their boxes in
63
+ # the screenshot's pixels. Run in the page and in each of its frames: (dx, dy) is where that frame's viewport is on the
64
+ # screenshot, f its index in the snapshot's frames, (VW, VH) the screenshot's size. Open shadow roots are read too (a
65
+ # closed one the page asked for is open while recording); a box inside one is marked `sh`.
66
+ SNAPSHOT_FN = r"""function (dx, dy, f, VW, VH) {
67
+ const vw = innerWidth, vh = innerHeight, top = f === null;
68
+ const out = top ? { url: location.origin + location.pathname, title: document.title, w: vw, h: vh, texts: [], fields: [] } : { texts: [], fields: [] };
60
69
  const seen = (el) => { const r = el.getBoundingClientRect(); if (r.width < 2 || r.height < 2 || r.bottom < 0 || r.right < 0 || r.top > vh || r.left > vw) return null;
70
+ const x = r.left + dx, y = r.top + dy; if (x + r.width < 0 || y + r.height < 0 || x > VW || y > VH) return null;
61
71
  const cs = getComputedStyle(el); if (cs.visibility === 'hidden' || cs.display === 'none' || +cs.opacity === 0) return null;
62
- return { x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height) }; };
72
+ return { x: Math.round(x), y: Math.round(y), w: Math.round(r.width), h: Math.round(r.height) }; };
73
+ const where = (el, o) => { if (!top) o.f = f; if (el.getRootNode() !== document) o.sh = 1; return o; };
63
74
  const own = (el) => [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join(' ').replace(/\s+/g, ' ').trim();
64
75
  const skip = (el) => el.closest('forgeqe-recorder,script,style,noscript,svg,template');
65
- for (const el of document.body ? document.body.querySelectorAll('*') : []) {
76
+ const roots = [document];
77
+ for (let i = 0; i < roots.length && roots.length < 300; i++) for (const x of roots[i].querySelectorAll('*')) if (x.shadowRoot) roots.push(x.shadowRoot);
78
+ const all = (sel) => roots.flatMap((r) => [...(r === document ? (document.body ? document.body.querySelectorAll(sel) : []) : r.querySelectorAll(sel))]);
79
+ for (const el of all('*')) {
66
80
  if (out.texts.length >= 200) break;
67
81
  if (skip(el) || /^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(el.tagName)) continue;
68
82
  const t = own(el); if (t.length < 2 || t.length > 160) continue;
69
83
  const box = seen(el); if (!box) continue;
70
- out.texts.push({ t, tag: el.tagName.toLowerCase(), role: el.getAttribute('role') || '', ...box });
84
+ out.texts.push(where(el, { t, tag: el.tagName.toLowerCase(), role: el.getAttribute('role') || '', ...box }));
71
85
  }
72
- for (const el of document.querySelectorAll('input,textarea,select')) {
86
+ for (const el of all('input,textarea,select')) {
73
87
  if (out.fields.length >= 60 || skip(el)) continue;
74
88
  const type = (el.getAttribute('type') || el.tagName).toLowerCase();
75
89
  if (/^(hidden|submit|button|image|reset|file)$/.test(type)) continue;
76
90
  const box = seen(el); if (!box) continue;
77
91
  const label = (el.getAttribute('aria-label') || (el.labels && el.labels[0] && el.labels[0].innerText) || el.getAttribute('placeholder') || el.name || '').replace(/\s+/g, ' ').trim().slice(0, 80);
78
92
  const value = type === 'password' ? '' : (type === 'checkbox' || type === 'radio') ? (el.checked ? 'checked' : 'not checked') : el.tagName === 'SELECT' ? (el.selectedOptions[0] ? el.selectedOptions[0].text : '') : String(el.value || '');
79
- out.fields.push({ label, value: value.slice(0, 120), type, ...box });
93
+ out.fields.push(where(el, { label, value: value.slice(0, 120), type, ...box }));
80
94
  }
81
95
  return out;
82
- })()"""
96
+ }"""
97
+ SNAPSHOT_JS = f"({SNAPSHOT_FN})(0, 0, null, innerWidth, innerHeight)"
98
+ # A snapshot keeps at most this many texts and fields, the page's and its frames' together.
99
+ MAX_SNAP_TEXTS = 200
100
+ MAX_SNAP_FIELDS = 60
83
101
  MAX_SECONDS = 4 * 3600
84
102
  DEFAULT_LEADER = {"code": "Space", "ctrl": True, "shift": True, "alt": False, "meta": False}
85
103
  MAX_PAGE_TEXT = 8000
@@ -156,6 +174,13 @@ class RecordSession:
156
174
  # The page's own API calls after each step (method, path, status), for checks of them in the review.
157
175
  self.calls: Dict[int, List[Dict[str, Any]]] = {}
158
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]] = {}
159
184
  # video.mp4 of the tab being recorded (payload ``video``), following the tester from tab to tab; paused with them.
160
185
  self.video: Any = None
161
186
  self._video_sid: Optional[str] = None
@@ -163,12 +188,39 @@ class RecordSession:
163
188
  # -- the browser ----------------------------------------------------------------------------------------------
164
189
 
165
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")
166
193
  domain, name = method.split(".", 1)
167
194
  fn = getattr(getattr(self.client.send, domain), name)
168
195
  kw: Dict[str, Any] = {"params": params} if params is not None else {}
169
196
  if sid:
170
197
  kw["session_id"] = sid
171
- 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
172
224
 
173
225
  def _queue(self, kind: str) -> Callable[[Any, Optional[str]], None]:
174
226
  def handler(event: Any, session_id: Optional[str] = None) -> None:
@@ -181,7 +233,7 @@ class RecordSession:
181
233
  from cdp_use.client import CDPClient
182
234
 
183
235
  from . import brand
184
- 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
185
237
  from .logins import load_sessions, parse_logins, text_envs, use_logins
186
238
 
187
239
  logins = parse_logins(self.payload.get("logins"))
@@ -195,7 +247,7 @@ class RecordSession:
195
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"))]
196
248
  self.browser, self.launch = await start_local_browser(
197
249
  candidates,
198
- make=lambda kw: Browser(**kw),
250
+ make=lambda kw: leave_dialogs(Browser(**kw)),
199
251
  on_fallback=lambda failed, nxt, reason: self.log(f"{browser_name(failed)} did not start ({reason}); trying {browser_name(nxt)}", "warn"),
200
252
  )
201
253
  self.client = CDPClient(self.browser.cdp_url)
@@ -208,6 +260,8 @@ class RecordSession:
208
260
  reg.Page.frameNavigated(self._queue("navigated"))
209
261
  reg.Page.navigatedWithinDocument(self._queue("navigated_same"))
210
262
  reg.Page.frameRequestedNavigation(self._queue("requested"))
263
+ reg.Page.javascriptDialogOpening(self._dialog("dialog_open"))
264
+ reg.Page.javascriptDialogClosed(self._dialog("dialog_closed"))
211
265
  reg.Network.requestWillBeSent(self._queue("request"))
212
266
  reg.Network.responseReceived(self._queue("response"))
213
267
  await self.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True})
@@ -245,16 +299,40 @@ class RecordSession:
245
299
  if str(getattr(self.browser, "cdp_url", "") or "").startswith(("http://127.0.0.1:", "ws://127.0.0.1:", "http://localhost:", "ws://localhost:")):
246
300
  self.emit({"type": "browser", "cdp": self.browser.cdp_url})
247
301
 
248
- async def close(self) -> None:
249
- 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
250
309
 
251
- await self._finish_video()
252
- 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:
253
318
  try:
254
- await self.client.stop()
319
+ self.profile = await asyncio.wait_for(browser_profile(self.browser, self.launch), timeout=8)
255
320
  except Exception:
256
- 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()
257
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()
258
336
 
259
337
  # -- the loop -------------------------------------------------------------------------------------------------
260
338
 
@@ -331,13 +409,37 @@ class RecordSession:
331
409
  self._requests[str(event["requestId"])] = str((event.get("request") or {}).get("method") or "GET")
332
410
  elif kind == "response":
333
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)
334
418
  elif kind == "cmd":
335
419
  await self.command(event)
336
420
  except Exception as ex:
337
- logger.warning("record: %s not handled: %s", kind, ex)
338
- 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)
339
427
  await self._follow_video()
340
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
+
341
443
  def _response(self, event: Dict[str, Any], sid: Optional[str]) -> None:
342
444
  method = self._requests.pop(str(event.get("requestId") or ""), None)
343
445
  rec = self.rec
@@ -429,6 +531,13 @@ class RecordSession:
429
531
  page["frame"] = frame.get("id") or page.get("frame")
430
532
  page["ctx"] = None
431
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)
432
541
  how = await self._how(sid, page)
433
542
  renderer = page.pop("renderer", False)
434
543
  if page.pop("initial", False) or (page.get("opener") and not page.get("seen")):
@@ -511,14 +620,23 @@ class RecordSession:
511
620
  provider = named if named in {n for n, _ in CAPTCHA_FRAMES} else ""
512
621
  if not provider:
513
622
  return
514
- if provider and kind in ("click", "dblclick", "fill", "select", "press", "captcha"):
623
+ if provider and kind in ("click", "dblclick", "fill", "select", "press", "captcha", "drag"):
515
624
  msg = rec.on_captcha(provider)
516
625
  if msg:
517
626
  self._changed(msg)
518
627
  return
519
628
 
629
+ logger.debug("record: %s%s%s", kind, " in a frame" if framed else "", f" ({len(chain)} deep)" if chain else "")
630
+
520
631
  async def target(d: Dict[str, Any]) -> Target:
521
632
  t = await self._target(sid, d, ctx=ctx)
633
+ best = t.locators[0] if t.locators else {}
634
+ logger.debug(
635
+ "record: %s <%s> best %s=%r (%s)%s",
636
+ kind, t.facts.get("tag") or "?", best.get("type"), str(best.get("value") or "")[:120],
637
+ "unique" if best.get("verified") else f"{best.get('matches', '?')} matches",
638
+ f", {len(t.locators)} locators" + (", closed shadow root" if t.closed_shadow else "") + (", anchored" if any(l.get("type") == "within" for l in t.locators) else ""),
639
+ )
522
640
  # A frame's element belongs to the page the tab shows; the frames say where in it.
523
641
  if framed:
524
642
  t = Target(rec.url or t.url, t.facts, t.locators, chain, closed_shadow=t.closed_shadow)
@@ -530,6 +648,13 @@ class RecordSession:
530
648
  t = await target(data)
531
649
  hover = await target(data["hover"]) if isinstance(data.get("hover"), dict) else None
532
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")))
533
658
  elif kind == "dblclick":
534
659
  msg = rec.on_dblclick(await target(data))
535
660
  elif kind == "fill":
@@ -642,6 +767,11 @@ class RecordSession:
642
767
  # counted them at the event, so its count stands in for a check that never finished.
643
768
  if not (not any(l.get("verified") for l in live.locators) and any(l.get("verified") for l in fallback.locators)):
644
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
645
775
  # None of its own locators unique: the one anchored on its container (the page script counted it), where there is one.
646
776
  anchored = within_locator(data.get("anchor"))
647
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):
@@ -649,6 +779,17 @@ class RecordSession:
649
779
  target = Target(target.url, target.facts, locs, target.frames, closed_shadow=target.closed_shadow)
650
780
  return await self._steady(sid, target, data.get("matches") if isinstance(data.get("matches"), dict) else {}, ctx=ctx)
651
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
+
652
793
  async def _in_closed_shadow(self, sid: str, backend: int) -> bool:
653
794
  """
654
795
  Whether an element is inside a shadow root the page asked for closed (open_shadow_js opened it): the hosts are
@@ -697,7 +838,8 @@ class RecordSession:
697
838
  if kind not in ("role", "text", "label", "title", "alt"):
698
839
  continue
699
840
  role, _, name = str(loc.get("value") or "").partition("|") if kind == "role" else ("", "", str(loc.get("value") or ""))
700
- 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):
701
843
  continue
702
844
  loc.update(verified=False, live_data=True)
703
845
  loc["confidence"] = max(1, int((loc.get("confidence") or 30) * 0.3))
@@ -1097,6 +1239,7 @@ class RecordSession:
1097
1239
  if ctx:
1098
1240
  res = await self.send("Runtime.evaluate", {"expression": SNAPSHOT_JS, "contextId": ctx, "returnByValue": True}, sid)
1099
1241
  snap = ((res.get("result") or {}).get("value")) or {}
1242
+ await self._snap_frames(sid, snap)
1100
1243
  except Exception as ex:
1101
1244
  logger.debug("record: no picture of the page: %s", ex)
1102
1245
  return None
@@ -1113,6 +1256,106 @@ class RecordSession:
1113
1256
  self.shot_at[len(rec.steps) - 1] = name
1114
1257
  return name
1115
1258
 
1259
+ async def _snap_frames(self, tab: str, snap: Dict[str, Any]) -> None:
1260
+ """
1261
+ The texts and fields of each frame of the tab, added to its snapshot where they show on the screenshot: each box
1262
+ moved by its frame's place on the screen (frame_offset) and naming its frame (an index into snap["frames"], each
1263
+ the frames on the way, outermost first, as a step keeps them). A CAPTCHA's frame is left out.
1264
+ """
1265
+ if not isinstance(snap, dict) or not isinstance(snap.get("texts"), list):
1266
+ return
1267
+ vw, vh = int(snap.get("w") or 0), int(snap.get("h") or 0)
1268
+ if vw <= 0 or vh <= 0:
1269
+ return
1270
+ frames: List[List[Dict[str, Any]]] = []
1271
+ if self.closed_count(await self._shadow_closure(tab)) > 0:
1272
+ # A box inside a shadow root may be in one the page asked for closed: a check there opens them, as a step does.
1273
+ snap["closed"] = True
1274
+ for s, c in self._frame_contexts(tab)[:20]:
1275
+ if len(snap["texts"]) >= MAX_SNAP_TEXTS and len(snap.get("fields") or []) >= MAX_SNAP_FIELDS:
1276
+ break
1277
+ try:
1278
+ chain = await self.frame_chain(s, c)
1279
+ if not chain or captcha_of(chain):
1280
+ continue
1281
+ at = await self.frame_offset(s, c)
1282
+ if at is None:
1283
+ continue
1284
+ expr = f"({SNAPSHOT_FN})({at[0]}, {at[1]}, {len(frames)}, {vw}, {vh})"
1285
+ res = await self.send("Runtime.evaluate", {"expression": expr, "contextId": c, "returnByValue": True}, s)
1286
+ got = (res.get("result") or {}).get("value") or {}
1287
+ except Exception as ex:
1288
+ logger.debug("record: a frame's texts were not read: %s", ex)
1289
+ continue
1290
+ texts = [b for b in got.get("texts") or [] if isinstance(b, dict)]
1291
+ fields = [b for b in got.get("fields") or [] if isinstance(b, dict)]
1292
+ if not texts and not fields:
1293
+ continue
1294
+ frames.append(chain)
1295
+ snap["texts"].extend(texts[: max(0, MAX_SNAP_TEXTS - len(snap["texts"]))])
1296
+ snap.setdefault("fields", []).extend(fields[: max(0, MAX_SNAP_FIELDS - len(snap["fields"]))])
1297
+ if frames:
1298
+ snap["frames"] = frames
1299
+
1300
+ async def frame_offset(self, sid: str, ctx: int) -> Optional[Tuple[int, int]]:
1301
+ """
1302
+ Where a frame's viewport is on the tab's screenshot: the content box of each <iframe> on the way. A box Chrome gives
1303
+ is on its own target's viewport, which already counts the frames above it in that target, so one is added for
1304
+ each target crossed (a cross-origin frame's); None when a frame's place cannot be read.
1305
+ """
1306
+ fid = self.contexts.get((sid, ctx))
1307
+ x = y = 0.0
1308
+ cur, counted = sid, False
1309
+ for _ in range(MAX_FRAME_DEPTH * 2):
1310
+ if not fid:
1311
+ return None
1312
+ tree = (await self.send("Page.getFrameTree", None, cur)).get("frameTree") or {}
1313
+ parent = _frame_parent(tree, fid)
1314
+ at = cur
1315
+ if parent is None and cur in self.frames:
1316
+ parent = str((tree.get("frame") or {}).get("parentId") or "") if str((tree.get("frame") or {}).get("id") or "") == fid else None
1317
+ at = self.frames[cur]["parent"]
1318
+ counted = False
1319
+ if not parent:
1320
+ return (round(x), round(y))
1321
+ if not counted:
1322
+ owner = await self.send("DOM.getFrameOwner", {"frameId": fid}, at)
1323
+ box = await self.send("DOM.getBoxModel", {"backendNodeId": int(owner.get("backendNodeId") or 0)}, at)
1324
+ quad = ((box.get("model") or {}).get("content")) or []
1325
+ if len(quad) < 2:
1326
+ return None
1327
+ x, y = x + float(quad[0]), y + float(quad[1])
1328
+ counted = True
1329
+ fid, cur = parent, at
1330
+ return None
1331
+
1332
+ async def _shadow_closure(self, sid: str) -> Dict[str, Any]:
1333
+ """The variables of open_shadow_js's closure in the tab's page (its key, the closed hosts, how many), read through the protocol."""
1334
+ try:
1335
+ fn = ((await self.send("Runtime.evaluate", {"expression": "Element.prototype.attachShadow"}, sid)).get("result") or {}).get("objectId")
1336
+ if not fn:
1337
+ return {}
1338
+ props = await self.send("Runtime.getProperties", {"objectId": fn, "ownProperties": False}, sid)
1339
+ scopes = next((p["value"].get("objectId") for p in props.get("internalProperties") or [] if p.get("name") == "[[Scopes]]" and p.get("value")), None)
1340
+ if not scopes:
1341
+ return {}
1342
+ for scope in (await self.send("Runtime.getProperties", {"objectId": scopes, "ownProperties": True}, sid)).get("result") or []:
1343
+ obj = (scope.get("value") or {}).get("objectId")
1344
+ if not obj:
1345
+ continue
1346
+ names = {v.get("name"): v.get("value") or {} for v in (await self.send("Runtime.getProperties", {"objectId": obj, "ownProperties": True}, sid)).get("result") or []}
1347
+ if (names.get("KEY") or {}).get("value") == self.shadow_key:
1348
+ return names
1349
+ except Exception as ex:
1350
+ logger.debug("record: the shadow closure was not read: %s", ex)
1351
+ return {}
1352
+
1353
+ @staticmethod
1354
+ def closed_count(names: Dict[str, Any]) -> int:
1355
+ """How many shadow roots the page asked for closed (open_shadow_js counts them)."""
1356
+ v = (names.get("count") or {}).get("value")
1357
+ return v if isinstance(v, int) and not isinstance(v, bool) else 0
1358
+
1116
1359
  # -- the video -------------------------------------------------------------------------------------------------------
1117
1360
 
1118
1361
  async def _start_video(self) -> None:
@@ -1199,10 +1442,12 @@ class RecordSession:
1199
1442
  ok = recorded > 0
1200
1443
  goal = self.name or auto_name(steps, self.start_url)
1201
1444
  summary = f"Recorded by hand: {rec.summary()}" if ok else "Nothing was recorded after opening the start page."
1202
- try:
1203
- profile = await browser_profile(self.browser, self.launch)
1204
- except Exception:
1205
- 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 = {}
1206
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")
1207
1452
  params = [s["param"] for s in steps if s.get("param")]
1208
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)]]
@@ -1256,10 +1501,20 @@ def _count(loc: Dict[str, Any], counted: Dict[str, Any]) -> Optional[int]:
1256
1501
  n = attrs.get("id")
1257
1502
  elif kind in ("placeholder", "title", "alt"):
1258
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
1259
1507
  elif kind in ("name", "href", "css", "text", "role", "label"):
1260
1508
  n = counted.get(kind)
1261
1509
  elif kind == "xpath":
1262
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))
1263
1518
  else:
1264
1519
  n = None
1265
1520
  return n if isinstance(n, int) and n >= 0 else None
@@ -1285,15 +1540,25 @@ OPEN_SHADOW_JS = r"""(() => {
1285
1540
  // through the DevTools protocol (RecordSession._in_closed_shadow), with KEY to know it is its own.
1286
1541
  const KEY = __KEY__;
1287
1542
  const closed = new WeakSet();
1543
+ let count = 0;
1288
1544
  const attach = Element.prototype.attachShadow;
1289
1545
  Element.prototype.attachShadow = function attachShadow(init) {
1290
1546
  const root = attach.call(this, Object.assign({}, init, { mode: 'open' }));
1291
- if (init && init.mode === 'closed' && KEY) closed.add(this);
1547
+ if (init && init.mode === 'closed' && KEY) { closed.add(this); count++; }
1292
1548
  return root;
1293
1549
  };
1294
1550
  })()"""
1295
1551
 
1296
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
+
1297
1562
  def click_position(raw: Any) -> Optional[Dict[str, int]]:
1298
1563
  """Where in a canvas a click landed, as the page script reported it: two whole numbers within a page's size, else None."""
1299
1564
  if not isinstance(raw, dict):
@@ -1353,6 +1618,11 @@ def clean_frame(raw: Any) -> Dict[str, Any]:
1353
1618
  return out
1354
1619
 
1355
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
+
1356
1626
  def fallback_target(url: str, facts: Dict[str, Any], counted: Optional[Dict[str, Any]] = None) -> Target:
1357
1627
  """
1358
1628
  A target from the facts the page script read, for an element the page took away before ForgeQE could look at it.
@@ -1365,7 +1635,7 @@ def fallback_target(url: str, facts: Dict[str, Any], counted: Optional[Dict[str,
1365
1635
  "name": " ".join(str(facts.get("name") or "").split())[:120],
1366
1636
  "text": " ".join(str(facts.get("text") or "").split())[:120],
1367
1637
  "attributes": {k: str(v) for k, v in (facts.get("attributes") or {}).items() if k in KEPT_ATTRS and v},
1368
- "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],
1369
1639
  "xpath": str(facts.get("xpath") or ""),
1370
1640
  "stable_hash": None,
1371
1641
  }
@@ -1438,6 +1708,9 @@ async def record_web(payload: Dict[str, Any], emit: Emit, commands: asyncio.Queu
1438
1708
  else:
1439
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).")
1440
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…")
1441
1714
  await s.review_values()
1442
1715
  s._render()
1443
1716
  return await s.finish()