@capagents/forgeqe 3.0.9 → 3.1.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/HOW_TO_USE.md +35 -22
- package/bin/bundle.js +3 -3
- package/bin/forgeqe.js +3 -3
- package/bin/license.js +1 -1
- package/dist/docs-site/CREDITS.md +11 -4
- package/dist/docs-site/LICENSE.dm-sans.txt +93 -0
- package/dist/docs-site/LICENSE.jetbrains-mono.txt +93 -0
- package/dist/docs-site/app-look.css +62 -0
- package/dist/docs-site/architecture-map/arch-fill.js +56 -0
- package/dist/docs-site/architecture-map/arch-theme.css +203 -0
- package/dist/docs-site/architecture-map/arch.css +0 -5
- package/dist/docs-site/architecture-map/index.html +57 -43
- package/dist/docs-site/docs/app-theme.css +166 -0
- package/dist/docs-site/docs/architecture/index.html +14 -11
- package/dist/docs-site/docs/containers/index.html +14 -11
- package/dist/docs-site/docs/cost-architecture/index.html +14 -11
- package/dist/docs-site/docs/custom-agents-first-run/index.html +14 -11
- package/dist/docs-site/docs/desktop/index.html +14 -11
- package/dist/docs-site/docs/desktop-ci/index.html +14 -11
- package/dist/docs-site/docs/docs.css +0 -7
- package/dist/docs-site/docs/evidence/index.html +14 -11
- package/dist/docs-site/docs/feature-test-prompts/index.html +14 -11
- package/dist/docs-site/docs/graphify/index.html +14 -11
- package/dist/docs-site/docs/guardrails/index.html +14 -11
- package/dist/docs-site/docs/index.html +96 -40
- package/dist/docs-site/docs/mobile/index.html +56 -18
- package/dist/docs-site/docs/model-routing/index.html +14 -11
- package/dist/docs-site/docs/product-graph/index.html +14 -11
- package/dist/docs-site/docs/product-knowledge/index.html +14 -11
- package/dist/docs-site/docs/product-views/index.html +14 -11
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/docs-site/docs/web-app/index.html +14 -11
- package/dist/docs-site/img/wordmark.webp +0 -0
- package/dist/docs-site/site-header.css +0 -5
- package/dist/forgeqe.js +2225 -1867
- package/dist/template.html +14 -14
- package/dist/web/assets/{AgentWork-BhepbEeU.js → AgentWork-DwAI0_Of.js} +1 -1
- package/dist/web/assets/ApiTests-C0vFSHmM.js +10 -0
- package/dist/web/assets/Browse-5jfdtRc5.js +2 -0
- package/dist/web/assets/Chat-B3uhI94O.js +3 -0
- package/dist/web/assets/{CommandPalette-DMAmXPq1.js → CommandPalette-D2J4nf5y.js} +1 -1
- package/dist/web/assets/{Compare-DJNSrM2v.js → Compare-CN75w1p9.js} +1 -1
- package/dist/web/assets/{Cost-CEOZgbPs.js → Cost-QoxyjR95.js} +1 -1
- package/dist/web/assets/{Data-COFRpcJn.js → Data-BAvkcBVt.js} +4 -4
- package/dist/web/assets/Desktop-BXdOIalN.js +1 -0
- package/dist/web/assets/DesktopReview-Bl2SrPP0.js +1 -0
- package/dist/web/assets/{Evidence-DTrdEz3M.js → Evidence-BJ_I52CD.js} +1 -1
- package/dist/web/assets/{Explore-DDXgQj5Q.js → Explore-D9AuyTip.js} +2 -2
- package/dist/web/assets/Features-CusGMDR9.js +1 -0
- package/dist/web/assets/Flags-CycGFuUP.js +2 -0
- package/dist/web/assets/Flaky-BcSzJogN.js +1 -0
- package/dist/web/assets/Impact-CJHnyZ21.js +3 -0
- package/dist/web/assets/Jobs-4xcFzEFo.js +5 -0
- package/dist/web/assets/KindPage-BielEIej.js +6 -0
- package/dist/web/assets/Migration-NwanKpJg.js +2 -0
- package/dist/web/assets/PageAgent-CNw4NXva.js +1 -0
- package/dist/web/assets/Product-DS3LJZ4P.js +7 -0
- package/dist/web/assets/Production-D3zsyNIS.js +1 -0
- package/dist/web/assets/{Quality-DgNo4H0u.js → Quality-Ctj2YpC4.js} +1 -1
- package/dist/web/assets/{Readiness--GiTxFZo.js → Readiness-DGcRr_co.js} +1 -1
- package/dist/web/assets/Record-Cc-wGe_Y.js +1 -0
- package/dist/web/assets/Regression-DcsbrRa1.js +5 -0
- package/dist/web/assets/{Reports-C-NSlVAn.js → Reports-BkCn0-Sf.js} +2 -2
- package/dist/web/assets/Response-BP0UwQcW.js +9 -0
- package/dist/web/assets/Responsive-C8U7dumd.js +3 -0
- package/dist/web/assets/{RunDiff-CIdQD95y.js → RunDiff-BhABuhF_.js} +1 -1
- package/dist/web/assets/Runs-OwdWEYBv.js +2 -0
- package/dist/web/assets/Steps-BvzbQyoD.js +2 -0
- package/dist/web/assets/{TestCases-D-ZRb2N7.js → TestCases-CLq_6JA5.js} +1 -1
- package/dist/web/assets/{TestData-kXWCn7uZ.js → TestData-B0oKAhp6.js} +2 -2
- package/dist/web/assets/TestDebt-8NLQ5YV_.js +1 -0
- package/dist/web/assets/TestManagement-2LYQ7vsN.js +1 -0
- package/dist/web/assets/Tosca-DfvMpPTG.js +3 -0
- package/dist/web/assets/{WhatsNew-DpJWNec7.js → WhatsNew-BGFNGwqN.js} +1 -1
- package/dist/web/assets/families-DYlN5v0i.js +1 -0
- package/dist/web/assets/filters-faaSnoIq.js +1 -0
- package/dist/web/assets/{fold-BRxvbN9r.js → fold-CUjwWAK3.js} +1 -1
- package/dist/web/assets/frame-BLPdAXUq.js +13 -0
- package/dist/web/assets/head-CsTxBsO0.js +1 -0
- package/dist/web/assets/index-CxiCvGZq.js +78 -0
- package/dist/web/assets/index-dOIsrzhD.css +2 -0
- package/dist/web/assets/line-icons-CwZWt93L.js +1 -0
- package/dist/web/assets/logos-dGuc1jIM.js +1 -0
- package/dist/web/assets/{markdown-CWisJbSJ.js → markdown-BI3F-SJ1.js} +5 -5
- package/dist/web/assets/paletteCommands-QJiCuUEr.js +1 -0
- package/dist/web/assets/parts-CdF1f7yS.js +1 -0
- package/dist/web/assets/{productParts-BxdHuSBa.js → productParts-hNLD9fN0.js} +1 -1
- package/dist/web/assets/qualityParts-CT25lBWU.js +1 -0
- package/dist/web/assets/{recordTest-CcplpTS6.js → recordTest-P792aBUt.js} +1 -1
- package/dist/web/index.html +6 -6
- package/docs/ForgeQE-Client-Overview.pdf +0 -0
- package/docs/ForgeQE-Installation-Guide.pdf +0 -0
- package/docs/MOBILE.md +42 -7
- package/docs/user-guide.html +65 -12
- package/package.json +1 -1
- package/prompts/brain.md +1 -0
- package/prompts/responsive-review.md +38 -0
- package/prompts/responsive-split.md +40 -0
- package/prompts/responsive.md +42 -0
- package/py/forgeqe_data/connect.py +3 -1
- package/py/forgeqe_data/flows.py +1 -1
- package/py/forgeqe_data/service.py +1 -1
- package/py/forgeqe_data/streams.py +1 -1
- package/py/forgeqe_data/testdata.py +1 -1
- package/py/forgeqe_desktop/replay.py +43 -1
- package/py/forgeqe_desktop/service.py +2 -0
- package/py/forgeqe_desktop/workflow.py +77 -15
- package/py/forgeqe_engine/brand.py +1 -1
- package/py/forgeqe_engine/browser.py +2 -1
- package/py/forgeqe_engine/diagnostics.py +1 -1
- package/py/forgeqe_engine/memory.py +2 -1
- package/py/forgeqe_engine/neutral_log.py +1 -1
- package/py/forgeqe_engine/otp.py +127 -12
- package/py/forgeqe_engine/pwlaunch.mjs +1 -1
- package/py/forgeqe_engine/recordsession.py +13 -3
- package/py/forgeqe_engine/webrecord.py +20 -0
- package/py/forgeqe_mobile/appium_driver.py +225 -10
- package/py/forgeqe_mobile/locators.py +277 -0
- package/py/forgeqe_mobile/maestro.py +28 -1
- package/py/forgeqe_mobile/magiclink.py +79 -0
- package/py/forgeqe_mobile/record.py +284 -67
- package/py/forgeqe_mobile/service.py +9 -0
- package/py/forgeqe_mobile/webview.py +142 -0
- package/py/forgeqe_tosca/ntir.py +45 -6
- package/dist/docs-site/LICENSE.ubuntu.txt +0 -96
- package/dist/docs-site/img/icons/api.svg +0 -1
- package/dist/docs-site/img/icons/architecture.svg +0 -1
- package/dist/docs-site/img/icons/branch.svg +0 -1
- package/dist/docs-site/img/icons/browser-agent.svg +0 -1
- package/dist/docs-site/img/icons/case.svg +0 -1
- package/dist/docs-site/img/icons/container.svg +0 -1
- package/dist/docs-site/img/icons/context-engine.svg +0 -1
- package/dist/docs-site/img/icons/desktop.svg +0 -1
- package/dist/docs-site/img/icons/download.svg +0 -1
- package/dist/docs-site/img/icons/explorer.svg +0 -1
- package/dist/docs-site/img/icons/feature.svg +0 -1
- package/dist/docs-site/img/icons/healer.svg +0 -1
- package/dist/docs-site/img/icons/knowledge-base.svg +0 -1
- package/dist/docs-site/img/icons/mail.svg +0 -1
- package/dist/docs-site/img/icons/mobile.svg +0 -1
- package/dist/docs-site/img/icons/model.svg +0 -1
- package/dist/docs-site/img/icons/network.svg +0 -1
- package/dist/docs-site/img/icons/orchestrator.svg +0 -1
- package/dist/docs-site/img/icons/plug.svg +0 -1
- package/dist/docs-site/img/icons/pr-reviewer.svg +0 -1
- package/dist/docs-site/img/icons/replay.svg +0 -1
- package/dist/docs-site/img/icons/report.svg +0 -1
- package/dist/docs-site/img/icons/result.svg +0 -1
- package/dist/docs-site/img/icons/rule.svg +0 -1
- package/dist/docs-site/img/icons/scribe.svg +0 -1
- package/dist/docs-site/img/icons/shield.svg +0 -1
- package/dist/docs-site/img/icons/specs.svg +0 -1
- package/dist/docs-site/img/icons/speed.svg +0 -1
- package/dist/docs-site/img/icons/stories.svg +0 -1
- package/dist/docs-site/img/icons/terminal.svg +0 -1
- package/dist/docs-site/img/icons/test-finder.svg +0 -1
- package/dist/docs-site/img/icons/visual.svg +0 -1
- package/dist/docs-site/img/icons/web.svg +0 -1
- package/dist/docs-site/img/icons/wikis.svg +0 -1
- package/dist/web/assets/Agent-MlW7cfAm.js +0 -7
- package/dist/web/assets/ApiTests-mxUkUZvv.js +0 -10
- package/dist/web/assets/Browse-DENLuv4C.js +0 -2
- package/dist/web/assets/Chat-jxak1jci.js +0 -3
- package/dist/web/assets/Desktop-DGNdy7iS.js +0 -1
- package/dist/web/assets/DesktopReview-SdAwvi9y.js +0 -1
- package/dist/web/assets/Features-BM5iXhOR.js +0 -1
- package/dist/web/assets/Flags-CkKp4bbv.js +0 -2
- package/dist/web/assets/Flaky-BqUHVLao.js +0 -1
- package/dist/web/assets/Impact-CA6s3POt.js +0 -3
- package/dist/web/assets/Jobs-B59p1qvn.js +0 -5
- package/dist/web/assets/KindPage-DPADNnwH.js +0 -6
- package/dist/web/assets/Migration-DtynahwR.js +0 -2
- package/dist/web/assets/PageAgent-CB8HtdGd.js +0 -1
- package/dist/web/assets/Product-wWMz2Nnk.js +0 -7
- package/dist/web/assets/Production-Nst6__N7.js +0 -1
- package/dist/web/assets/Record-a4whC1jV.js +0 -1
- package/dist/web/assets/Regression-hesOlN4G.js +0 -5
- package/dist/web/assets/RelationGraph-C3Re0M1N.js +0 -1
- package/dist/web/assets/Response-CzX2rQEZ.js +0 -9
- package/dist/web/assets/Runs-DIDCOhbK.js +0 -2
- package/dist/web/assets/Steps-BOWDBzu4.js +0 -2
- package/dist/web/assets/TestDebt-BvP3w7ye.js +0 -1
- package/dist/web/assets/TestManagement-CphGo9DZ.js +0 -1
- package/dist/web/assets/Tosca-dhFuqYxV.js +0 -3
- package/dist/web/assets/agentTabs-BO5l3zw2.js +0 -1
- package/dist/web/assets/dataParts-DeUdfjjv.js +0 -3
- package/dist/web/assets/diff-D1_Qo2h1.js +0 -2
- package/dist/web/assets/families-DWilSDct.js +0 -1
- package/dist/web/assets/filters-CVzIOjPG.js +0 -1
- package/dist/web/assets/frame-VTMu7MoC.js +0 -13
- package/dist/web/assets/index-CKRa-K2y.css +0 -2
- package/dist/web/assets/index-nuLrB-Rb.js +0 -69
- package/dist/web/assets/line-icons-C_amZ5-o.js +0 -1
- package/dist/web/assets/logos-J6txZkKc.js +0 -1
- package/dist/web/assets/paletteCommands-BmYmp6YY.js +0 -1
- package/dist/web/assets/parts-CDBCk_Xz.js +0 -1
- package/dist/web/assets/qualityParts-CGKSK9Dq.js +0 -1
- package/dist/web/assets/rows-yPc39hV7.js +0 -1
|
@@ -49,6 +49,8 @@ class StepResult:
|
|
|
49
49
|
error: str = ""
|
|
50
50
|
healed_target: Optional[Dict[str, Any]] = None
|
|
51
51
|
attempts: int = 1
|
|
52
|
+
# Which of the target's locators found its control (mobile): 0 its own, n its n-th fallback, when its own failed.
|
|
53
|
+
found_by: int = 0
|
|
52
54
|
# Labels of the dialogs dismissed while this step ran.
|
|
53
55
|
dismissed: List[str] = field(default_factory=list)
|
|
54
56
|
# A dismiss control found but not clicked, with the reason: told with the step's error, never dropped.
|
|
@@ -83,6 +85,10 @@ STALE_RETRIES = 2
|
|
|
83
85
|
LAUNCH_SETTLE = 1.5
|
|
84
86
|
|
|
85
87
|
|
|
88
|
+
# How long a checkbox or switch is given to show its new state after a tap.
|
|
89
|
+
CHECKED_SECONDS = 3.0
|
|
90
|
+
|
|
91
|
+
|
|
86
92
|
def _label(target: Mapping[str, Any]) -> str:
|
|
87
93
|
return str(target.get("name") or target.get("automation_id") or "")
|
|
88
94
|
|
|
@@ -104,6 +110,7 @@ def replay(
|
|
|
104
110
|
clock: Callable[[], float] = time.time,
|
|
105
111
|
keep_open: bool = False,
|
|
106
112
|
secret_aliases: Optional[Mapping[str, str]] = None,
|
|
113
|
+
open_link: Optional[Callable[[str, float], None]] = None,
|
|
107
114
|
) -> ReplayResult:
|
|
108
115
|
wf = validate(dict(workflow))
|
|
109
116
|
spec = resolve_app(wf["app"], apps, must_exist=must_exist)
|
|
@@ -134,6 +141,9 @@ def replay(
|
|
|
134
141
|
|
|
135
142
|
runner = _Runner(driver, spec, values, allowed_secret, wf.get("timeout", find_timeout), wf.get("dismiss") or [], sleep, clock, compare_image)
|
|
136
143
|
runner.mobile = wf["format"] == MOBILE_FORMAT
|
|
144
|
+
runner.open_link = open_link
|
|
145
|
+
if any(s["op"] == "open_link" for s in wf["steps"]) and open_link is None:
|
|
146
|
+
raise WorkflowError("this workflow opens a magic link, and this replay has no mailbox to read it from")
|
|
137
147
|
retry_ops = MOBILE_RETRY_OPS if runner.mobile else RETRY_OPS
|
|
138
148
|
default_retries = int(wf.get("retries", 0))
|
|
139
149
|
result = ReplayResult(ok=True)
|
|
@@ -146,6 +156,8 @@ def replay(
|
|
|
146
156
|
op = step["op"]
|
|
147
157
|
res = StepResult(index=i, op=op, ok=True, ms=0)
|
|
148
158
|
runner.res = res
|
|
159
|
+
# A magic link is the one sent since the step before it started (the step that asked for it).
|
|
160
|
+
runner.prev_started, runner.started = runner.started, started
|
|
149
161
|
tries = 1 + (int(step.get("retries", default_retries)) if op in retry_ops else 0)
|
|
150
162
|
error: Optional[Exception] = None
|
|
151
163
|
attempt = failures = stale = 0
|
|
@@ -223,6 +235,9 @@ class _Runner:
|
|
|
223
235
|
self.timeout, self.dismiss, self.sleep, self.clock, self.compare_image = timeout, dismiss, sleep, clock, compare_image
|
|
224
236
|
self.res = StepResult(index=0, op="", ok=True, ms=0)
|
|
225
237
|
self.mobile = False
|
|
238
|
+
self.open_link: Optional[Callable[[str, float], None]] = None
|
|
239
|
+
self.started: Optional[float] = None
|
|
240
|
+
self.prev_started: Optional[float] = None
|
|
226
241
|
|
|
227
242
|
def dismiss_dialogs(self) -> bool:
|
|
228
243
|
"""Click every ``dismiss`` control that is on screen now; whether any was."""
|
|
@@ -253,6 +268,9 @@ class _Runner:
|
|
|
253
268
|
started = self.clock()
|
|
254
269
|
try:
|
|
255
270
|
control = self.driver.find(target, timeout)
|
|
271
|
+
by = getattr(self.driver, "found_by", 0)
|
|
272
|
+
if isinstance(by, int) and by > 0:
|
|
273
|
+
self.res.found_by = max(self.res.found_by, by)
|
|
256
274
|
wait_ready = getattr(self.driver, "wait_ready", None)
|
|
257
275
|
if ready and wait_ready is not None:
|
|
258
276
|
wait_ready(control, max(0.0, timeout - (self.clock() - started)))
|
|
@@ -281,6 +299,10 @@ class _Runner:
|
|
|
281
299
|
self.dismiss_dialogs()
|
|
282
300
|
elif op == "close":
|
|
283
301
|
driver.close()
|
|
302
|
+
elif op == "open_link":
|
|
303
|
+
if self.open_link is None:
|
|
304
|
+
raise WorkflowError("this replay has no mailbox to read a magic link from")
|
|
305
|
+
self.open_link(step["login"], self.prev_started if self.prev_started is not None else self.started or self.clock())
|
|
284
306
|
elif op == "wait":
|
|
285
307
|
self.sleep(float(step["seconds"]))
|
|
286
308
|
elif op == "keys" and self.mobile:
|
|
@@ -302,6 +324,10 @@ class _Runner:
|
|
|
302
324
|
driver.scroll(step["direction"], control) # type: ignore[attr-defined]
|
|
303
325
|
elif op == "scroll_to":
|
|
304
326
|
self._scroll_to(step, timeout)
|
|
327
|
+
elif op in ("tap", "double_tap", "long_press") and "at" in step:
|
|
328
|
+
# A point inside the control (what the app draws there has no control of its own).
|
|
329
|
+
control = self.find(step["target"], timeout, ready=True)
|
|
330
|
+
driver.tap_point(control, step["at"], double=op == "double_tap", hold=op == "long_press") # type: ignore[attr-defined]
|
|
305
331
|
elif op in ("tap", "double_tap"):
|
|
306
332
|
driver.click(self.find(step["target"], timeout, ready=True), double=op == "double_tap")
|
|
307
333
|
elif op == "long_press":
|
|
@@ -311,13 +337,17 @@ class _Runner:
|
|
|
311
337
|
elif op == "expect_image":
|
|
312
338
|
self._expect_image(index, step, timeout)
|
|
313
339
|
else:
|
|
314
|
-
control = self.find(step["target"], timeout, ready=op in ("click", "double_click", "type", "select"))
|
|
340
|
+
control = self.find(step["target"], timeout, ready=op in ("click", "double_click", "type", "select", "set_checked"))
|
|
315
341
|
if op in ("click", "double_click"):
|
|
316
342
|
driver.click(control, double=op == "double_click")
|
|
317
343
|
elif op == "type":
|
|
318
344
|
driver.type_text(control, fill(step["text"], self.values, self.secret))
|
|
319
345
|
elif op == "select":
|
|
320
346
|
driver.select(control, fill(step["value"], self.values, self.secret))
|
|
347
|
+
elif op == "set_checked":
|
|
348
|
+
self._set_checked(control, bool(step["checked"]), timeout)
|
|
349
|
+
elif op == "expect" and "checked" in step and driver.is_checked(control) != bool(step["checked"]): # type: ignore[attr-defined]
|
|
350
|
+
raise AssertionError(f"expected {_label(step['target'])!r} to be {'on' if step['checked'] else 'off'}, it is {'off' if step['checked'] else 'on'}")
|
|
321
351
|
elif op == "expect" and "text" in step:
|
|
322
352
|
want = fill(step["text"], self.values, self.secret)
|
|
323
353
|
got = driver.text_of(control)
|
|
@@ -326,6 +356,18 @@ class _Runner:
|
|
|
326
356
|
raise AssertionError("the control's text does not contain the expected value (it holds a secret, so it is not shown)")
|
|
327
357
|
raise AssertionError(f"expected {want!r} in the control's text, found {got!r}")
|
|
328
358
|
|
|
359
|
+
def _set_checked(self, control: Any, want: bool, timeout: float) -> None:
|
|
360
|
+
"""A checkbox, switch or radio button left ``want``: tapped only when it is not so already, then confirmed."""
|
|
361
|
+
driver = self.driver
|
|
362
|
+
if driver.is_checked(control) == want: # type: ignore[attr-defined]
|
|
363
|
+
return
|
|
364
|
+
driver.click(control)
|
|
365
|
+
deadline = self.clock() + min(timeout, CHECKED_SECONDS)
|
|
366
|
+
while driver.is_checked(control) != want: # type: ignore[attr-defined]
|
|
367
|
+
if self.clock() >= deadline:
|
|
368
|
+
raise AssertionError(f"it was tapped but stayed {'off' if want else 'on'}")
|
|
369
|
+
self.sleep(POLL_SECONDS)
|
|
370
|
+
|
|
329
371
|
def _scroll_to(self, step: Mapping[str, Any], timeout: float) -> None:
|
|
330
372
|
"""Scroll (default: down the page) until the target is on screen, up to the timeout or MAX_SCROLLS."""
|
|
331
373
|
direction = step.get("direction", "down")
|
|
@@ -76,6 +76,8 @@ def _model(req: Mapping[str, Any], events: Events, model_factory: Optional[Calla
|
|
|
76
76
|
|
|
77
77
|
def _step_fields(res: Any) -> Dict[str, Any]:
|
|
78
78
|
out = {"index": res.index, "op": res.op, "ok": res.ok, "ms": res.ms, "error": res.error, "healed_target": res.healed_target}
|
|
79
|
+
if res.found_by:
|
|
80
|
+
out["found_by"] = res.found_by
|
|
79
81
|
if res.attempts > 1:
|
|
80
82
|
out["attempts"] = res.attempts
|
|
81
83
|
if res.dismissed:
|
|
@@ -34,20 +34,26 @@ MAX_DISMISS = 10
|
|
|
34
34
|
RETRY_OPS = ("click", "double_click", "type", "select", "keys", "expect", "expect_image")
|
|
35
35
|
TIMEOUT_OPS = ("launch", *TARGET_OPS, "expect_image", "long_press", "double_tap", "tap", "scroll_to", "drag")
|
|
36
36
|
|
|
37
|
-
MOBILE_OPS = ("launch", "tap", "double_tap", "long_press", "type", "select", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "back", "hide_keyboard", "keys", "wait", "wait_for", "close")
|
|
38
|
-
MOBILE_TARGET_OPS = ("tap", "double_tap", "long_press", "type", "select", "expect", "wait_for", "scroll_to", "drag")
|
|
39
|
-
MOBILE_RETRY_OPS = ("tap", "double_tap", "long_press", "type", "select", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "keys")
|
|
37
|
+
MOBILE_OPS = ("launch", "open_link", "tap", "double_tap", "long_press", "type", "select", "set_checked", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "back", "hide_keyboard", "keys", "wait", "wait_for", "close")
|
|
38
|
+
MOBILE_TARGET_OPS = ("tap", "double_tap", "long_press", "type", "select", "set_checked", "expect", "wait_for", "scroll_to", "drag")
|
|
39
|
+
MOBILE_RETRY_OPS = ("tap", "double_tap", "long_press", "type", "select", "set_checked", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "keys")
|
|
40
40
|
MOBILE_KEYS = ("enter", "back", "tab", "delete", "search")
|
|
41
41
|
SWIPE_DIRECTIONS = ("up", "down", "left", "right")
|
|
42
42
|
_MOBILE_STEP_KEYS = {
|
|
43
43
|
"launch": set(),
|
|
44
|
-
|
|
45
|
-
"
|
|
46
|
-
|
|
44
|
+
# The newest magic link the login's site sent to its mailbox, opened on the device (forgeqe_mobile/magiclink.py).
|
|
45
|
+
"open_link": {"login"},
|
|
46
|
+
# at: [x, y] inside the target in thousandths of its width and height, for what the app draws with no control.
|
|
47
|
+
"tap": {"target", "at"},
|
|
48
|
+
"double_tap": {"target", "at"},
|
|
49
|
+
"long_press": {"target", "at"},
|
|
47
50
|
"type": {"target", "text"},
|
|
48
51
|
# Opens the target (a drop-down) and picks the item that shows `value`.
|
|
49
52
|
"select": {"target", "value"},
|
|
50
|
-
|
|
53
|
+
# A checkbox, switch or radio button left on (checked: true) or off: tapped only when it is not so already.
|
|
54
|
+
"set_checked": {"target", "checked"},
|
|
55
|
+
# checked: the control is on (true) or off (false), as well as or instead of showing a text.
|
|
56
|
+
"expect": {"target", "text", "checked"},
|
|
51
57
|
"expect_image": {"target", "image", "tolerance", "ignore"},
|
|
52
58
|
"swipe": {"direction", "target"},
|
|
53
59
|
# Moves the content (down: shows what is further down) of the target, or of the screen's scrolling view.
|
|
@@ -62,7 +68,7 @@ _MOBILE_STEP_KEYS = {
|
|
|
62
68
|
"wait_for": {"target", "text", "gone"},
|
|
63
69
|
"close": set(),
|
|
64
70
|
}
|
|
65
|
-
_MOBILE_REQUIRED = {"type": {"target", "text"}, "select": {"target", "value"}, "keys": {"keys"}, "wait": {"seconds"}, "expect_image": {"image"}, "swipe": {"direction"}, "scroll": {"direction"}, "drag": {"target", "to"}}
|
|
71
|
+
_MOBILE_REQUIRED = {"open_link": {"login"}, "type": {"target", "text"}, "select": {"target", "value"}, "set_checked": {"target", "checked"}, "keys": {"keys"}, "wait": {"seconds"}, "expect_image": {"image"}, "swipe": {"direction"}, "scroll": {"direction"}, "drag": {"target", "to"}}
|
|
66
72
|
IMAGE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,99}\.png$")
|
|
67
73
|
MAX_IGNORE = 20
|
|
68
74
|
|
|
@@ -123,12 +129,44 @@ def parse_chord(chord: str) -> List[str]:
|
|
|
123
129
|
return [*mods, key]
|
|
124
130
|
|
|
125
131
|
|
|
126
|
-
|
|
132
|
+
# A mobile target's alternatives a replay tries in order (forgeqe_mobile/locators.py), and how many at most.
|
|
133
|
+
MOBILE_LOCATOR_KEYS = ("within", "fallbacks", "web")
|
|
134
|
+
MAX_FALLBACKS = 4
|
|
135
|
+
_ANCHOR_KEYS = ("automation_id", "name")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _check_target(where: str, target: Any, mobile: bool = False, fallback: bool = False) -> Dict[str, Any]:
|
|
127
139
|
if not isinstance(target, dict):
|
|
128
140
|
raise WorkflowError(f"{where}: target must be a mapping of UIA properties")
|
|
129
|
-
|
|
141
|
+
allowed = set(LOCATOR_KEYS) | ({"within", "web"} | (set() if fallback else {"fallbacks"}) if mobile else set())
|
|
142
|
+
unknown = set(target) - allowed
|
|
130
143
|
if unknown:
|
|
131
|
-
raise WorkflowError(f"{where}: unknown target keys {sorted(unknown)}; use {', '.join(LOCATOR_KEYS)}")
|
|
144
|
+
raise WorkflowError(f"{where}: unknown target keys {sorted(unknown)}; use {', '.join(sorted(allowed, key=lambda k: (k not in LOCATOR_KEYS, k)))}")
|
|
145
|
+
out_extra: Dict[str, Any] = {}
|
|
146
|
+
if "within" in target:
|
|
147
|
+
# The ancestor a relative locator starts from: plain properties only, never a path or a query.
|
|
148
|
+
anchor = target["within"]
|
|
149
|
+
if not isinstance(anchor, dict) or not anchor or set(anchor) - set(_ANCHOR_KEYS) or not all(isinstance(v, str) and v.strip() and not any(ord(c) < 32 or ord(c) == 127 for c in v) for v in anchor.values()):
|
|
150
|
+
raise WorkflowError(f"{where}: target.within must be {{automation_id}} or {{name}}: the ancestor it is found inside")
|
|
151
|
+
out_extra["within"] = dict(anchor)
|
|
152
|
+
if "web" in target:
|
|
153
|
+
# An element of a web page inside the app, by plain properties only (forgeqe_mobile/webview.py builds the query).
|
|
154
|
+
from forgeqe_mobile.webview import WEB_KEYS, clean_web
|
|
155
|
+
|
|
156
|
+
web = clean_web(target["web"])
|
|
157
|
+
if web is None:
|
|
158
|
+
raise WorkflowError(f"{where}: target.web must be plain properties of a web element ({', '.join(WEB_KEYS)}), one line each")
|
|
159
|
+
if set(target) - {"web", "fallbacks"}:
|
|
160
|
+
raise WorkflowError(f"{where}: a web element's target has only web (and fallbacks)")
|
|
161
|
+
out_extra["web"] = web
|
|
162
|
+
if "fallbacks" in target:
|
|
163
|
+
rest = target["fallbacks"]
|
|
164
|
+
if not isinstance(rest, list) or not rest or len(rest) > MAX_FALLBACKS:
|
|
165
|
+
raise WorkflowError(f"{where}: target.fallbacks must be a list of 1 to {MAX_FALLBACKS} targets")
|
|
166
|
+
out_extra["fallbacks"] = [_check_target(f"{where} (fallback {i})", f, mobile=True, fallback=True) for i, f in enumerate(rest, 1)]
|
|
167
|
+
target = {k: v for k, v in target.items() if k not in MOBILE_LOCATOR_KEYS}
|
|
168
|
+
if "web" in out_extra:
|
|
169
|
+
return {**target, **out_extra}
|
|
132
170
|
if not str(target.get("automation_id") or "").strip() and not str(target.get("name") or "").strip():
|
|
133
171
|
raise WorkflowError(f"{where}: target needs an automation_id or a name")
|
|
134
172
|
for k in ("automation_id", "name", "control_type", "class_name"):
|
|
@@ -140,7 +178,7 @@ def _check_target(where: str, target: Any) -> Dict[str, Any]:
|
|
|
140
178
|
path = target["path"]
|
|
141
179
|
if not isinstance(path, list) or not all(isinstance(p, dict) and set(p) <= {"control_type", "name"} for p in path):
|
|
142
180
|
raise WorkflowError(f"{where}: target.path must be a list of {{control_type, name}}")
|
|
143
|
-
return dict(target)
|
|
181
|
+
return {**dict(target), **out_extra}
|
|
144
182
|
|
|
145
183
|
|
|
146
184
|
def _seconds(where: str, value: Any, most: float) -> float:
|
|
@@ -214,14 +252,27 @@ def validate(doc: Any) -> Dict[str, Any]:
|
|
|
214
252
|
raise WorkflowError(f"{where} ({op}) needs {', '.join(sorted(missing))}")
|
|
215
253
|
clean: Dict[str, Any] = {"op": op}
|
|
216
254
|
if "target" in step:
|
|
217
|
-
clean["target"] = _check_target(where, step["target"])
|
|
255
|
+
clean["target"] = _check_target(where, step["target"], mobile)
|
|
218
256
|
if "to" in step:
|
|
219
|
-
clean["to"] = _check_target(f"{where} (to)", step["to"])
|
|
257
|
+
clean["to"] = _check_target(f"{where} (to)", step["to"], mobile)
|
|
220
258
|
for k in ("text", "value"):
|
|
221
259
|
if k in step:
|
|
222
260
|
if not isinstance(step[k], (str, int, float)) or isinstance(step[k], bool):
|
|
223
261
|
raise WorkflowError(f"{where}: {k} must be text")
|
|
224
262
|
clean[k] = str(step[k])
|
|
263
|
+
if "at" in step:
|
|
264
|
+
at = step["at"]
|
|
265
|
+
if not (isinstance(at, list) and len(at) == 2 and all(isinstance(n, int) and not isinstance(n, bool) and 0 <= n <= 1000 for n in at)):
|
|
266
|
+
raise WorkflowError(f"{where}: at is [x, y] inside the control, each a whole number from 0 to 1000 (thousandths of its size)")
|
|
267
|
+
clean["at"] = list(at)
|
|
268
|
+
if op == "open_link":
|
|
269
|
+
if not isinstance(step["login"], str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,63}", step["login"]):
|
|
270
|
+
raise WorkflowError(f"{where}: login is the name of a saved login (letters, digits and _)")
|
|
271
|
+
clean["login"] = step["login"]
|
|
272
|
+
if "checked" in step:
|
|
273
|
+
if not isinstance(step["checked"], bool):
|
|
274
|
+
raise WorkflowError(f"{where}: checked must be true or false")
|
|
275
|
+
clean["checked"] = step["checked"]
|
|
225
276
|
if op == "keys" and mobile:
|
|
226
277
|
key = str(step["keys"]).strip().lower()
|
|
227
278
|
if key not in MOBILE_KEYS:
|
|
@@ -271,7 +322,7 @@ def validate(doc: Any) -> Dict[str, Any]:
|
|
|
271
322
|
dismiss = doc["dismiss"]
|
|
272
323
|
if not isinstance(dismiss, list) or len(dismiss) > MAX_DISMISS:
|
|
273
324
|
raise WorkflowError(f"dismiss must be a list of at most {MAX_DISMISS} targets (the buttons that close a dialog in the way)")
|
|
274
|
-
result["dismiss"] = [_check_target(f"dismiss {i}", t) for i, t in enumerate(dismiss, 1)]
|
|
325
|
+
result["dismiss"] = [_check_target(f"dismiss {i}", t, mobile) for i, t in enumerate(dismiss, 1)]
|
|
275
326
|
return result
|
|
276
327
|
|
|
277
328
|
|
|
@@ -335,6 +386,17 @@ def fill_targets(workflow: Mapping[str, Any], variables: Mapping[str, Any]) -> D
|
|
|
335
386
|
out[k] = fill(out[k], variables, no_secret)
|
|
336
387
|
if isinstance(out.get("path"), list):
|
|
337
388
|
out["path"] = [{**p, **({"name": fill(p["name"], variables, no_secret)} if isinstance(p.get("name"), str) else {})} for p in out["path"]]
|
|
389
|
+
if isinstance(out.get("web"), Mapping):
|
|
390
|
+
from forgeqe_mobile.webview import clean_web
|
|
391
|
+
|
|
392
|
+
filled = {k: fill(v, variables, no_secret) if isinstance(v, str) and k not in ("attr", "tag") else v for k, v in out["web"].items()}
|
|
393
|
+
if clean_web(filled) is None:
|
|
394
|
+
raise WorkflowError("a web element's locator holds a variable whose value is not one plain line of text")
|
|
395
|
+
out["web"] = filled
|
|
396
|
+
if isinstance(out.get("within"), Mapping):
|
|
397
|
+
out["within"] = {k: fill(v, variables, no_secret) if isinstance(v, str) else v for k, v in out["within"].items()}
|
|
398
|
+
if isinstance(out.get("fallbacks"), list):
|
|
399
|
+
out["fallbacks"] = [one(f) for f in out["fallbacks"] if isinstance(f, Mapping)]
|
|
338
400
|
return out
|
|
339
401
|
|
|
340
402
|
wf = dict(workflow)
|
|
@@ -381,7 +381,7 @@ def _pattern_words(pattern: Any, is_regex: Any = None) -> str:
|
|
|
381
381
|
s = _REGEX_GAP.sub(" … ", s)
|
|
382
382
|
s = _REGEX_SPACE.sub(" ", s)
|
|
383
383
|
s = re.sub(r"\\([^a-zA-Z0-9])", r"\1", s)
|
|
384
|
-
s = re.sub(r"
|
|
384
|
+
s = re.sub(r"(?:^\^)|(?:(?<!\\)\$$)", "", s.strip())
|
|
385
385
|
s = re.sub(r"\s*…\s*", " … ", s)
|
|
386
386
|
return re.sub(r"\s+", " ", s).strip() or str(pattern or "")
|
|
387
387
|
|
|
@@ -7,6 +7,7 @@ import atexit
|
|
|
7
7
|
import contextlib
|
|
8
8
|
import json
|
|
9
9
|
import logging
|
|
10
|
+
import math
|
|
10
11
|
import os
|
|
11
12
|
import sys
|
|
12
13
|
import time
|
|
@@ -178,7 +179,7 @@ def devtools_wait_seconds() -> float:
|
|
|
178
179
|
value = float((os.getenv("FORGEQE_ENGINE_BROWSER_START_SECONDS") or "").strip())
|
|
179
180
|
except ValueError:
|
|
180
181
|
return DEVTOOLS_WAIT_SECONDS
|
|
181
|
-
return min(600.0, max(15.0, value))
|
|
182
|
+
return DEVTOOLS_WAIT_SECONDS if math.isnan(value) else min(600.0, max(15.0, value))
|
|
182
183
|
|
|
183
184
|
|
|
184
185
|
start_logger = logging.getLogger("forgeqe_engine.browser_start")
|
|
@@ -137,7 +137,7 @@ L10N_MEASURE = r"""((full) => {
|
|
|
137
137
|
const vw = window.innerWidth;
|
|
138
138
|
const out = {lang: html.getAttribute('lang') || '', dir: getComputedStyle(html).direction, pageScroll: html.scrollWidth > vw + 2,
|
|
139
139
|
truncated: [], overflow: [], keys: [], english: [], checked: 0};
|
|
140
|
-
const key = /^[a-z][a-z0-9_-]*(\.[a-z0-9_-]+){2,}$|\{\{\s*[\w.$-]+\s*\}\}|\[missing ["'][^\]]+["'] translation\]|missing[ _]translation|^__[\w.]+__$|\$t\(
|
|
140
|
+
const key = /^[a-z][a-z0-9_-]*(\.[a-z0-9_-]+){2,}$|\{\{\s*[\w.$-]+\s*\}\}|\[missing ["'][^\]]+["'] translation\]|missing[ _]translation|^__[\w.]+__$|\$t\(|%%\(?[sd]\)?s?$/i;
|
|
141
141
|
const common = /\b(the|and|your|you|please|click|submit|cancel|save|delete|search|sign in|log in|password|continue|back|next|error|required|welcome)\b/gi;
|
|
142
142
|
const english = full && out.lang && !/^en\b/i.test(out.lang);
|
|
143
143
|
const seen = new Set();
|
|
@@ -165,7 +165,8 @@ def playwright_role_ok(tag: str, attrs: Dict[str, str], role: str) -> bool:
|
|
|
165
165
|
|
|
166
166
|
|
|
167
167
|
def _sha(text: str, n: int) -> str:
|
|
168
|
-
|
|
168
|
+
# A short id for a memory entry, not a security check; SHA-1 keeps existing ids the same.
|
|
169
|
+
return hashlib.sha1(text.encode("utf-8"), usedforsecurity=False).hexdigest()[:n]
|
|
169
170
|
|
|
170
171
|
|
|
171
172
|
# Classes a page sets for a state, not for what an element is: the item under the pointer or chosen (active, selected,
|
|
@@ -13,7 +13,7 @@ import re
|
|
|
13
13
|
from typing import Any
|
|
14
14
|
|
|
15
15
|
_LIBRARY = "browser_use"
|
|
16
|
-
_PROJECT_LINK = re.compile(r"\s*\(?\bhttps?://(?:[\w.-]*\.)?(?:github\.com/browser-use|browser-use\.com)\S*\)?", re.IGNORECASE)
|
|
16
|
+
_PROJECT_LINK = re.compile(r"(?<!\s)\s*\(?\bhttps?://(?:[\w.-]*\.)?(?:github\.com/browser-use|browser-use\.com)\S*\)?", re.IGNORECASE)
|
|
17
17
|
_NAME = re.compile(r"\bbrowser[-_ ]?use\b", re.IGNORECASE)
|
|
18
18
|
# A session's contents as the library prints them: storage_state=..., or a cookie's value, to the end of the line.
|
|
19
19
|
_SESSION = re.compile(r"(\bstorage_state\s*[=:]\s*)(?=[{\[(\'\"]).*", re.IGNORECASE)
|
package/py/forgeqe_engine/otp.py
CHANGED
|
@@ -6,6 +6,10 @@ What arrives is untrusted: a message's text is never logged, shown to the model
|
|
|
6
6
|
it, by the login's pattern (a capture group), and only when it looks like a code (letters, digits and -, 3 to 12).
|
|
7
7
|
Every connection checks TLS (the system's trust, never turned off); a test environment's endpoint is https, or http on
|
|
8
8
|
this computer only. Credentials come from environment variables named in the login, never from the request.
|
|
9
|
+
|
|
10
|
+
A magic link (a sign-in or verification link sent by email) is read from the same mailbox (``fetch_link``): only an
|
|
11
|
+
https link to one of the login's own sites (``link_in``), never with a user name in it; it is opened, never logged,
|
|
12
|
+
shown or kept.
|
|
9
13
|
"""
|
|
10
14
|
from __future__ import annotations
|
|
11
15
|
|
|
@@ -13,6 +17,7 @@ import base64
|
|
|
13
17
|
import email
|
|
14
18
|
import email.policy
|
|
15
19
|
import email.utils
|
|
20
|
+
import html
|
|
16
21
|
import imaplib
|
|
17
22
|
import json
|
|
18
23
|
import os
|
|
@@ -144,9 +149,16 @@ def _text_of(msg: Any) -> str:
|
|
|
144
149
|
return " ".join(parts)[:MAX_MESSAGE]
|
|
145
150
|
|
|
146
151
|
|
|
147
|
-
def
|
|
148
|
-
"""
|
|
149
|
-
|
|
152
|
+
def tls_context() -> ssl.SSLContext:
|
|
153
|
+
"""Verified TLS (certificate and host name), 1.2 or newer: Python 3.9's default context still offers 1.0 and 1.1."""
|
|
154
|
+
ctx = ssl.create_default_context()
|
|
155
|
+
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
156
|
+
return ctx
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _messages(src: CodeSource, since: float, env: Mapping[str, str], imap: Callable[..., Any]) -> Any:
|
|
160
|
+
"""The mailbox's messages since `since` (from `sender`, to `to` when given), newest first, read-only."""
|
|
161
|
+
box = imap(src.host, 993, ssl_context=tls_context())
|
|
150
162
|
try:
|
|
151
163
|
box.login(_env(src.user_env, env), _env(src.secret_env, env))
|
|
152
164
|
box.select(_quote(src.folder), readonly=True)
|
|
@@ -158,7 +170,7 @@ def read_email(src: CodeSource, since: float, env: Mapping[str, str], imap: Call
|
|
|
158
170
|
query += ["TO", _quote(src.to)]
|
|
159
171
|
status, data = box.search(None, *query)
|
|
160
172
|
if status != "OK" or not data or not data[0]:
|
|
161
|
-
return
|
|
173
|
+
return
|
|
162
174
|
for num in reversed(data[0].split()[-MAX_MESSAGES:]):
|
|
163
175
|
status, parts = box.fetch(num, f"(BODY.PEEK[]<0.{MAX_MESSAGE}>)")
|
|
164
176
|
raw = next((p[1] for p in parts or [] if isinstance(p, tuple) and len(p) > 1), None)
|
|
@@ -169,12 +181,8 @@ def read_email(src: CodeSource, since: float, env: Mapping[str, str], imap: Call
|
|
|
169
181
|
sent = email.utils.parsedate_to_datetime(str(msg.get("date"))).timestamp()
|
|
170
182
|
except Exception:
|
|
171
183
|
continue
|
|
172
|
-
if sent
|
|
173
|
-
|
|
174
|
-
code = code_in(_text_of(msg), src.pattern)
|
|
175
|
-
if code:
|
|
176
|
-
return code
|
|
177
|
-
return None
|
|
184
|
+
if sent >= since - SKEW:
|
|
185
|
+
yield msg
|
|
178
186
|
finally:
|
|
179
187
|
try:
|
|
180
188
|
box.logout()
|
|
@@ -182,6 +190,15 @@ def read_email(src: CodeSource, since: float, env: Mapping[str, str], imap: Call
|
|
|
182
190
|
pass
|
|
183
191
|
|
|
184
192
|
|
|
193
|
+
def read_email(src: CodeSource, since: float, env: Mapping[str, str], imap: Callable[..., Any] = imaplib.IMAP4_SSL) -> Optional[str]:
|
|
194
|
+
"""The code of the newest message since `since` (from `sender`, to `to` when given), read-only."""
|
|
195
|
+
for msg in _messages(src, since, env, imap):
|
|
196
|
+
code = code_in(_text_of(msg), src.pattern)
|
|
197
|
+
if code:
|
|
198
|
+
return code
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
|
|
185
202
|
def _quote(s: str) -> str:
|
|
186
203
|
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
187
204
|
|
|
@@ -201,8 +218,7 @@ class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
|
201
218
|
|
|
202
219
|
|
|
203
220
|
def _opener() -> Callable[..., Any]:
|
|
204
|
-
|
|
205
|
-
return urllib.request.build_opener(_NoRedirect(), urllib.request.HTTPSHandler(context=ctx)).open
|
|
221
|
+
return urllib.request.build_opener(_NoRedirect(), urllib.request.HTTPSHandler(context=tls_context())).open
|
|
206
222
|
|
|
207
223
|
|
|
208
224
|
def read_sms(src: CodeSource, since: float, env: Mapping[str, str], opener: Optional[Callable[..., Any]] = None) -> Optional[str]:
|
|
@@ -301,3 +317,102 @@ def fetch_code(
|
|
|
301
317
|
where = {"email": f"the mailbox on {src.host}", "sms": f"the text messages to {src.to}", "http": "the test environment's address"}[src.kind]
|
|
302
318
|
raise CodeError(f"No new code arrived in {where} within {src.wait} s" + (f" (the last try failed: {last})" if last else ""))
|
|
303
319
|
sleep(3)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
# A magic link: the longest kept, and how a link is found in a message's plain text and its HTML.
|
|
323
|
+
MAX_LINK = 2048
|
|
324
|
+
_PLAIN_LINK = re.compile(r"https://[^\s<>\"'()]+", re.I)
|
|
325
|
+
_HREF = re.compile(r"""href\s*=\s*(?:"([^"]*)"|'([^']*)')""", re.I)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _site_of(host: str, hosts: List[str]) -> bool:
|
|
329
|
+
"""One of the login's sites: a host exactly, or a subdomain only of a ``*.`` pattern (shop.example's, never .com's)."""
|
|
330
|
+
for h in hosts:
|
|
331
|
+
if h.startswith("*."):
|
|
332
|
+
base = h[2:]
|
|
333
|
+
if base.count(".") >= 1 and (host == base or host.endswith("." + base)):
|
|
334
|
+
return True
|
|
335
|
+
elif h and host == h:
|
|
336
|
+
return True
|
|
337
|
+
return False
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def link_in(msg: Any, hosts: List[str]) -> Optional[str]:
|
|
341
|
+
"""
|
|
342
|
+
The first https link of a message (its HTML links, then its plain text) to one of ``hosts`` or their subdomains,
|
|
343
|
+
with no user name, at most MAX_LINK long and on one line; None when it has none. The message is data.
|
|
344
|
+
"""
|
|
345
|
+
hosts = [h.lower().rstrip(".") for h in hosts if h]
|
|
346
|
+
found: List[str] = []
|
|
347
|
+
for part in msg.walk() if msg.is_multipart() else [msg]:
|
|
348
|
+
ctype = part.get_content_type()
|
|
349
|
+
if ctype not in ("text/plain", "text/html") or part.get_filename():
|
|
350
|
+
continue
|
|
351
|
+
try:
|
|
352
|
+
body = str(part.get_content())[:MAX_MESSAGE]
|
|
353
|
+
except Exception:
|
|
354
|
+
continue
|
|
355
|
+
if ctype == "text/html":
|
|
356
|
+
# In HTML only its links: a scan of its text could cut a link short where the href was refused.
|
|
357
|
+
found += [html.unescape(a or b) for a, b in _HREF.findall(body)]
|
|
358
|
+
else:
|
|
359
|
+
found += _PLAIN_LINK.findall(body)
|
|
360
|
+
for raw in found:
|
|
361
|
+
link = raw.strip().rstrip(".,;")
|
|
362
|
+
if not link or len(link) > MAX_LINK or re.search(r"[\x00-\x20\x7f]", link):
|
|
363
|
+
continue
|
|
364
|
+
try:
|
|
365
|
+
u = urllib.parse.urlsplit(link)
|
|
366
|
+
except ValueError:
|
|
367
|
+
continue
|
|
368
|
+
if u.scheme.lower() != "https" or not u.hostname or u.username or u.password:
|
|
369
|
+
continue
|
|
370
|
+
if _site_of(u.hostname.lower(), hosts):
|
|
371
|
+
return link
|
|
372
|
+
return None
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def read_email_link(src: CodeSource, since: float, env: Mapping[str, str], hosts: List[str], imap: Callable[..., Any] = imaplib.IMAP4_SSL) -> Optional[str]:
|
|
376
|
+
"""The magic link of the newest message since `since` (from `sender`, to `to` when given), read-only."""
|
|
377
|
+
for msg in _messages(src, since, env, imap):
|
|
378
|
+
link = link_in(msg, hosts)
|
|
379
|
+
if link:
|
|
380
|
+
return link
|
|
381
|
+
return None
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def fetch_link(
|
|
385
|
+
src: CodeSource,
|
|
386
|
+
hosts: List[str],
|
|
387
|
+
since: float,
|
|
388
|
+
env: Optional[Mapping[str, str]] = None,
|
|
389
|
+
*,
|
|
390
|
+
used: Optional[List[str]] = None,
|
|
391
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
392
|
+
clock: Callable[[], float] = time.time,
|
|
393
|
+
reader: Optional[Callable[..., Optional[str]]] = None,
|
|
394
|
+
) -> str:
|
|
395
|
+
"""
|
|
396
|
+
The magic link sent since `since` to the login's mailbox, waiting for it up to the login's wait; a link in `used`
|
|
397
|
+
(opened already in this run) is skipped. Raises CodeError when none came; its message never holds a link.
|
|
398
|
+
"""
|
|
399
|
+
if src.kind != "email":
|
|
400
|
+
raise CodeError("a magic link is read from the login's mailbox: its code: settings must be email")
|
|
401
|
+
if not hosts:
|
|
402
|
+
raise CodeError("the login names no sites, so no link in a message could be trusted")
|
|
403
|
+
env = os.environ if env is None else env
|
|
404
|
+
deadline = clock() + src.wait
|
|
405
|
+
last: Optional[str] = None
|
|
406
|
+
while True:
|
|
407
|
+
try:
|
|
408
|
+
link = (reader or read_email_link)(src, since, env, hosts)
|
|
409
|
+
except CodeError:
|
|
410
|
+
raise
|
|
411
|
+
except Exception as ex:
|
|
412
|
+
last = type(ex).__name__
|
|
413
|
+
link = None
|
|
414
|
+
if link and link not in (used or []):
|
|
415
|
+
return link
|
|
416
|
+
if clock() >= deadline:
|
|
417
|
+
raise CodeError(f"No new link to the login's sites arrived in the mailbox on {src.host} within {src.wait} s" + (f" (the last try failed: {last})" if last else ""))
|
|
418
|
+
sleep(3)
|
|
@@ -46,7 +46,7 @@ async function start(line) {
|
|
|
46
46
|
const file = path.join(String(req.userDataDir), "DevToolsActivePort")
|
|
47
47
|
const until = Date.now() + 30000
|
|
48
48
|
while (!existsSync(file) && Date.now() < until) await new Promise((r) => setTimeout(r, 100))
|
|
49
|
-
const port = existsSync(file) ? Number(readFileSync(file, "utf8").split(/\r?\n/)[0]) : NaN
|
|
49
|
+
const port = existsSync(file) ? Number(readFileSync(file, "utf8").split(/\r?\n/)[0]) : Number.NaN
|
|
50
50
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("the browser started but wrote no DevTools port")
|
|
51
51
|
say({ port })
|
|
52
52
|
}
|
|
@@ -28,7 +28,7 @@ import secrets
|
|
|
28
28
|
import time
|
|
29
29
|
from pathlib import Path
|
|
30
30
|
from types import SimpleNamespace
|
|
31
|
-
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
|
|
31
|
+
from typing import Any, Awaitable, Callable, Dict, List, Optional, Set, Tuple
|
|
32
32
|
|
|
33
33
|
from .capture import capture_element, locate_check
|
|
34
34
|
from .network import NetworkCapture
|
|
@@ -45,6 +45,16 @@ def _utc_now() -> str:
|
|
|
45
45
|
|
|
46
46
|
logger = logging.getLogger("forgeqe_engine.record")
|
|
47
47
|
|
|
48
|
+
# Calls started and never awaited (a page's log line, a screencast frame's ack). The event loop keeps only a weak reference
|
|
49
|
+
# to a task, so one could be collected before it ran: each is held here until it is done.
|
|
50
|
+
_UNAWAITED: Set["asyncio.Future[Any]"] = set()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _unawaited(aw: Awaitable[Any]) -> None:
|
|
54
|
+
task = asyncio.ensure_future(aw)
|
|
55
|
+
_UNAWAITED.add(task)
|
|
56
|
+
task.add_done_callback(_UNAWAITED.discard)
|
|
57
|
+
|
|
48
58
|
Emit = Callable[[Dict[str, Any]], None]
|
|
49
59
|
|
|
50
60
|
CDP_TIMEOUT = 5.0
|
|
@@ -1513,7 +1523,7 @@ class RecordSession:
|
|
|
1513
1523
|
|
|
1514
1524
|
def _to_pages(self, expression: str) -> None:
|
|
1515
1525
|
for sid in list(self.pages):
|
|
1516
|
-
|
|
1526
|
+
_unawaited(self._page_call(sid, expression))
|
|
1517
1527
|
|
|
1518
1528
|
def _changed(self, msg: str) -> None:
|
|
1519
1529
|
rec = self.rec
|
|
@@ -1728,7 +1738,7 @@ class RecordSession:
|
|
|
1728
1738
|
ack = event.get("sessionId") if isinstance(event, dict) else None
|
|
1729
1739
|
if ack is not None and session_id:
|
|
1730
1740
|
try:
|
|
1731
|
-
|
|
1741
|
+
_unawaited(self.send("Page.screencastFrameAck", {"sessionId": ack}, session_id))
|
|
1732
1742
|
except RuntimeError:
|
|
1733
1743
|
pass
|
|
1734
1744
|
video = self.video
|
|
@@ -278,6 +278,25 @@ def auto_name(steps: List[Dict[str, Any]], start_url: str, limit: int = 4) -> st
|
|
|
278
278
|
return f"{host}: {' → '.join(seen[:limit])}{more}"
|
|
279
279
|
|
|
280
280
|
|
|
281
|
+
# How many of a step's locators the Recorder lists: the one a replay uses, and a few it falls back on.
|
|
282
|
+
VIEW_LOCATORS = 4
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def step_locators(step: Mapping[str, Any]) -> List[Dict[str, str]]:
|
|
286
|
+
"""
|
|
287
|
+
A step's locators as the Recorder lists them, best first: the Playwright expression a replay uses, then the other
|
|
288
|
+
ranked locators recorded for its element (role, test id, label, text, CSS…) by kind and value. Page text, as data.
|
|
289
|
+
"""
|
|
290
|
+
out: List[Dict[str, str]] = []
|
|
291
|
+
best = step.get("best_locator")
|
|
292
|
+
if isinstance(best, str) and best.strip():
|
|
293
|
+
out.append({"kind": "playwright", "value": best})
|
|
294
|
+
locs = [l for l in step.get("locators") or [] if isinstance(l, Mapping) and isinstance(l.get("type"), str) and isinstance(l.get("value"), str)]
|
|
295
|
+
for l in locs[1 if out else 0 :]:
|
|
296
|
+
out.append({"kind": str(l["type"]).replace("_", " "), "value": str(l["value"])})
|
|
297
|
+
return out[:VIEW_LOCATORS]
|
|
298
|
+
|
|
299
|
+
|
|
281
300
|
def describe(step: Dict[str, Any]) -> str:
|
|
282
301
|
"""One line for the step list in the Recorder and the terminal."""
|
|
283
302
|
op = step.get("op") or ""
|
|
@@ -937,6 +956,7 @@ class WebRecorder:
|
|
|
937
956
|
**({"inferred": True} if s.get("inferred") else {}),
|
|
938
957
|
**({"case_step": s["case_step"]} if s.get("case_step") else {}),
|
|
939
958
|
**({"generated": s["generated"]} if s.get("generated") else {}),
|
|
959
|
+
**({"locators": step_locators(s)} if step_locators(s) else {}),
|
|
940
960
|
}
|
|
941
961
|
for i, s in enumerate(self.steps)
|
|
942
962
|
]
|