@capagents/forgeqe 3.0.8 → 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 (214) hide show
  1. package/HOW_TO_USE.md +20 -19
  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 +1889 -1863
  36. package/dist/template.html +14 -14
  37. package/dist/web/assets/AgentWork-C3KdZh5M.js +2 -0
  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-Cm8lLnfi.js → CommandPalette-D89NM2_E.js} +1 -1
  43. package/dist/web/assets/{Compare-D10RIrFU.js → Compare-YfFYHwfK.js} +1 -1
  44. package/dist/web/assets/Cost-ClaDz0YR.js +1 -0
  45. package/dist/web/assets/Data-jSFgAfej.js +6 -0
  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-DOQ8KddV.js → Explore-BdFvqgF4.js} +2 -2
  50. package/dist/web/assets/Features-CIBbw6PG.js +1 -0
  51. package/dist/web/assets/Flags-B62v4uWR.js +2 -0
  52. package/dist/web/assets/Flaky-Cut1kZw6.js +1 -0
  53. package/dist/web/assets/Impact-jOSl5Q0k.js +3 -0
  54. package/dist/web/assets/Jobs-DMJGgWtQ.js +5 -0
  55. package/dist/web/assets/KindPage-BbQWH5wa.js +6 -0
  56. package/dist/web/assets/Migration-BBgv7xXo.js +2 -0
  57. package/dist/web/assets/PageAgent-txbNoP6u.js +1 -0
  58. package/dist/web/assets/Product-BrXH81Ns.js +7 -0
  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-ClcY7M0Q.js +2 -0
  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-CFvmdULI.js +2 -0
  68. package/dist/web/assets/{Steps-BoSfaEHJ.js → Steps-BS66s0E1.js} +2 -2
  69. package/dist/web/assets/TestCases-CrQEUtfD.js +1 -0
  70. package/dist/web/assets/TestData-e3IX0xwG.js +2 -0
  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-C5YaMLS0.js +3 -0
  74. package/dist/web/assets/WhatsNew-CwnRbDnd.js +1 -0
  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/{families-D78NUxTI.js → families-DWilSDct.js} +1 -1
  78. package/dist/web/assets/filters-CVzIOjPG.js +1 -0
  79. package/dist/web/assets/{fold-DFcP0iIo.js → fold-tvLGnxD1.js} +1 -1
  80. package/dist/web/assets/frame-Deu1IqzV.js +13 -0
  81. package/dist/web/assets/index-BWMIKyPB.js +76 -0
  82. package/dist/web/assets/index-C2Yq55oT.css +2 -0
  83. package/dist/web/assets/line-icons-C_amZ5-o.js +1 -0
  84. package/dist/web/assets/logos-C1NBtBMc.js +1 -0
  85. package/dist/web/assets/logos-DFyhMw0i.js +1 -0
  86. package/dist/web/assets/{markdown-DIB_8ewG.js → markdown-DC2HA0yZ.js} +7 -7
  87. package/dist/web/assets/paletteCommands-Qxm5DZIs.js +1 -0
  88. package/dist/web/assets/parts-BR6dUwqn.js +1 -0
  89. package/dist/web/assets/{productParts-BYAQJWF9.js → productParts-BxdHuSBa.js} +1 -1
  90. package/dist/web/assets/qualityParts-lz6eYVxC.js +1 -0
  91. package/dist/web/assets/{recordTest-GM1nj_SM.js → recordTest-CcplpTS6.js} +1 -1
  92. package/dist/web/assets/today-DuQFapJM.js +1 -0
  93. package/dist/web/assets/when-CHnpLdYw.js +1 -0
  94. package/dist/web/index.html +12 -6
  95. package/docs/ForgeQE-Client-Overview.pdf +0 -0
  96. package/docs/ForgeQE-Installation-Guide.pdf +0 -0
  97. package/docs/MOBILE.md +42 -7
  98. package/docs/TEST_MANAGEMENT_PLAN.md +186 -15
  99. package/docs/user-guide.html +1 -1
  100. package/package.json +2 -1
  101. package/prompts/README.md +1 -0
  102. package/prompts/brain.md +1 -0
  103. package/prompts/test-linker.md +43 -0
  104. package/py/forgeqe_data/connect.py +3 -1
  105. package/py/forgeqe_data/flows.py +1 -1
  106. package/py/forgeqe_data/service.py +1 -1
  107. package/py/forgeqe_data/streams.py +1 -1
  108. package/py/forgeqe_data/testdata.py +1 -1
  109. package/py/forgeqe_desktop/replay.py +43 -1
  110. package/py/forgeqe_desktop/service.py +2 -0
  111. package/py/forgeqe_desktop/workflow.py +77 -15
  112. package/py/forgeqe_engine/brand.py +1 -1
  113. package/py/forgeqe_engine/browser.py +2 -1
  114. package/py/forgeqe_engine/diagnostics.py +1 -1
  115. package/py/forgeqe_engine/memory.py +2 -1
  116. package/py/forgeqe_engine/neutral_log.py +1 -1
  117. package/py/forgeqe_engine/otp.py +127 -12
  118. package/py/forgeqe_engine/pwlaunch.mjs +1 -1
  119. package/py/forgeqe_engine/recordsession.py +13 -3
  120. package/py/forgeqe_engine/webrecord.py +20 -0
  121. package/py/forgeqe_mobile/appium_driver.py +225 -10
  122. package/py/forgeqe_mobile/locators.py +277 -0
  123. package/py/forgeqe_mobile/maestro.py +28 -1
  124. package/py/forgeqe_mobile/magiclink.py +79 -0
  125. package/py/forgeqe_mobile/record.py +284 -67
  126. package/py/forgeqe_mobile/service.py +9 -0
  127. package/py/forgeqe_mobile/webview.py +142 -0
  128. package/py/forgeqe_testmgmt/__init__.py +1 -0
  129. package/py/forgeqe_testmgmt/pytest_collect.py +56 -0
  130. package/py/forgeqe_tosca/ntir.py +45 -6
  131. package/dist/docs-site/LICENSE.ubuntu.txt +0 -96
  132. package/dist/docs-site/img/icons/api.svg +0 -1
  133. package/dist/docs-site/img/icons/architecture.svg +0 -1
  134. package/dist/docs-site/img/icons/branch.svg +0 -1
  135. package/dist/docs-site/img/icons/browser-agent.svg +0 -1
  136. package/dist/docs-site/img/icons/case.svg +0 -1
  137. package/dist/docs-site/img/icons/container.svg +0 -1
  138. package/dist/docs-site/img/icons/context-engine.svg +0 -1
  139. package/dist/docs-site/img/icons/desktop.svg +0 -1
  140. package/dist/docs-site/img/icons/download.svg +0 -1
  141. package/dist/docs-site/img/icons/explorer.svg +0 -1
  142. package/dist/docs-site/img/icons/feature.svg +0 -1
  143. package/dist/docs-site/img/icons/healer.svg +0 -1
  144. package/dist/docs-site/img/icons/knowledge-base.svg +0 -1
  145. package/dist/docs-site/img/icons/mail.svg +0 -1
  146. package/dist/docs-site/img/icons/mobile.svg +0 -1
  147. package/dist/docs-site/img/icons/model.svg +0 -1
  148. package/dist/docs-site/img/icons/network.svg +0 -1
  149. package/dist/docs-site/img/icons/orchestrator.svg +0 -1
  150. package/dist/docs-site/img/icons/plug.svg +0 -1
  151. package/dist/docs-site/img/icons/pr-reviewer.svg +0 -1
  152. package/dist/docs-site/img/icons/replay.svg +0 -1
  153. package/dist/docs-site/img/icons/report.svg +0 -1
  154. package/dist/docs-site/img/icons/result.svg +0 -1
  155. package/dist/docs-site/img/icons/rule.svg +0 -1
  156. package/dist/docs-site/img/icons/scribe.svg +0 -1
  157. package/dist/docs-site/img/icons/shield.svg +0 -1
  158. package/dist/docs-site/img/icons/specs.svg +0 -1
  159. package/dist/docs-site/img/icons/speed.svg +0 -1
  160. package/dist/docs-site/img/icons/stories.svg +0 -1
  161. package/dist/docs-site/img/icons/terminal.svg +0 -1
  162. package/dist/docs-site/img/icons/test-finder.svg +0 -1
  163. package/dist/docs-site/img/icons/visual.svg +0 -1
  164. package/dist/docs-site/img/icons/web.svg +0 -1
  165. package/dist/docs-site/img/icons/wikis.svg +0 -1
  166. package/dist/web/assets/Agent-BgpsSPrr.js +0 -7
  167. package/dist/web/assets/AgentWork-VRJbVshA.js +0 -2
  168. package/dist/web/assets/ApiTests-DHwAbLqi.js +0 -10
  169. package/dist/web/assets/Browse-BMF56Efz.js +0 -2
  170. package/dist/web/assets/Chat-CaUU-WY7.js +0 -3
  171. package/dist/web/assets/Cost-B_UPdLMv.js +0 -1
  172. package/dist/web/assets/Data-C4H5sYEC.js +0 -6
  173. package/dist/web/assets/Desktop-bLj_WL8M.js +0 -1
  174. package/dist/web/assets/DesktopReview-Bl9TCBkR.js +0 -1
  175. package/dist/web/assets/Evidence-Cp1HUzpL.js +0 -1
  176. package/dist/web/assets/Features-RCBkPcEQ.js +0 -1
  177. package/dist/web/assets/Flags-n0IwBw02.js +0 -2
  178. package/dist/web/assets/Flaky-BfwzLt5Z.js +0 -1
  179. package/dist/web/assets/Impact-DLpuEZSR.js +0 -3
  180. package/dist/web/assets/Jobs-BdXmyaEl.js +0 -5
  181. package/dist/web/assets/KindPage-B3aoqE1U.js +0 -6
  182. package/dist/web/assets/Migration-CZyx2ubc.js +0 -2
  183. package/dist/web/assets/PageAgent-D5ZEQOQe.js +0 -1
  184. package/dist/web/assets/Product-BZe62mCa.js +0 -7
  185. package/dist/web/assets/Production-D0PyJr7i.js +0 -1
  186. package/dist/web/assets/Quality-k-6G5B1k.js +0 -1
  187. package/dist/web/assets/Readiness-InUynp50.js +0 -1
  188. package/dist/web/assets/Record-DIprTx7M.js +0 -1
  189. package/dist/web/assets/Regression-CWk9uEE7.js +0 -5
  190. package/dist/web/assets/RelationGraph-ybf6gf-K.js +0 -1
  191. package/dist/web/assets/Reports-BYOTLZah.js +0 -2
  192. package/dist/web/assets/Response-BC4GgybP.js +0 -9
  193. package/dist/web/assets/RunDiff-B0sRO9OI.js +0 -1
  194. package/dist/web/assets/Runs-Dy_fBhhR.js +0 -2
  195. package/dist/web/assets/TestCases-D4xZlPgR.js +0 -1
  196. package/dist/web/assets/TestData-CXDU1gv4.js +0 -2
  197. package/dist/web/assets/TestDebt-Cc5ODjR-.js +0 -1
  198. package/dist/web/assets/TestManagement-Cdj_o5D6.js +0 -1
  199. package/dist/web/assets/Tosca-CfgkdgcT.js +0 -3
  200. package/dist/web/assets/WhatsNew-DVzuub1d.js +0 -1
  201. package/dist/web/assets/agentTabs-CmOYLCIU.js +0 -1
  202. package/dist/web/assets/dataParts-Bw4pl6JD.js +0 -3
  203. package/dist/web/assets/diff-CRxu9ARd.js +0 -2
  204. package/dist/web/assets/filters-D2j1h_NS.js +0 -1
  205. package/dist/web/assets/frame-Cr9XkzMf.js +0 -13
  206. package/dist/web/assets/index-C5JQ2Q4O.js +0 -69
  207. package/dist/web/assets/index-CpHco9gF.css +0 -2
  208. package/dist/web/assets/line-icons-Cb4JZG1G.js +0 -1
  209. package/dist/web/assets/logos-d0fFqQS2.js +0 -1
  210. package/dist/web/assets/paletteCommands-COA2_LAh.js +0 -1
  211. package/dist/web/assets/parts-Dsb4bByj.js +0 -1
  212. package/dist/web/assets/qualityParts-DyfqNmRK.js +0 -1
  213. package/dist/web/assets/rows-CpFeqs4P.js +0 -1
  214. package/dist/web/assets/segmented-BbcK9lLg.js +0 -1
@@ -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
- asyncio.ensure_future(self._page_call(sid, expression))
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
- asyncio.ensure_future(self.send("Page.screencastFrameAck", {"sessionId": ack}, session_id))
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
  ]
@@ -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: