@capagents/forgeqe 3.0.9 → 3.1.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 (188) hide show
  1. package/HOW_TO_USE.md +1 -1
  2. package/bin/bundle.js +3 -3
  3. package/bin/forgeqe.js +3 -3
  4. package/bin/license.js +1 -1
  5. package/dist/docs-site/CREDITS.md +11 -4
  6. package/dist/docs-site/LICENSE.dm-sans.txt +93 -0
  7. package/dist/docs-site/LICENSE.jetbrains-mono.txt +93 -0
  8. package/dist/docs-site/app-look.css +62 -0
  9. package/dist/docs-site/architecture-map/arch-fill.js +56 -0
  10. package/dist/docs-site/architecture-map/arch-theme.css +203 -0
  11. package/dist/docs-site/architecture-map/arch.css +0 -5
  12. package/dist/docs-site/architecture-map/index.html +57 -43
  13. package/dist/docs-site/docs/app-theme.css +166 -0
  14. package/dist/docs-site/docs/architecture/index.html +14 -11
  15. package/dist/docs-site/docs/containers/index.html +14 -11
  16. package/dist/docs-site/docs/cost-architecture/index.html +14 -11
  17. package/dist/docs-site/docs/custom-agents-first-run/index.html +14 -11
  18. package/dist/docs-site/docs/desktop/index.html +14 -11
  19. package/dist/docs-site/docs/desktop-ci/index.html +14 -11
  20. package/dist/docs-site/docs/docs.css +0 -7
  21. package/dist/docs-site/docs/evidence/index.html +14 -11
  22. package/dist/docs-site/docs/feature-test-prompts/index.html +14 -11
  23. package/dist/docs-site/docs/graphify/index.html +14 -11
  24. package/dist/docs-site/docs/guardrails/index.html +14 -11
  25. package/dist/docs-site/docs/index.html +71 -36
  26. package/dist/docs-site/docs/mobile/index.html +56 -18
  27. package/dist/docs-site/docs/model-routing/index.html +14 -11
  28. package/dist/docs-site/docs/product-graph/index.html +14 -11
  29. package/dist/docs-site/docs/product-knowledge/index.html +14 -11
  30. package/dist/docs-site/docs/product-views/index.html +14 -11
  31. package/dist/docs-site/docs/search.js +1 -1
  32. package/dist/docs-site/docs/web-app/index.html +14 -11
  33. package/dist/docs-site/img/wordmark.webp +0 -0
  34. package/dist/docs-site/site-header.css +0 -5
  35. package/dist/forgeqe.js +1784 -1784
  36. package/dist/template.html +14 -14
  37. package/dist/web/assets/{AgentWork-BhepbEeU.js → AgentWork-C3KdZh5M.js} +1 -1
  38. package/dist/web/assets/ApiTests-BLnl7JGO.js +10 -0
  39. package/dist/web/assets/Browse-C-Enjpmd.js +2 -0
  40. package/dist/web/assets/Chat-Bt6jZI68.js +3 -0
  41. package/dist/web/assets/Choices-D5eTFinz.js +3 -0
  42. package/dist/web/assets/{CommandPalette-DMAmXPq1.js → CommandPalette-D89NM2_E.js} +1 -1
  43. package/dist/web/assets/{Compare-DJNSrM2v.js → Compare-YfFYHwfK.js} +1 -1
  44. package/dist/web/assets/Cost-ClaDz0YR.js +1 -0
  45. package/dist/web/assets/{Data-COFRpcJn.js → Data-jSFgAfej.js} +4 -4
  46. package/dist/web/assets/Desktop-BofKeLVf.js +1 -0
  47. package/dist/web/assets/DesktopReview--WjeZh3w.js +1 -0
  48. package/dist/web/assets/Evidence-CJNzSQpY.js +1 -0
  49. package/dist/web/assets/{Explore-DDXgQj5Q.js → Explore-BdFvqgF4.js} +2 -2
  50. package/dist/web/assets/{Features-BM5iXhOR.js → Features-CIBbw6PG.js} +1 -1
  51. package/dist/web/assets/Flags-B62v4uWR.js +2 -0
  52. package/dist/web/assets/{Flaky-BqUHVLao.js → Flaky-Cut1kZw6.js} +1 -1
  53. package/dist/web/assets/{Impact-CA6s3POt.js → Impact-jOSl5Q0k.js} +3 -3
  54. package/dist/web/assets/{Jobs-B59p1qvn.js → Jobs-DMJGgWtQ.js} +2 -2
  55. package/dist/web/assets/KindPage-BbQWH5wa.js +6 -0
  56. package/dist/web/assets/{Migration-DtynahwR.js → Migration-BBgv7xXo.js} +2 -2
  57. package/dist/web/assets/PageAgent-txbNoP6u.js +1 -0
  58. package/dist/web/assets/{Product-wWMz2Nnk.js → Product-BrXH81Ns.js} +3 -3
  59. package/dist/web/assets/Production-CCVtFNGQ.js +1 -0
  60. package/dist/web/assets/Quality-Dxh-60A8.js +1 -0
  61. package/dist/web/assets/Readiness-DyJvSOLN.js +1 -0
  62. package/dist/web/assets/Record-Dnlkimjb.js +1 -0
  63. package/dist/web/assets/Regression-D2DDTwzs.js +5 -0
  64. package/dist/web/assets/{Reports-C-NSlVAn.js → Reports-ClcY7M0Q.js} +2 -2
  65. package/dist/web/assets/Response-D9FYUvHg.js +9 -0
  66. package/dist/web/assets/RunDiff-CNImaEdz.js +1 -0
  67. package/dist/web/assets/{Runs-DIDCOhbK.js → Runs-CFvmdULI.js} +2 -2
  68. package/dist/web/assets/{Steps-BOWDBzu4.js → Steps-BS66s0E1.js} +1 -1
  69. package/dist/web/assets/TestCases-CrQEUtfD.js +1 -0
  70. package/dist/web/assets/{TestData-kXWCn7uZ.js → TestData-e3IX0xwG.js} +2 -2
  71. package/dist/web/assets/TestDebt-tXPoexMF.js +1 -0
  72. package/dist/web/assets/TestManagement-wjGaoZzI.js +1 -0
  73. package/dist/web/assets/{Tosca-dhFuqYxV.js → Tosca-C5YaMLS0.js} +2 -2
  74. package/dist/web/assets/{WhatsNew-DpJWNec7.js → WhatsNew-CwnRbDnd.js} +1 -1
  75. package/dist/web/assets/azuredevops-BcQ5AFOM.js +1 -0
  76. package/dist/web/assets/crew-CWfjZIxE.js +1 -0
  77. package/dist/web/assets/{fold-BRxvbN9r.js → fold-tvLGnxD1.js} +1 -1
  78. package/dist/web/assets/frame-Deu1IqzV.js +13 -0
  79. package/dist/web/assets/index-BWMIKyPB.js +76 -0
  80. package/dist/web/assets/index-C2Yq55oT.css +2 -0
  81. package/dist/web/assets/logos-C1NBtBMc.js +1 -0
  82. package/dist/web/assets/logos-DFyhMw0i.js +1 -0
  83. package/dist/web/assets/{markdown-CWisJbSJ.js → markdown-DC2HA0yZ.js} +1 -1
  84. package/dist/web/assets/paletteCommands-Qxm5DZIs.js +1 -0
  85. package/dist/web/assets/parts-BR6dUwqn.js +1 -0
  86. package/dist/web/assets/qualityParts-lz6eYVxC.js +1 -0
  87. package/dist/web/assets/today-DuQFapJM.js +1 -0
  88. package/dist/web/assets/when-CHnpLdYw.js +1 -0
  89. package/dist/web/index.html +10 -4
  90. package/docs/ForgeQE-Client-Overview.pdf +0 -0
  91. package/docs/ForgeQE-Installation-Guide.pdf +0 -0
  92. package/docs/MOBILE.md +42 -7
  93. package/docs/user-guide.html +1 -1
  94. package/package.json +1 -1
  95. package/prompts/brain.md +1 -0
  96. package/py/forgeqe_data/connect.py +3 -1
  97. package/py/forgeqe_data/flows.py +1 -1
  98. package/py/forgeqe_data/service.py +1 -1
  99. package/py/forgeqe_data/streams.py +1 -1
  100. package/py/forgeqe_data/testdata.py +1 -1
  101. package/py/forgeqe_desktop/replay.py +43 -1
  102. package/py/forgeqe_desktop/service.py +2 -0
  103. package/py/forgeqe_desktop/workflow.py +77 -15
  104. package/py/forgeqe_engine/brand.py +1 -1
  105. package/py/forgeqe_engine/browser.py +2 -1
  106. package/py/forgeqe_engine/diagnostics.py +1 -1
  107. package/py/forgeqe_engine/memory.py +2 -1
  108. package/py/forgeqe_engine/neutral_log.py +1 -1
  109. package/py/forgeqe_engine/otp.py +127 -12
  110. package/py/forgeqe_engine/pwlaunch.mjs +1 -1
  111. package/py/forgeqe_engine/recordsession.py +13 -3
  112. package/py/forgeqe_engine/webrecord.py +20 -0
  113. package/py/forgeqe_mobile/appium_driver.py +225 -10
  114. package/py/forgeqe_mobile/locators.py +277 -0
  115. package/py/forgeqe_mobile/maestro.py +28 -1
  116. package/py/forgeqe_mobile/magiclink.py +79 -0
  117. package/py/forgeqe_mobile/record.py +284 -67
  118. package/py/forgeqe_mobile/service.py +9 -0
  119. package/py/forgeqe_mobile/webview.py +142 -0
  120. package/py/forgeqe_tosca/ntir.py +45 -6
  121. package/dist/docs-site/LICENSE.ubuntu.txt +0 -96
  122. package/dist/docs-site/img/icons/api.svg +0 -1
  123. package/dist/docs-site/img/icons/architecture.svg +0 -1
  124. package/dist/docs-site/img/icons/branch.svg +0 -1
  125. package/dist/docs-site/img/icons/browser-agent.svg +0 -1
  126. package/dist/docs-site/img/icons/case.svg +0 -1
  127. package/dist/docs-site/img/icons/container.svg +0 -1
  128. package/dist/docs-site/img/icons/context-engine.svg +0 -1
  129. package/dist/docs-site/img/icons/desktop.svg +0 -1
  130. package/dist/docs-site/img/icons/download.svg +0 -1
  131. package/dist/docs-site/img/icons/explorer.svg +0 -1
  132. package/dist/docs-site/img/icons/feature.svg +0 -1
  133. package/dist/docs-site/img/icons/healer.svg +0 -1
  134. package/dist/docs-site/img/icons/knowledge-base.svg +0 -1
  135. package/dist/docs-site/img/icons/mail.svg +0 -1
  136. package/dist/docs-site/img/icons/mobile.svg +0 -1
  137. package/dist/docs-site/img/icons/model.svg +0 -1
  138. package/dist/docs-site/img/icons/network.svg +0 -1
  139. package/dist/docs-site/img/icons/orchestrator.svg +0 -1
  140. package/dist/docs-site/img/icons/plug.svg +0 -1
  141. package/dist/docs-site/img/icons/pr-reviewer.svg +0 -1
  142. package/dist/docs-site/img/icons/replay.svg +0 -1
  143. package/dist/docs-site/img/icons/report.svg +0 -1
  144. package/dist/docs-site/img/icons/result.svg +0 -1
  145. package/dist/docs-site/img/icons/rule.svg +0 -1
  146. package/dist/docs-site/img/icons/scribe.svg +0 -1
  147. package/dist/docs-site/img/icons/shield.svg +0 -1
  148. package/dist/docs-site/img/icons/specs.svg +0 -1
  149. package/dist/docs-site/img/icons/speed.svg +0 -1
  150. package/dist/docs-site/img/icons/stories.svg +0 -1
  151. package/dist/docs-site/img/icons/terminal.svg +0 -1
  152. package/dist/docs-site/img/icons/test-finder.svg +0 -1
  153. package/dist/docs-site/img/icons/visual.svg +0 -1
  154. package/dist/docs-site/img/icons/web.svg +0 -1
  155. package/dist/docs-site/img/icons/wikis.svg +0 -1
  156. package/dist/web/assets/Agent-MlW7cfAm.js +0 -7
  157. package/dist/web/assets/ApiTests-mxUkUZvv.js +0 -10
  158. package/dist/web/assets/Browse-DENLuv4C.js +0 -2
  159. package/dist/web/assets/Chat-jxak1jci.js +0 -3
  160. package/dist/web/assets/Cost-CEOZgbPs.js +0 -1
  161. package/dist/web/assets/Desktop-DGNdy7iS.js +0 -1
  162. package/dist/web/assets/DesktopReview-SdAwvi9y.js +0 -1
  163. package/dist/web/assets/Evidence-DTrdEz3M.js +0 -1
  164. package/dist/web/assets/Flags-CkKp4bbv.js +0 -2
  165. package/dist/web/assets/KindPage-DPADNnwH.js +0 -6
  166. package/dist/web/assets/PageAgent-CB8HtdGd.js +0 -1
  167. package/dist/web/assets/Production-Nst6__N7.js +0 -1
  168. package/dist/web/assets/Quality-DgNo4H0u.js +0 -1
  169. package/dist/web/assets/Readiness--GiTxFZo.js +0 -1
  170. package/dist/web/assets/Record-a4whC1jV.js +0 -1
  171. package/dist/web/assets/Regression-hesOlN4G.js +0 -5
  172. package/dist/web/assets/RelationGraph-C3Re0M1N.js +0 -1
  173. package/dist/web/assets/Response-CzX2rQEZ.js +0 -9
  174. package/dist/web/assets/RunDiff-CIdQD95y.js +0 -1
  175. package/dist/web/assets/TestCases-D-ZRb2N7.js +0 -1
  176. package/dist/web/assets/TestDebt-BvP3w7ye.js +0 -1
  177. package/dist/web/assets/TestManagement-CphGo9DZ.js +0 -1
  178. package/dist/web/assets/agentTabs-BO5l3zw2.js +0 -1
  179. package/dist/web/assets/dataParts-DeUdfjjv.js +0 -3
  180. package/dist/web/assets/diff-D1_Qo2h1.js +0 -2
  181. package/dist/web/assets/frame-VTMu7MoC.js +0 -13
  182. package/dist/web/assets/index-CKRa-K2y.css +0 -2
  183. package/dist/web/assets/index-nuLrB-Rb.js +0 -69
  184. package/dist/web/assets/logos-J6txZkKc.js +0 -1
  185. package/dist/web/assets/paletteCommands-BmYmp6YY.js +0 -1
  186. package/dist/web/assets/parts-CDBCk_Xz.js +0 -1
  187. package/dist/web/assets/qualityParts-CGKSK9Dq.js +0 -1
  188. package/dist/web/assets/rows-yPc39hV7.js +0 -1
@@ -19,6 +19,7 @@ from __future__ import annotations
19
19
  import base64
20
20
  import hashlib
21
21
  import json
22
+ import re
22
23
  import socket
23
24
  import time
24
25
  import urllib.error
@@ -43,6 +44,10 @@ class AppiumError(RuntimeError):
43
44
  """The Appium server refused a command or could not be reached; the message says which."""
44
45
 
45
46
 
47
+ # Appium's name for the app's own screen, as opposed to a web page inside it (WEBVIEW_…).
48
+ NATIVE = "NATIVE_APP"
49
+
50
+
46
51
  def xpath_literal(value: str) -> str:
47
52
  """``value`` as an XPath 1.0 string literal, whatever quotes it holds."""
48
53
  if "'" not in value:
@@ -54,7 +59,73 @@ def xpath_literal(value: str) -> str:
54
59
 
55
60
 
56
61
  def target_xpath(target: Mapping[str, Any], platform: str) -> str:
57
- """The XPath for a target's properties on ``platform``: every given property must match."""
62
+ """
63
+ The XPath for a target's properties on ``platform``: every given property must match. A target ``within`` an
64
+ anchor (an ancestor named by its id or text) is a relative path below it, never one from the screen's root.
65
+ """
66
+ anchor = target.get("within")
67
+ if isinstance(anchor, Mapping) and anchor:
68
+ inner = {k: v for k, v in target.items() if k not in ("within", "fallbacks", "index")}
69
+ # //*[anchor]//*[control]: any depth below the anchor.
70
+ return _target_conds_xpath(anchor, platform) + _target_conds_xpath(inner, platform)
71
+ return _target_conds_xpath(target, platform)
72
+
73
+
74
+ def _java_string(value: str) -> str:
75
+ """``value`` as a Java string literal for a UiSelector (UiAutomator parses the selector as Java)."""
76
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
77
+
78
+
79
+ def _predicate_string(value: str) -> str:
80
+ """``value`` as an NSPredicate string literal for XCUITest."""
81
+ return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
82
+
83
+
84
+ def locator_query(target: Mapping[str, Any], platform: str) -> Tuple[str, str]:
85
+ """
86
+ How Appium is asked for a target, as (strategy, value): the platform's own fast strategies where they say exactly
87
+ what the target means, XPath otherwise.
88
+
89
+ - iOS: an identifier alone is ``accessibility id``; an identifier, a label and a type are an ``-ios predicate
90
+ string`` (on screen only, as the XPath is);
91
+ - Android: a resource id alone is an ``-android uiautomator`` UiSelector (its package left open, as the XPath's);
92
+ a text, which matches the text or the accessibility label, stays XPath;
93
+ - a place among several (``index``) or an anchor (``within``) is XPath.
94
+
95
+ Every value is quoted for its query language here, so a control's text can never change the query's shape.
96
+ """
97
+ if isinstance(target.get("web"), Mapping):
98
+ # An element of a web page inside the app: CSS or XPath built from its checked properties (webview.py).
99
+ from .webview import web_query
100
+
101
+ return web_query(target["web"])
102
+ keys = {k for k, v in target.items() if v not in (None, "") and k != "fallbacks"}
103
+ aid, name, kind = target.get("automation_id"), target.get("name"), target.get("control_type")
104
+ if "index" not in keys and "within" not in keys:
105
+ if platform == "ios":
106
+ if keys == {"automation_id"}:
107
+ return ("accessibility id", str(aid))
108
+ if keys and keys <= {"automation_id", "name", "control_type"}:
109
+ conds = ["visible == 1"]
110
+ if aid:
111
+ conds.append(f"name == {_predicate_string(str(aid))}")
112
+ if name:
113
+ lit = _predicate_string(str(name))
114
+ conds.append(f"(label == {lit} OR name == {lit} OR value == {lit})")
115
+ if kind:
116
+ conds.append(f"type == {_predicate_string(str(kind))}")
117
+ return ("-ios predicate string", " AND ".join(conds))
118
+ elif keys == {"automation_id"} and re.fullmatch(r"[A-Za-z0-9_.]+", str(aid)):
119
+ # A Java regex inside a Java string: an id is letters, digits, _ and . only, the dots escaped.
120
+ pattern = "(.+:id/)?" + str(aid).replace(".", "\\\\.")
121
+ return ("-android uiautomator", f"new UiSelector().resourceIdMatches(\"{pattern}\")")
122
+ elif keys == {"automation_id", "control_type"} and re.fullmatch(r"[A-Za-z0-9_.]+", str(aid)):
123
+ pattern = "(.+:id/)?" + str(aid).replace(".", "\\\\.")
124
+ return ("-android uiautomator", f"new UiSelector().resourceIdMatches(\"{pattern}\").className({_java_string(str(kind))})")
125
+ return ("xpath", target_xpath(target, platform))
126
+
127
+
128
+ def _target_conds_xpath(target: Mapping[str, Any], platform: str) -> str:
58
129
  conds: List[str] = []
59
130
  aid = target.get("automation_id")
60
131
  name = target.get("name")
@@ -217,6 +288,10 @@ class AppiumDriver:
217
288
  self.auth = "Basic " + base64.b64encode(f"{username}:{access_key}".encode()).decode() if username and access_key else None
218
289
  self.command_timeout = command_timeout
219
290
  self.poll = poll
291
+ # Which of a target's locators found it last (0 its own, n its n-th fallback).
292
+ self.found_by = 0
293
+ # The context commands go to: the app's own screen, or a web page inside it (webview.py).
294
+ self.context = NATIVE
220
295
  self.open = opener or urllib.request.urlopen
221
296
  self.session: Optional[str] = None
222
297
  self.screen_digest: Optional[str] = None
@@ -281,6 +356,57 @@ class AppiumDriver:
281
356
 
282
357
  # -- Driver ---------------------------------------------------------------------------------------------------
283
358
 
359
+ # -- contexts: the app's screen, or a web page inside it -------------------------------------------------------
360
+
361
+ def _use(self, name: str) -> None:
362
+ if self.context != name:
363
+ self._call("POST", self._s("/context"), {"name": name})
364
+ self.context = name
365
+
366
+ def _native(self) -> None:
367
+ """The app's own screen: what a screenshot, the page source, a key, Back or a swipe across the screen need."""
368
+ if self.context != NATIVE:
369
+ self._use(NATIVE)
370
+
371
+ def webview(self) -> Optional[str]:
372
+ """The app's web page Appium can reach (WEBVIEW_…, the app's own first), or None when there is none (its web
373
+ debugging is off in this build, or no page is open)."""
374
+ names = self._call("GET", self._s("/contexts")) or []
375
+ webs = [n for n in names if isinstance(n, str) and n.startswith("WEBVIEW") and len(n) <= 200]
376
+ app_id = getattr(getattr(self, "app", None), "app_id", "") or ""
377
+ mine = [n for n in webs if app_id and app_id in n]
378
+ return (mine or webs or [None])[0]
379
+
380
+ def _context_for(self, target: Mapping[str, Any]) -> bool:
381
+ """Switch to where the target is looked for; False when it is a web element and no web page can be reached."""
382
+ if isinstance(target.get("web"), Mapping):
383
+ web = self.webview()
384
+ if web is None:
385
+ return False
386
+ self._use(web)
387
+ else:
388
+ self._native()
389
+ return True
390
+
391
+ def web_locators(self, fx: float, fy: float) -> List[Dict[str, str]]:
392
+ """
393
+ The web page's element at a spot (fractions of the page's width and height) and the locators that find only
394
+ it, best first; the page's answer read as untrusted (webview.web_candidates). Back on the app's screen after.
395
+ """
396
+ from .webview import LOCATE_SCRIPT, web_candidates
397
+
398
+ if not (0 <= fx <= 1 and 0 <= fy <= 1):
399
+ return []
400
+ web = self.webview()
401
+ if web is None:
402
+ raise AppiumError("no web page in the app can be read: its web debugging is off in this build, or none is open")
403
+ try:
404
+ self._use(web)
405
+ answer = self._call("POST", self._s("/execute/sync"), {"script": LOCATE_SCRIPT, "args": [float(fx), float(fy)]})
406
+ finally:
407
+ self._native()
408
+ return web_candidates(answer)
409
+
284
410
  def launch(self, app: MobileAppSpec, timeout: Optional[float] = None) -> None:
285
411
  self.app = app
286
412
  self.platform = app.platform
@@ -324,20 +450,39 @@ class AppiumDriver:
324
450
  if not isinstance(session, str) or not session:
325
451
  raise AppiumError("Appium started no session")
326
452
  self.session = session
453
+ self.context = NATIVE
327
454
 
328
455
  def find(self, target: Mapping[str, Any], timeout: float) -> Any:
329
- xpath = target_xpath(target, self.platform)
330
- index = int(target.get("index", 0) or 0)
456
+ """
457
+ The control: the target's own locator first, then each of its ``fallbacks`` in order, every round until
458
+ ``timeout``. ``found_by`` says which found it (0 its own, 1 its first fallback, …), for the replay's report.
459
+ """
460
+ from .locators import tried
461
+
462
+ targets = tried(target)
463
+ queries = [(locator_query(t, self.platform), int(t.get("index", 0) or 0)) for t in targets]
331
464
  deadline = time.time() + timeout
332
465
  while True:
333
- found = self._call("POST", self._s("/elements"), {"using": "xpath", "value": xpath}) or []
334
- if isinstance(found, list) and len(found) > index:
335
- el = found[index]
336
- if isinstance(el, dict):
337
- ref = el.get("element-6066-11e4-a52e-4f735466cecf") or el.get("ELEMENT")
338
- if isinstance(ref, str):
339
- return ref
466
+ refused: Optional[AppiumError] = None
467
+ for n, ((using, value), index) in enumerate(queries):
468
+ try:
469
+ if not self._context_for(targets[n]):
470
+ continue
471
+ found = self._call("POST", self._s("/elements"), {"using": using, "value": value}) or []
472
+ except AppiumError as e:
473
+ # A strategy the server refuses (an old driver without it) is one locator failing: the next is tried.
474
+ refused = e
475
+ continue
476
+ if isinstance(found, list) and len(found) > index:
477
+ el = found[index]
478
+ if isinstance(el, dict):
479
+ ref = el.get("element-6066-11e4-a52e-4f735466cecf") or el.get("ELEMENT")
480
+ if isinstance(ref, str):
481
+ self.found_by = n
482
+ return ref
340
483
  if time.time() >= deadline:
484
+ if refused is not None and len(queries) == 1:
485
+ raise refused
341
486
  raise ControlNotFound(f"no control matches {dict(target)}")
342
487
  time.sleep(self.poll)
343
488
 
@@ -356,12 +501,48 @@ class AppiumDriver:
356
501
  def click(self, control: Any, double: bool = False) -> None:
357
502
  if not double:
358
503
  self._call("POST", self._s(f"/element/{control}/click"))
504
+ elif self.context != NATIVE:
505
+ # A web page's element: the native gestures take only the app's own elements, so two taps at its centre.
506
+ self.tap_point(control, [500, 500], double=True)
359
507
  elif self.platform == "android":
360
508
  self._script("mobile: doubleClickGesture", {"elementId": control})
361
509
  else:
362
510
  self._script("mobile: doubleTap", {"elementId": control})
363
511
 
512
+ def open_link(self, url: str) -> None:
513
+ """
514
+ A link opened on the device for the app under test, as a tap on it in a mail would (Android's VIEW intent for
515
+ the app's package, iOS's deep link for its bundle). Only an https link; never logged.
516
+ """
517
+ if not isinstance(url, str) or not url.lower().startswith("https://") or any(ord(c) < 33 for c in url):
518
+ raise AppiumError("only an https link is opened on the device")
519
+ app_id = getattr(getattr(self, "app", None), "app_id", "") or ""
520
+ self._native()
521
+ if self.platform == "android":
522
+ self._script("mobile: deepLink", {"url": url, **({"package": app_id} if app_id else {}), "waitForLaunch": True})
523
+ else:
524
+ self._script("mobile: deepLink", {"url": url, **({"bundleId": app_id} if app_id else {})})
525
+
526
+ def tap_point(self, control: Any, at: List[int], double: bool = False, hold: bool = False) -> None:
527
+ """A tap (or two, or a press held a second) at ``at`` inside the control: thousandths of its width and height."""
528
+ r = self._area(control)
529
+ if r["width"] <= 0 or r["height"] <= 0:
530
+ raise AppiumError("the control to tap inside has no size")
531
+ x = r["x"] + min(r["width"] - 1, r["width"] * int(at[0]) // 1000)
532
+ y = r["y"] + min(r["height"] - 1, r["height"] * int(at[1]) // 1000)
533
+ press = [{"type": "pointerDown", "button": 0}, {"type": "pause", "duration": 1000 if hold else 80}, {"type": "pointerUp", "button": 0}]
534
+ finger = [{"type": "pointerMove", "duration": 0, "x": x, "y": y}, *press, *([{"type": "pause", "duration": 100}, *press] if double else [])]
535
+ self._call("POST", self._s("/actions"), {"actions": [{"type": "pointer", "id": "finger1", "parameters": {"pointerType": "touch"}, "actions": finger}]})
536
+ try:
537
+ self._call("DELETE", self._s("/actions"))
538
+ except (AppiumError, ControlNotFound):
539
+ pass
540
+
364
541
  def long_press(self, control: Any) -> None:
542
+ if self.context != NATIVE:
543
+ # A web page's element: a press held at its centre (the native gestures take only the app's own elements).
544
+ self.tap_point(control, [500, 500], hold=True)
545
+ return
365
546
  if self.platform == "android":
366
547
  self._script("mobile: longClickGesture", {"elementId": control, "duration": 1000})
367
548
  else:
@@ -372,9 +553,33 @@ class AppiumDriver:
372
553
  self._call("POST", self._s(f"/element/{control}/value"), {"text": text, "value": list(text)})
373
554
 
374
555
  def select(self, control: Any, value: str) -> None:
556
+ """
557
+ A drop-down or menu: opened, then its item that shows ``value`` tapped. An iOS picker wheel is turned to
558
+ ``value`` instead (XCUITest sets a wheel by the value sent to it).
559
+ """
560
+ if self.platform == "ios" and self._call("GET", self._s(f"/element/{control}/attribute/type")) == "XCUIElementTypePickerWheel":
561
+ self._call("POST", self._s(f"/element/{control}/value"), {"text": value})
562
+ return
375
563
  self.click(control)
376
564
  self.click(self.find({"name": value}, 10))
377
565
 
566
+ def is_checked(self, control: Any) -> bool:
567
+ """
568
+ Whether a checkbox, switch or radio button is on: Android's ``checked``; iOS's ``value`` (a switch says 1 or
569
+ 0) or, for a cell or button, whether it is ``selected``.
570
+ """
571
+ if self.context != NATIVE:
572
+ # A web page's checkbox or radio button: WebDriver's own "is it selected".
573
+ return bool(self._call("GET", self._s(f"/element/{control}/selected")))
574
+ if self.platform == "android":
575
+ return str(self._call("GET", self._s(f"/element/{control}/attribute/checked")) or "").lower() == "true"
576
+ value = str(self._call("GET", self._s(f"/element/{control}/attribute/value")) or "").strip().lower()
577
+ if value in ("1", "true", "on"):
578
+ return True
579
+ if value in ("0", "false", "off"):
580
+ return False
581
+ return bool(self._call("GET", self._s(f"/element/{control}/selected")))
582
+
378
583
  def text_of(self, control: Any) -> str:
379
584
  texts = [str(self._call("GET", self._s(f"/element/{control}/text")) or "")]
380
585
  for attr in (("content-desc",) if self.platform == "android" else ("label", "value")):
@@ -387,6 +592,7 @@ class AppiumDriver:
387
592
  return "\n".join(t for t in texts if t)
388
593
 
389
594
  def press_key(self, key: str) -> None:
595
+ self._native()
390
596
  if self.platform == "android":
391
597
  self._script("mobile: pressKey", {"keycode": ANDROID_KEYCODES[key]})
392
598
  elif key == "enter":
@@ -395,9 +601,11 @@ class AppiumDriver:
395
601
  raise AppiumError(f"the {key} key does not exist on iOS")
396
602
 
397
603
  def back(self) -> None:
604
+ self._native()
398
605
  self._call("POST", self._s("/back"))
399
606
 
400
607
  def hide_keyboard(self) -> None:
608
+ self._native()
401
609
  try:
402
610
  self._call("POST", self._s("/appium/device/hide_keyboard"))
403
611
  except AppiumError:
@@ -441,6 +649,8 @@ class AppiumDriver:
441
649
 
442
650
  def swipe(self, direction: str, control: Any = None) -> None:
443
651
  """A finger swipe in ``direction`` (on the control, or across the screen)."""
652
+ if control is None:
653
+ self._native()
444
654
  if self.platform == "android":
445
655
  # A finger drag: Android's swipeGesture is a fling that a React Native carousel ignores on a real device.
446
656
  self._drag(direction, self._area(control), 0.7, 400)
@@ -491,6 +701,8 @@ class AppiumDriver:
491
701
  def scroll(self, direction: str, control: Any = None) -> None:
492
702
  """Move the content (of the control, or of the screen's scrolling view) so that what is further ``direction``
493
703
  (down: further down the page) comes into view."""
704
+ if control is None:
705
+ self._native()
494
706
  finger = {"down": "up", "up": "down", "left": "right", "right": "left"}.get(direction)
495
707
  if not finger:
496
708
  raise AppiumError(f"a scroll goes up, down, left or right, not {direction!r}")
@@ -551,14 +763,17 @@ class AppiumDriver:
551
763
 
552
764
  def source(self) -> str:
553
765
  """The screen's page source (XML), as Appium gives it: the app's own text, so data."""
766
+ self._native()
554
767
  source = self._call("GET", self._s("/source")) or ""
555
768
  return source if isinstance(source, str) else ""
556
769
 
557
770
  def window_size(self) -> Dict[str, int]:
771
+ self._native()
558
772
  r = self._call("GET", self._s("/window/rect")) or {}
559
773
  return {"width": int(r.get("width", 0)), "height": int(r.get("height", 0))} if isinstance(r, dict) else {"width": 0, "height": 0}
560
774
 
561
775
  def screenshot_png(self) -> Optional[bytes]:
776
+ self._native()
562
777
  if not self.session:
563
778
  return None
564
779
  try:
@@ -0,0 +1,277 @@
1
+ """
2
+ How a mobile recording finds a control again, chosen the way Playwright ranks a web page's locators: what the app's
3
+ developers named for tests and accessibility first, then what the control is and says, and a path only when nothing
4
+ else tells it apart.
5
+
6
+ For each control on the screen, ``locate`` lists candidate targets in this order and keeps only those that match
7
+ exactly that one control on the screen now (``count``), so every kept locator is proven unique where it was recorded:
8
+
9
+ - Android: its resource id (the app's own test id), its accessibility label (content-desc), its id with its text (rows
10
+ of a list share an id), its role (class) with its text, its text;
11
+ - iOS: its accessibility identifier, its role (type) with its label, its label.
12
+
13
+ A field's text (a hint now, what is typed later) and a text that reads as data (``varies``: long, or mostly digits, like
14
+ a price, a date or an order number) come last. When no candidate is unique alone, the nearest ancestor with a unique id
15
+ anchors it (``within``: a relative path, never one from the screen's root). When even that fails, the best candidate
16
+ with its place among those it matches (``index``) is the last resort.
17
+
18
+ The first kept candidate is the step's target; up to ``MAX_FALLBACKS`` more go in its ``fallbacks``, which a replay
19
+ tries in order when the first finds nothing (``appium_driver.find``). Every value is the app's text, read as data: a
20
+ target holds plain properties only and the driver builds each query from them, quoting every value
21
+ (``appium_driver.locator_query``).
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import re
26
+ import xml.etree.ElementTree as ET
27
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple
28
+
29
+ # A target's alternatives a replay tries after it: enough to survive a renamed id or a changed text, few enough to read.
30
+ MAX_FALLBACKS = 3
31
+ # A name longer than this is a paragraph, never a locator.
32
+ MAX_LOCATOR_NAME = 300
33
+ # A text this long, or this share digits, reads as data that changes between runs.
34
+ VARIES_LENGTH = 60
35
+ VARIES_DIGITS = 0.5
36
+ _CONTROL_CHARS = re.compile(r"[\u0000-\u001f\u007f]")
37
+ _ANCHOR_KEYS = ("automation_id", "name")
38
+
39
+
40
+ def _plain(value: Any) -> Optional[str]:
41
+ """A value fit for a locator: one line of text, not a paragraph; else None."""
42
+ if not isinstance(value, str):
43
+ return None
44
+ v = value.strip()
45
+ if not v or len(v) > MAX_LOCATOR_NAME or _CONTROL_CHARS.search(v):
46
+ return None
47
+ return v
48
+
49
+
50
+ def varies(text: str) -> bool:
51
+ """Whether a text reads as data that changes between runs (a price, a date, an order number, a sentence)."""
52
+ t = text.strip()
53
+ if len(t) > VARIES_LENGTH:
54
+ return True
55
+ digits = sum(c.isdigit() for c in t)
56
+ return digits >= 3 and digits / max(1, len([c for c in t if not c.isspace()])) >= VARIES_DIGITS
57
+
58
+
59
+ def _attrs(node: ET.Element, platform: str) -> Dict[str, str]:
60
+ """The node's properties a locator can use: id, accessibility label, text and role."""
61
+ a = node.attrib
62
+ if platform == "android":
63
+ rid = a.get("resource-id", "")
64
+ return {
65
+ k: v
66
+ for k, v in {
67
+ "id": rid.split(":id/", 1)[1] if ":id/" in rid else rid,
68
+ "desc": a.get("content-desc", ""),
69
+ "text": a.get("text", ""),
70
+ "role": a.get("class") or node.tag,
71
+ }.items()
72
+ if v
73
+ }
74
+ name, label = a.get("name", ""), a.get("label", "")
75
+ return {
76
+ k: v
77
+ for k, v in {
78
+ # The accessibility identifier: XCUITest gives the label as the name when there is none, so it is an id
79
+ # only when it differs from the label.
80
+ "id": name if name and name != label else "",
81
+ # Its label only: with no label, the name is the identifier, not a text it shows.
82
+ "label": label,
83
+ "role": a.get("type") or node.tag,
84
+ }.items()
85
+ if v
86
+ }
87
+
88
+
89
+ def candidates(node: ET.Element, platform: str, field: bool = False) -> List[Dict[str, Any]]:
90
+ """The node's candidate targets, best first (see the module's note); none unique-checked yet."""
91
+ at = _attrs(node, platform)
92
+ out: List[Dict[str, Any]] = []
93
+ late: List[Dict[str, Any]] = []
94
+
95
+ def add(target: Dict[str, Optional[str]], *, text: str = "") -> None:
96
+ if not all(_plain(v) for v in target.values()):
97
+ return
98
+ t = {k: str(v).strip() for k, v in target.items()}
99
+ if t in out or t in late:
100
+ return
101
+ # A field's text is a hint now and what is typed later; a text of data changes: both are tried last.
102
+ (late if text and (field or varies(text)) else out).append(t)
103
+
104
+ if platform == "android":
105
+ # Android's own ids (android:id/button1 on every dialog's OK, android:id/text1 on every list row) name the
106
+ # framework's layout, not the app's control: what the control says comes first, the id after it.
107
+ generic = node.attrib.get("resource-id", "").startswith("android:id/")
108
+ if at.get("id") and not generic:
109
+ add({"automation_id": at["id"]})
110
+ if at.get("desc"):
111
+ add({"name": at["desc"]})
112
+ if at.get("id") and at.get("text") and not generic:
113
+ add({"automation_id": at["id"], "name": at["text"]}, text=at["text"])
114
+ if at.get("text") and at.get("role"):
115
+ add({"name": at["text"], "control_type": at["role"]}, text=at["text"])
116
+ if at.get("text"):
117
+ add({"name": at["text"]}, text=at["text"])
118
+ if at.get("id") and generic:
119
+ add({"automation_id": at["id"]})
120
+ else:
121
+ if at.get("id"):
122
+ add({"automation_id": at["id"]})
123
+ if at.get("label") and at.get("role"):
124
+ add({"name": at["label"], "control_type": at["role"]}, text=at["label"])
125
+ if at.get("label"):
126
+ add({"name": at["label"]}, text=at["label"])
127
+ if field and out:
128
+ # A field found by its id never falls back to its text: that is a hint now and what is typed later.
129
+ return out
130
+ return out + late
131
+
132
+
133
+ def matches(node: ET.Element, target: Mapping[str, Any], platform: str) -> bool:
134
+ """Whether ``node`` is one the target's query finds (``appium_driver.locator_query``), from its attributes."""
135
+ a = node.attrib
136
+ aid, name, kind = target.get("automation_id"), target.get("name"), target.get("control_type")
137
+ if platform == "android":
138
+ rid = a.get("resource-id", "")
139
+ if aid and not (rid == aid or rid.endswith(":id/" + str(aid))):
140
+ return False
141
+ if name and name not in (a.get("text"), a.get("content-desc")):
142
+ return False
143
+ return not kind or (a.get("class") or node.tag) == kind
144
+ if a.get("visible") == "false":
145
+ return False
146
+ if aid and a.get("name") != aid:
147
+ return False
148
+ if name and name not in (a.get("label"), a.get("name"), a.get("value")):
149
+ return False
150
+ return not kind or (a.get("type") or node.tag) == kind
151
+
152
+
153
+ def parents_of(root: ET.Element) -> Dict[ET.Element, ET.Element]:
154
+ return {child: parent for parent in root.iter() for child in parent}
155
+
156
+
157
+ def _ancestors(node: ET.Element, parents: Mapping[ET.Element, ET.Element]) -> Iterable[ET.Element]:
158
+ p = parents.get(node)
159
+ while p is not None:
160
+ yield p
161
+ p = parents.get(p)
162
+
163
+
164
+ class ScreenIndex:
165
+ """
166
+ The screen's controls by id and by text, in document order, built once per screen read: a count looks only at the
167
+ controls that could match, not at every control for every candidate of every control.
168
+ """
169
+
170
+ def __init__(self, nodes: List[ET.Element], platform: str) -> None:
171
+ self.pos = {n: i for i, n in enumerate(nodes)}
172
+ self.by_id: Dict[str, List[ET.Element]] = {}
173
+ self.by_name: Dict[str, List[ET.Element]] = {}
174
+ for n in nodes:
175
+ a = n.attrib
176
+ if platform == "android":
177
+ rid = a.get("resource-id", "")
178
+ ids = {rid, rid.split(":id/", 1)[1]} if ":id/" in rid else {rid}
179
+ names = {a.get("text", ""), a.get("content-desc", "")}
180
+ else:
181
+ ids = {a.get("name", "")}
182
+ names = {a.get("label", ""), a.get("name", ""), a.get("value", "")}
183
+ for k in ids - {""}:
184
+ self.by_id.setdefault(k, []).append(n)
185
+ for k in names - {""}:
186
+ self.by_name.setdefault(k, []).append(n)
187
+
188
+ def pool(self, target: Mapping[str, Any]) -> Optional[List[ET.Element]]:
189
+ """The controls a target could match (a superset, in document order), or None for all of them."""
190
+ if target.get("automation_id"):
191
+ return self.by_id.get(str(target["automation_id"]), [])
192
+ if target.get("name"):
193
+ return self.by_name.get(str(target["name"]), [])
194
+ return None
195
+
196
+
197
+ def count(target: Mapping[str, Any], nodes: List[ET.Element], parents: Mapping[ET.Element, ET.Element], platform: str, before: Optional[ET.Element] = None, index: Optional[ScreenIndex] = None) -> int:
198
+ """How many controls the target matches (inside its anchor, when it has one), or only those before ``before``."""
199
+ anchor = target.get("within")
200
+ pool = index.pool(target) if index is not None else None
201
+ stop = index.pos.get(before) if index is not None and before is not None else None
202
+ if pool is None or (before is not None and stop is None):
203
+ pool, stop = nodes, None
204
+ n = 0
205
+ for other in pool:
206
+ if other is before or (stop is not None and index is not None and index.pos.get(other, -1) >= stop):
207
+ break
208
+ if not matches(other, target, platform):
209
+ continue
210
+ if anchor and not any(matches(up, anchor, platform) for up in _ancestors(other, parents)):
211
+ continue
212
+ n += 1
213
+ return n
214
+
215
+
216
+ def _anchor(node: ET.Element, nodes: List[ET.Element], parents: Mapping[ET.Element, ET.Element], platform: str, index: Optional[ScreenIndex] = None) -> Optional[Dict[str, str]]:
217
+ """The nearest ancestor that one id (or Android accessibility label) names uniquely on the screen."""
218
+ for up in _ancestors(node, parents):
219
+ at = _attrs(up, platform)
220
+ for t in ({"automation_id": at.get("id")}, {"name": at.get("desc")} if platform == "android" else {}):
221
+ if not t or not all(_plain(v) for v in t.values()):
222
+ continue
223
+ t = {k: str(v).strip() for k, v in t.items()}
224
+ if count(t, nodes, parents, platform, index=index) == 1:
225
+ return t
226
+ return None
227
+
228
+
229
+ def locate(node: ET.Element, nodes: List[ET.Element], parents: Mapping[ET.Element, ET.Element], platform: str, field: bool = False, index: Optional[ScreenIndex] = None) -> Optional[Dict[str, Any]]:
230
+ """
231
+ The node's target: its best candidate that is unique on the screen, with the next ones as ``fallbacks``; else one
232
+ anchored in its nearest uniquely named ancestor; else its best candidate with ``index``. None when it has no
233
+ candidate at all (neither an id nor a text).
234
+ """
235
+ found = candidates(node, platform, field)
236
+ if not found:
237
+ return None
238
+ unique = [t for t in found if count(t, nodes, parents, platform, index=index) == 1]
239
+ if not unique:
240
+ anchor = _anchor(node, nodes, parents, platform, index)
241
+ if anchor is not None:
242
+ for t in found:
243
+ inside = {**t, "within": anchor}
244
+ if count(inside, nodes, parents, platform, index=index) == 1:
245
+ unique.append(inside)
246
+ break
247
+ if not unique:
248
+ best = found[0]
249
+ earlier = count(best, nodes, parents, platform, before=node, index=index)
250
+ return {**best, **({"index": earlier} if earlier else {})}
251
+ # A fallback that only adds conditions to one tried before it can never find what that one missed: left out.
252
+ kept: List[Dict[str, Any]] = []
253
+ for t in unique:
254
+ if not any(set(k.items()) <= set(t.items()) for k in kept if "within" not in k and "within" not in t):
255
+ kept.append(t)
256
+ first, rest = kept[0], kept[1 : 1 + MAX_FALLBACKS]
257
+ return {**first, **({"fallbacks": rest} if rest else {})}
258
+
259
+
260
+ def without_fallbacks(target: Mapping[str, Any]) -> Dict[str, Any]:
261
+ return {k: v for k, v in target.items() if k != "fallbacks"}
262
+
263
+
264
+ def tried(target: Mapping[str, Any]) -> List[Dict[str, Any]]:
265
+ """The targets a replay tries, in order: the step's own, then its fallbacks."""
266
+ rest = target.get("fallbacks")
267
+ return [without_fallbacks(target), *[dict(f) for f in rest if isinstance(f, Mapping)]] if isinstance(rest, list) else [without_fallbacks(target)]
268
+
269
+
270
+ def pairs(target: Mapping[str, Any], query: Any, platform: str) -> List[Tuple[str, str]]:
271
+ """Each target a replay tries, as (strategy, value) the driver sends: what the Record page shows as its locators."""
272
+ out: List[Tuple[str, str]] = []
273
+ for t in tried(target):
274
+ using, value = query(t, platform)
275
+ # A web page's element is looked for in the page inside the app: said so.
276
+ out.append((f"webview {using}" if isinstance(t.get("web"), Mapping) else using, value))
277
+ return out