@capagents/forgeqe 2.9.9 → 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.
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/docs-site/docs/web-app/index.html +6 -2
- package/dist/forgeqe.js +1811 -1696
- package/dist/web/assets/{Agent-B0R4tnqF.js → Agent-DQeWzsWG.js} +1 -1
- package/dist/web/assets/{ApiTests-CqWPHWCs.js → ApiTests-DrQBxtra.js} +1 -1
- package/dist/web/assets/{Browse-DlbTQPA8.js → Browse-CXqsKgMN.js} +2 -2
- package/dist/web/assets/{Chat-DtI3dgGs.js → Chat-rChaK9vu.js} +1 -1
- package/dist/web/assets/{CommandPalette-BTI3Q3sc.js → CommandPalette-LNTJ2Pie.js} +1 -1
- package/dist/web/assets/{Compare-BMcHYq3I.js → Compare-CP24uSyS.js} +1 -1
- package/dist/web/assets/{Cost-BcZ6gC9M.js → Cost-Cz6F4MAu.js} +1 -1
- package/dist/web/assets/{Data-Cbl35RTK.js → Data-RSpfLC9W.js} +1 -1
- package/dist/web/assets/{Desktop-D4JLSUnE.js → Desktop-C0VftUUl.js} +1 -1
- package/dist/web/assets/{DesktopReview-vyosGOyC.js → DesktopReview-BTYnwZKB.js} +1 -1
- package/dist/web/assets/{Evidence-MDaV4ttv.js → Evidence-DxfTgGLn.js} +1 -1
- package/dist/web/assets/{Explore-yjmJHnzH.js → Explore-BKAnJ0AP.js} +1 -1
- package/dist/web/assets/{Features-kXt6Um2p.js → Features-YYcKT5mB.js} +1 -1
- package/dist/web/assets/{Flags-CdLXiacX.js → Flags-B23vWmDR.js} +1 -1
- package/dist/web/assets/{Flaky-BZx54uo3.js → Flaky-kuhde8PW.js} +1 -1
- package/dist/web/assets/{Impact-_t7bwCwP.js → Impact-DetuURYY.js} +1 -1
- package/dist/web/assets/{Jobs-D4PIAcdO.js → Jobs-BTiCqtr9.js} +1 -1
- package/dist/web/assets/{KindPage-CGfjoezZ.js → KindPage-BbL7COME.js} +1 -1
- package/dist/web/assets/{Migration-OGOnRmUX.js → Migration-CPv7gDC-.js} +1 -1
- package/dist/web/assets/{Product-DycPE2MI.js → Product-DcrBguCI.js} +1 -1
- package/dist/web/assets/{Production-DqnrcSfn.js → Production-N11W9Ckr.js} +1 -1
- package/dist/web/assets/{Quality-C__pEYpt.js → Quality-DzXW1cvp.js} +1 -1
- package/dist/web/assets/{Readiness-j22NEcwR.js → Readiness-BbHO8wa2.js} +1 -1
- package/dist/web/assets/Record-P7TKcE5d.js +2 -0
- package/dist/web/assets/{Regression-ByBOHx96.js → Regression-BOSQ2Pxp.js} +1 -1
- package/dist/web/assets/{Reports-BGs_YnwI.js → Reports-BA1VdwoC.js} +1 -1
- package/dist/web/assets/{Response-DWF22-5i.js → Response-0i0ww7OC.js} +1 -1
- package/dist/web/assets/{RunDiff-YxrBVtxF.js → RunDiff-D-4tB7Is.js} +1 -1
- package/dist/web/assets/{Runs-CP3CgO6s.js → Runs-DW7dZh2j.js} +1 -1
- package/dist/web/assets/{TestCases-BzuM4M4t.js → TestCases-BfPkdwR6.js} +1 -1
- package/dist/web/assets/{TestData-CRmYpEgE.js → TestData-DRoJc7Me.js} +1 -1
- package/dist/web/assets/{TestDebt-D3I2zyGE.js → TestDebt-ly8BsLSJ.js} +1 -1
- package/dist/web/assets/{Tosca-jVIQnyZv.js → Tosca-CzrCAhEs.js} +1 -1
- package/dist/web/assets/{WhatsNew-EKniIJ6W.js → WhatsNew-Cd8D1O1X.js} +1 -1
- package/dist/web/assets/{dataParts-DRO6c2Kb.js → dataParts-DzHf4K4-.js} +1 -1
- package/dist/web/assets/{fold-D9yUIbTt.js → fold-CyU-Mjqe.js} +1 -1
- package/dist/web/assets/{frame--ur6lpMR.js → frame-DUo0M0VF.js} +2 -2
- package/dist/web/assets/index-Bv3atkwB.js +67 -0
- package/dist/web/assets/{logos-CdIbTq_J.js → logos-cftOc5MX.js} +1 -1
- package/dist/web/assets/{palette-D5_w8xup.js → palette-D_SCreF2.js} +1 -1
- package/dist/web/assets/{qualityParts-BPBFzuHH.js → qualityParts-50E_QRTX.js} +1 -1
- package/dist/web/assets/{rows-BVHC-HKz.js → rows-JZ5MvdCQ.js} +1 -1
- package/dist/web/assets/{thread-B4g66SWA.js → thread-CrExMoMY.js} +1 -1
- package/dist/web/assets/{usePageChat-BU6VEv0K.js → usePageChat-DpnA7edC.js} +1 -1
- package/dist/web/index.html +2 -2
- package/docs/WEB_APP.md +6 -2
- package/package.json +1 -1
- package/py/forgeqe_engine/browser.py +29 -0
- package/py/forgeqe_engine/capture.py +2 -2
- package/py/forgeqe_engine/dynamic.py +8 -0
- package/py/forgeqe_engine/memory.py +33 -2
- package/py/forgeqe_engine/recordsession.py +273 -22
- package/py/forgeqe_engine/webrecord.py +165 -2
- package/py/forgeqe_engine/webrecord_page.py +197 -11
- package/dist/web/assets/Record-D7h6g_aw.js +0 -2
- package/dist/web/assets/index-GLMqsotN.js +0 -66
|
@@ -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,9 +31,9 @@ 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
|
-
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
|
|
36
37
|
from .webrecord_page import recorder_js
|
|
37
38
|
|
|
38
39
|
|
|
@@ -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
|
|
@@ -123,6 +127,9 @@ class RecordSession:
|
|
|
123
127
|
self.emit = emit
|
|
124
128
|
self.start_url = str(payload.get("start_url") or "").strip()
|
|
125
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] = {}
|
|
126
133
|
self.name = " ".join(str(payload.get("name") or "").split())[:200]
|
|
127
134
|
self.leader = {**DEFAULT_LEADER, **(payload.get("leader") or {})}
|
|
128
135
|
self.queue: asyncio.Queue = asyncio.Queue()
|
|
@@ -170,6 +177,16 @@ class RecordSession:
|
|
|
170
177
|
# The page's own API calls after each step (method, path, status), for checks of them in the review.
|
|
171
178
|
self.calls: Dict[int, List[Dict[str, Any]]] = {}
|
|
172
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]] = {}
|
|
183
|
+
# The browser was closed once the recording stopped (release_browser), and its facts read just before.
|
|
184
|
+
self.released = False
|
|
185
|
+
self.profile: Optional[Dict[str, Any]] = None
|
|
186
|
+
# Sessions with a browser dialog open, how many have opened, and what each asked (to record with its answer).
|
|
187
|
+
self._dialogs: set = set()
|
|
188
|
+
self._dialog_count = 0
|
|
189
|
+
self._asked: Dict[str, Dict[str, Any]] = {}
|
|
173
190
|
# video.mp4 of the tab being recorded (payload ``video``), following the tester from tab to tab; paused with them.
|
|
174
191
|
self.video: Any = None
|
|
175
192
|
self._video_sid: Optional[str] = None
|
|
@@ -177,12 +194,39 @@ class RecordSession:
|
|
|
177
194
|
# -- the browser ----------------------------------------------------------------------------------------------
|
|
178
195
|
|
|
179
196
|
async def send(self, method: str, params: Optional[Dict[str, Any]] = None, sid: Optional[str] = None) -> Dict[str, Any]:
|
|
197
|
+
if self.client is None:
|
|
198
|
+
raise RuntimeError("the recording's browser is closed")
|
|
180
199
|
domain, name = method.split(".", 1)
|
|
181
200
|
fn = getattr(getattr(self.client.send, domain), name)
|
|
182
201
|
kw: Dict[str, Any] = {"params": params} if params is not None else {}
|
|
183
202
|
if sid:
|
|
184
203
|
kw["session_id"] = sid
|
|
185
|
-
|
|
204
|
+
call = asyncio.ensure_future(fn(**kw))
|
|
205
|
+
waited = 0.0
|
|
206
|
+
while True:
|
|
207
|
+
seen = self._dialog_count
|
|
208
|
+
done, _ = await asyncio.wait({call}, timeout=CDP_TIMEOUT)
|
|
209
|
+
if done:
|
|
210
|
+
return call.result() or {}
|
|
211
|
+
waited += CDP_TIMEOUT
|
|
212
|
+
# A dialog open now, or one that opened meanwhile: the page waits for the person, and the call with it.
|
|
213
|
+
if (self._dialogs or self._dialog_count != seen) and waited < DIALOG_WAIT:
|
|
214
|
+
continue
|
|
215
|
+
call.cancel()
|
|
216
|
+
raise asyncio.TimeoutError()
|
|
217
|
+
|
|
218
|
+
def _dialog(self, kind: str) -> Callable[[Any, Optional[str]], None]:
|
|
219
|
+
"""A dialog opening or closing: known at once (calls into the page wait while one is open), and queued to record."""
|
|
220
|
+
def handler(event: Any, session_id: Optional[str] = None) -> None:
|
|
221
|
+
key = session_id or ""
|
|
222
|
+
if kind == "dialog_open":
|
|
223
|
+
self._dialogs.add(key)
|
|
224
|
+
self._dialog_count += 1
|
|
225
|
+
else:
|
|
226
|
+
self._dialogs.discard(key)
|
|
227
|
+
self.queue.put_nowait((kind, event, session_id))
|
|
228
|
+
|
|
229
|
+
return handler
|
|
186
230
|
|
|
187
231
|
def _queue(self, kind: str) -> Callable[[Any, Optional[str]], None]:
|
|
188
232
|
def handler(event: Any, session_id: Optional[str] = None) -> None:
|
|
@@ -195,11 +239,12 @@ class RecordSession:
|
|
|
195
239
|
from cdp_use.client import CDPClient
|
|
196
240
|
|
|
197
241
|
from . import brand
|
|
198
|
-
from .browser import browser_name, local_launch_candidates, start_local_browser
|
|
242
|
+
from .browser import browser_name, leave_dialogs, local_launch_candidates, start_local_browser
|
|
199
243
|
from .logins import load_sessions, parse_logins, text_envs, use_logins
|
|
200
244
|
|
|
201
245
|
logins = parse_logins(self.payload.get("logins"))
|
|
202
246
|
use_logins(logins)
|
|
247
|
+
self.logins = logins
|
|
203
248
|
login_values = {env: os.environ.get(env, "") for env in text_envs() if os.environ.get(env)}
|
|
204
249
|
login_passwords = {",".join(l.hosts()): l.password_env for l in logins if l.password_env}
|
|
205
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)
|
|
@@ -209,7 +254,8 @@ class RecordSession:
|
|
|
209
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"))]
|
|
210
255
|
self.browser, self.launch = await start_local_browser(
|
|
211
256
|
candidates,
|
|
212
|
-
|
|
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})),
|
|
213
259
|
on_fallback=lambda failed, nxt, reason: self.log(f"{browser_name(failed)} did not start ({reason}); trying {browser_name(nxt)}", "warn"),
|
|
214
260
|
)
|
|
215
261
|
self.client = CDPClient(self.browser.cdp_url)
|
|
@@ -222,9 +268,19 @@ class RecordSession:
|
|
|
222
268
|
reg.Page.frameNavigated(self._queue("navigated"))
|
|
223
269
|
reg.Page.navigatedWithinDocument(self._queue("navigated_same"))
|
|
224
270
|
reg.Page.frameRequestedNavigation(self._queue("requested"))
|
|
271
|
+
reg.Page.javascriptDialogOpening(self._dialog("dialog_open"))
|
|
272
|
+
reg.Page.javascriptDialogClosed(self._dialog("dialog_closed"))
|
|
273
|
+
reg.Browser.downloadWillBegin(self._queue("download_begin"))
|
|
274
|
+
reg.Browser.downloadProgress(self._queue("download_progress"))
|
|
225
275
|
reg.Network.requestWillBeSent(self._queue("request"))
|
|
226
276
|
reg.Network.responseReceived(self._queue("response"))
|
|
227
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)
|
|
228
284
|
if self.llm is None and self.payload.get("llm") and (self.payload["llm"].get("provider") or "") != "mock":
|
|
229
285
|
try:
|
|
230
286
|
from .llm import _build_llm, _time_llm_calls
|
|
@@ -259,16 +315,49 @@ class RecordSession:
|
|
|
259
315
|
if str(getattr(self.browser, "cdp_url", "") or "").startswith(("http://127.0.0.1:", "ws://127.0.0.1:", "http://localhost:", "ws://localhost:")):
|
|
260
316
|
self.emit({"type": "browser", "cdp": self.browser.cdp_url})
|
|
261
317
|
|
|
262
|
-
async def
|
|
263
|
-
|
|
318
|
+
async def release_browser(self) -> None:
|
|
319
|
+
"""
|
|
320
|
+
The recording is over: its browser closes now, before what is left (the model's look at the values, the video
|
|
321
|
+
made from its pictures, the run's files), which needs none, so the window goes when the tester stops. The video's
|
|
322
|
+
pictures stop coming first, and the browser's facts for the run are read while it is still there.
|
|
323
|
+
"""
|
|
324
|
+
from .browser import _shutdown_browser_instance, browser_profile
|
|
264
325
|
|
|
265
|
-
|
|
266
|
-
|
|
326
|
+
if self.released:
|
|
327
|
+
return
|
|
328
|
+
self.released = True
|
|
329
|
+
sid, self._video_sid = self._video_sid, None
|
|
330
|
+
if self.video is not None and sid and sid in self.pages:
|
|
331
|
+
with contextlib.suppress(Exception):
|
|
332
|
+
await self.send("Page.stopScreencast", {}, sid)
|
|
333
|
+
if self.browser is not None and self.profile is None:
|
|
267
334
|
try:
|
|
268
|
-
await self.
|
|
335
|
+
self.profile = await asyncio.wait_for(browser_profile(self.browser, self.launch), timeout=8)
|
|
269
336
|
except Exception:
|
|
270
|
-
|
|
337
|
+
self.profile = {}
|
|
338
|
+
# Nothing is sent to the page any more (the panel, a log line): it is going.
|
|
339
|
+
self.pages.clear()
|
|
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)
|
|
350
|
+
client, self.client = self.client, None
|
|
351
|
+
if client is not None:
|
|
352
|
+
with contextlib.suppress(Exception):
|
|
353
|
+
await client.stop()
|
|
354
|
+
started = time.monotonic()
|
|
271
355
|
await _shutdown_browser_instance(self.browser)
|
|
356
|
+
logger.info("record: the browser closed %.1f s after the recording stopped", time.monotonic() - started)
|
|
357
|
+
|
|
358
|
+
async def close(self) -> None:
|
|
359
|
+
await self.release_browser()
|
|
360
|
+
await self._finish_video()
|
|
272
361
|
|
|
273
362
|
# -- the loop -------------------------------------------------------------------------------------------------
|
|
274
363
|
|
|
@@ -345,14 +434,89 @@ class RecordSession:
|
|
|
345
434
|
self._requests[str(event["requestId"])] = str((event.get("request") or {}).get("method") or "GET")
|
|
346
435
|
elif kind == "response":
|
|
347
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)
|
|
443
|
+
elif kind == "dialog_open":
|
|
444
|
+
if len(self._asked) > 100:
|
|
445
|
+
self._asked.clear()
|
|
446
|
+
self._asked[sid or ""] = {"kind": str(event.get("type") or ""), "message": event.get("message")}
|
|
447
|
+
elif kind == "dialog_closed":
|
|
448
|
+
self._dialog_closed(event, sid)
|
|
348
449
|
elif kind == "cmd":
|
|
349
450
|
await self.command(event)
|
|
350
451
|
except Exception as ex:
|
|
351
|
-
|
|
352
|
-
|
|
452
|
+
if "Session with given id not found" in str(ex) or "No target with given id" in str(ex):
|
|
453
|
+
# A frame or tab that closed before it was reached (an ad's frame, often): nothing to record there.
|
|
454
|
+
logger.debug("record: %s gone before it was reached: %s", kind, ex)
|
|
455
|
+
else:
|
|
456
|
+
logger.warning("record: %s not handled: %s", kind, ex)
|
|
457
|
+
logger.debug("record: details", exc_info=True)
|
|
353
458
|
await self._follow_video()
|
|
354
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
|
+
|
|
503
|
+
def _dialog_closed(self, event: Dict[str, Any], sid: Optional[str]) -> None:
|
|
504
|
+
"""The person answered a dialog of a tab or one of its frames: a step with what it asked and their answer."""
|
|
505
|
+
asked = self._asked.pop(sid or "", None)
|
|
506
|
+
rec = self.rec
|
|
507
|
+
tab = sid if sid in self.pages else (self.frames.get(sid or "") or {}).get("page")
|
|
508
|
+
if asked is None or rec is None or tab not in self.pages:
|
|
509
|
+
return
|
|
510
|
+
accept = event.get("result") is True
|
|
511
|
+
msg = rec.on_dialog(asked["kind"], asked["message"], accept, event.get("userInput") if accept else None)
|
|
512
|
+
logger.debug("record: a %s was answered %s", asked["kind"], "OK" if accept else "Cancel")
|
|
513
|
+
if msg:
|
|
514
|
+
self.active = tab
|
|
515
|
+
self._changed(msg)
|
|
516
|
+
|
|
355
517
|
def _response(self, event: Dict[str, Any], sid: Optional[str]) -> None:
|
|
518
|
+
if event.get("type") == "Document":
|
|
519
|
+
self._http_auth(event)
|
|
356
520
|
method = self._requests.pop(str(event.get("requestId") or ""), None)
|
|
357
521
|
rec = self.rec
|
|
358
522
|
if not method or rec is None or not rec.steps or self.paused or event.get("type") not in ("XHR", "Fetch"):
|
|
@@ -443,6 +607,13 @@ class RecordSession:
|
|
|
443
607
|
page["frame"] = frame.get("id") or page.get("frame")
|
|
444
608
|
page["ctx"] = None
|
|
445
609
|
url = str(frame.get("url") or "")
|
|
610
|
+
# A page loaded in the tab the video follows: Chrome drops a screencast when the tab moves to another
|
|
611
|
+
# process (the first page of a site, often), so it is asked for again.
|
|
612
|
+
if self.video is not None and sid == self._video_sid:
|
|
613
|
+
try:
|
|
614
|
+
await self.send("Page.startScreencast", dict(VIDEO_SCREENCAST), sid)
|
|
615
|
+
except Exception as ex:
|
|
616
|
+
logger.debug("record: no screencast of the page: %s", ex)
|
|
446
617
|
how = await self._how(sid, page)
|
|
447
618
|
renderer = page.pop("renderer", False)
|
|
448
619
|
if page.pop("initial", False) or (page.get("opener") and not page.get("seen")):
|
|
@@ -525,7 +696,7 @@ class RecordSession:
|
|
|
525
696
|
provider = named if named in {n for n, _ in CAPTCHA_FRAMES} else ""
|
|
526
697
|
if not provider:
|
|
527
698
|
return
|
|
528
|
-
if provider and kind in ("click", "dblclick", "fill", "select", "press", "captcha"):
|
|
699
|
+
if provider and kind in ("click", "dblclick", "fill", "select", "press", "captcha", "drag"):
|
|
529
700
|
msg = rec.on_captcha(provider)
|
|
530
701
|
if msg:
|
|
531
702
|
self._changed(msg)
|
|
@@ -552,7 +723,14 @@ class RecordSession:
|
|
|
552
723
|
if kind == "click":
|
|
553
724
|
t = await target(data)
|
|
554
725
|
hover = await target(data["hover"]) if isinstance(data.get("hover"), dict) else None
|
|
555
|
-
msg = rec.on_click(t, hover=hover)
|
|
726
|
+
msg = rec.on_click(t, hover=hover, right=data.get("button") == "right")
|
|
727
|
+
elif kind == "drag":
|
|
728
|
+
# An element moved: the one taken and, when it was let go on another, that one (each with a point in it).
|
|
729
|
+
if not isinstance(data.get("source"), dict):
|
|
730
|
+
return
|
|
731
|
+
src = await target(data["source"])
|
|
732
|
+
to = await target(data["target"]) if isinstance(data.get("target"), dict) else None
|
|
733
|
+
msg = rec.on_drag(src, to, drag_offset(data.get("offset")))
|
|
556
734
|
elif kind == "dblclick":
|
|
557
735
|
msg = rec.on_dblclick(await target(data))
|
|
558
736
|
elif kind == "fill":
|
|
@@ -566,6 +744,16 @@ class RecordSession:
|
|
|
566
744
|
msg = await self._uploaded(sid, data, ctx, target)
|
|
567
745
|
elif kind == "unsupported":
|
|
568
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))
|
|
569
757
|
elif kind == "pick":
|
|
570
758
|
# Picked here: a pick waiting in the tab's other frames (or the page) is over.
|
|
571
759
|
await self._cancel_picks(tab, but=(sid, ctx))
|
|
@@ -665,6 +853,11 @@ class RecordSession:
|
|
|
665
853
|
# counted them at the event, so its count stands in for a check that never finished.
|
|
666
854
|
if not (not any(l.get("verified") for l in live.locators) and any(l.get("verified") for l in fallback.locators)):
|
|
667
855
|
target = live
|
|
856
|
+
# Hidden since the event (a list of results that closes on the click): a locator by its name or text
|
|
857
|
+
# finds nothing now, so only its place (XPath) checks out. The page script counted them while it showed.
|
|
858
|
+
if target is live and _best_kind(fallback) > _best_kind(live) and not await self._shows(sid, int(backend)):
|
|
859
|
+
logger.debug("record: the element is hidden since the event: its locators as the page script counted them")
|
|
860
|
+
target = fallback
|
|
668
861
|
# None of its own locators unique: the one anchored on its container (the page script counted it), where there is one.
|
|
669
862
|
anchored = within_locator(data.get("anchor"))
|
|
670
863
|
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 +865,17 @@ class RecordSession:
|
|
|
672
865
|
target = Target(target.url, target.facts, locs, target.frames, closed_shadow=target.closed_shadow)
|
|
673
866
|
return await self._steady(sid, target, data.get("matches") if isinstance(data.get("matches"), dict) else {}, ctx=ctx)
|
|
674
867
|
|
|
868
|
+
async def _shows(self, sid: str, backend: int) -> bool:
|
|
869
|
+
"""Whether an element shows on the page now (it has a box); True when it cannot tell."""
|
|
870
|
+
try:
|
|
871
|
+
el = ((await self.send("DOM.resolveNode", {"backendNodeId": backend}, sid)).get("object") or {}).get("objectId")
|
|
872
|
+
if not el:
|
|
873
|
+
return True
|
|
874
|
+
r = await self.send("Runtime.callFunctionOn", {"objectId": el, "functionDeclaration": "function() { return this.getClientRects().length > 0; }", "returnByValue": True}, sid)
|
|
875
|
+
return (r.get("result") or {}).get("value") is not False
|
|
876
|
+
except Exception:
|
|
877
|
+
return True
|
|
878
|
+
|
|
675
879
|
async def _in_closed_shadow(self, sid: str, backend: int) -> bool:
|
|
676
880
|
"""
|
|
677
881
|
Whether an element is inside a shadow root the page asked for closed (open_shadow_js opened it): the hosts are
|
|
@@ -720,7 +924,8 @@ class RecordSession:
|
|
|
720
924
|
if kind not in ("role", "text", "label", "title", "alt"):
|
|
721
925
|
continue
|
|
722
926
|
role, _, name = str(loc.get("value") or "").partition("|") if kind == "role" else ("", "", str(loc.get("value") or ""))
|
|
723
|
-
|
|
927
|
+
# A control named only by a time of day (a slot in a time picker: "15:00") is the same choice on every run.
|
|
928
|
+
if not dynamic.is_dynamic(name) or dynamic.time_of_day(name):
|
|
724
929
|
continue
|
|
725
930
|
loc.update(verified=False, live_data=True)
|
|
726
931
|
loc["confidence"] = max(1, int((loc.get("confidence") or 30) * 0.3))
|
|
@@ -799,6 +1004,9 @@ class RecordSession:
|
|
|
799
1004
|
assert rec is not None
|
|
800
1005
|
t = await target(data)
|
|
801
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)
|
|
802
1010
|
if purpose == "variable":
|
|
803
1011
|
return rec.add_capture(t, text)
|
|
804
1012
|
if purpose == "wait":
|
|
@@ -1313,6 +1521,9 @@ class RecordSession:
|
|
|
1313
1521
|
rec = self.rec
|
|
1314
1522
|
assert rec is not None
|
|
1315
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()
|
|
1316
1527
|
video = await self._finish_video()
|
|
1317
1528
|
# The recorder's own working fields (an element's facts) stay out of the run.
|
|
1318
1529
|
steps = [
|
|
@@ -1323,10 +1534,12 @@ class RecordSession:
|
|
|
1323
1534
|
ok = recorded > 0
|
|
1324
1535
|
goal = self.name or auto_name(steps, self.start_url)
|
|
1325
1536
|
summary = f"Recorded by hand: {rec.summary()}" if ok else "Nothing was recorded after opening the start page."
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1537
|
+
profile = self.profile
|
|
1538
|
+
if profile is None:
|
|
1539
|
+
try:
|
|
1540
|
+
profile = await browser_profile(self.browser, self.launch)
|
|
1541
|
+
except Exception:
|
|
1542
|
+
profile = {}
|
|
1330
1543
|
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
1544
|
params = [s["param"] for s in steps if s.get("param")]
|
|
1332
1545
|
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)]]
|
|
@@ -1356,6 +1569,7 @@ class RecordSession:
|
|
|
1356
1569
|
"secrets": list(rec.secrets),
|
|
1357
1570
|
"skipped": list(rec.skipped),
|
|
1358
1571
|
"signed_in": bool(self.payload.get("signed_in")),
|
|
1572
|
+
**({"http_auth": list(self.http_auth.values())} if self.http_auth else {}),
|
|
1359
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 {}),
|
|
1360
1574
|
**({"case_id": self.case_id, "case_gaps": rec.case_gaps()} if rec.case_steps else {}),
|
|
1361
1575
|
},
|
|
@@ -1380,10 +1594,20 @@ def _count(loc: Dict[str, Any], counted: Dict[str, Any]) -> Optional[int]:
|
|
|
1380
1594
|
n = attrs.get("id")
|
|
1381
1595
|
elif kind in ("placeholder", "title", "alt"):
|
|
1382
1596
|
n = attrs.get(kind)
|
|
1597
|
+
elif kind == "css" and counted.get("css_sel") is not None and counted.get("css_sel") != loc.get("css"):
|
|
1598
|
+
# Counted for another selector (a class the page script kept that ForgeQE leaves out): not this one's count.
|
|
1599
|
+
n = None
|
|
1383
1600
|
elif kind in ("name", "href", "css", "text", "role", "label"):
|
|
1384
1601
|
n = counted.get(kind)
|
|
1385
1602
|
elif kind == "xpath":
|
|
1386
1603
|
n = 1
|
|
1604
|
+
elif kind == "role_pattern" and isinstance(counted.get("role_names"), list):
|
|
1605
|
+
# By how a long name starts: counted in the names of the others with that role, sent at the event.
|
|
1606
|
+
try:
|
|
1607
|
+
rx = re.compile(str(loc.get("value") or "").partition("|")[2])
|
|
1608
|
+
except re.error:
|
|
1609
|
+
return None
|
|
1610
|
+
n = sum(1 for x in counted["role_names"][:400] if isinstance(x, str) and rx.search(x))
|
|
1387
1611
|
else:
|
|
1388
1612
|
n = None
|
|
1389
1613
|
return n if isinstance(n, int) and n >= 0 else None
|
|
@@ -1419,6 +1643,25 @@ OPEN_SHADOW_JS = r"""(() => {
|
|
|
1419
1643
|
})()"""
|
|
1420
1644
|
|
|
1421
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
|
+
|
|
1656
|
+
def drag_offset(raw: Any) -> Optional[Dict[str, int]]:
|
|
1657
|
+
"""How far a drag moved the pointer, as the page script reported it: two whole numbers within a page's size, else None."""
|
|
1658
|
+
if not isinstance(raw, dict):
|
|
1659
|
+
return None
|
|
1660
|
+
x, y = raw.get("x"), raw.get("y")
|
|
1661
|
+
ok = lambda v: isinstance(v, int) and not isinstance(v, bool) and -20000 <= v <= 20000 # noqa: E731
|
|
1662
|
+
return {"x": x, "y": y} if ok(x) and ok(y) and (x or y) else None
|
|
1663
|
+
|
|
1664
|
+
|
|
1422
1665
|
def click_position(raw: Any) -> Optional[Dict[str, int]]:
|
|
1423
1666
|
"""Where in a canvas a click landed, as the page script reported it: two whole numbers within a page's size, else None."""
|
|
1424
1667
|
if not isinstance(raw, dict):
|
|
@@ -1478,6 +1721,11 @@ def clean_frame(raw: Any) -> Dict[str, Any]:
|
|
|
1478
1721
|
return out
|
|
1479
1722
|
|
|
1480
1723
|
|
|
1724
|
+
def _best_kind(t: Target) -> float:
|
|
1725
|
+
"""How good a target's best checked locator is, by its kind (BASE): -1 when none is checked."""
|
|
1726
|
+
return max((BASE.get(str(l.get("type")), 0) for l in t.locators if l.get("verified")), default=-1)
|
|
1727
|
+
|
|
1728
|
+
|
|
1481
1729
|
def fallback_target(url: str, facts: Dict[str, Any], counted: Optional[Dict[str, Any]] = None) -> Target:
|
|
1482
1730
|
"""
|
|
1483
1731
|
A target from the facts the page script read, for an element the page took away before ForgeQE could look at it.
|
|
@@ -1490,7 +1738,7 @@ def fallback_target(url: str, facts: Dict[str, Any], counted: Optional[Dict[str,
|
|
|
1490
1738
|
"name": " ".join(str(facts.get("name") or "").split())[:120],
|
|
1491
1739
|
"text": " ".join(str(facts.get("text") or "").split())[:120],
|
|
1492
1740
|
"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],
|
|
1741
|
+
"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
1742
|
"xpath": str(facts.get("xpath") or ""),
|
|
1495
1743
|
"stable_hash": None,
|
|
1496
1744
|
}
|
|
@@ -1559,10 +1807,13 @@ async def record_web(payload: Dict[str, Any], emit: Emit, commands: asyncio.Queu
|
|
|
1559
1807
|
await s.start()
|
|
1560
1808
|
await s.open()
|
|
1561
1809
|
if s.payload.get("panel") == "badge":
|
|
1562
|
-
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.")
|
|
1563
1811
|
else:
|
|
1564
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).")
|
|
1565
1813
|
await s.run(float(payload.get("max_seconds") or MAX_SECONDS))
|
|
1814
|
+
# Stopped: the browser closes at once; the rest is saving.
|
|
1815
|
+
await s.release_browser()
|
|
1816
|
+
s.log("Recording stopped; the browser is closed. Saving it…")
|
|
1566
1817
|
await s.review_values()
|
|
1567
1818
|
s._render()
|
|
1568
1819
|
return await s.finish()
|