@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
@@ -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
@@ -51,6 +51,18 @@ def regex_literal(text: str) -> str:
51
51
 
52
52
 
53
53
  def _selector(target: Mapping[str, Any], text: Optional[str] = None) -> Dict[str, Any]:
54
+ web = target.get("web")
55
+ if isinstance(web, Mapping):
56
+ # A web page's element: Maestro reads the page through the accessibility tree, where its label or text shows
57
+ # as text and its id as the resource id; a test id, a field's name or a placeholder has no Maestro form.
58
+ if web.get("label") or web.get("text"):
59
+ return {"text": regex_literal(str(web.get("label") or web.get("text")))}
60
+ if web.get("id"):
61
+ return {"id": regex_literal(str(web["id"]))}
62
+ fallback = next((f for f in target.get("fallbacks") or [] if isinstance(f, Mapping) and not f.get("web")), None)
63
+ if fallback is not None:
64
+ return _selector(fallback, text)
65
+ raise WorkflowError("a web page's element found by its test id, name or placeholder has no Maestro form; replay this workflow with Appium")
54
66
  sel: Dict[str, Any] = {}
55
67
  if target.get("automation_id"):
56
68
  sel["id"] = regex_literal(str(target["automation_id"]))
@@ -62,6 +74,10 @@ def _selector(target: Mapping[str, Any], text: Optional[str] = None) -> Dict[str
62
74
  sel["index"] = int(target["index"])
63
75
  if not sel:
64
76
  raise WorkflowError("a Maestro step needs an automation_id or a name")
77
+ anchor = target.get("within")
78
+ if isinstance(anchor, Mapping) and anchor:
79
+ # A control found inside its uniquely named parent: Maestro's childOf (its fallbacks have no Maestro form).
80
+ sel["childOf"] = _selector(anchor)
65
81
  return sel
66
82
 
67
83
 
@@ -109,6 +125,12 @@ def to_flow(workflow: Mapping[str, Any], app_id: str, variables: Optional[Mappin
109
125
  cmds.append({"tapOn": {**_selector(d), "optional": True}})
110
126
  elif op == "close":
111
127
  cmds.append("stopApp")
128
+ elif op == "open_link":
129
+ # Maestro's openLink takes the link as written, and a magic link is read when the step runs.
130
+ raise WorkflowError(f"step {i}: a magic link read from the mailbox has no Maestro form; replay this workflow with Appium")
131
+ elif op in ("tap", "double_tap", "long_press") and "at" in step:
132
+ # Maestro taps a point of the screen, never one inside a control: said, not guessed.
133
+ raise WorkflowError(f"step {i}: a tap at a point inside a control has no Maestro form; replay this workflow with Appium")
112
134
  elif op in ("tap", "double_tap", "long_press"):
113
135
  cmds.append({{"tap": "tapOn", "double_tap": "doubleTapOn", "long_press": "longPressOn"}[op]: _selector(step["target"])})
114
136
  elif op == "type":
@@ -116,8 +138,13 @@ def to_flow(workflow: Mapping[str, Any], app_id: str, variables: Optional[Mappin
116
138
  elif op == "select":
117
139
  # Open the drop-down, then tap the item by the text it shows.
118
140
  cmds += [{"tapOn": _selector(step["target"])}, {"tapOn": {"text": text(step["value"])}}]
141
+ elif op == "set_checked":
142
+ # Tapped only while it is not so already (optional: no tap when it is), then confirmed.
143
+ want = bool(step["checked"])
144
+ cmds += [{"tapOn": {**_selector(step["target"]), "checked": not want, "optional": True}}, {"assertVisible": {**_selector(step["target"]), "checked": want}}]
119
145
  elif op == "expect":
120
- cmds.append({"assertVisible": _selector(step["target"], text(step["text"]) if "text" in step else None)})
146
+ sel = _selector(step["target"], text(step["text"]) if "text" in step else None)
147
+ cmds.append({"assertVisible": {**sel, **({"checked": bool(step["checked"])} if "checked" in step else {})}})
121
148
  elif op == "wait_for":
122
149
  sel = _selector(step["target"], text(step["text"]) if "text" in step else None)
123
150
  cmds.append({"extendedWaitUntil": {("notVisible" if step.get("gone") else "visible"): sel, "timeout": _ms(t or 10)}})
@@ -0,0 +1,79 @@
1
+ """
2
+ A magic link: a sign-in or verification link a site sends by email, opened on the device so the app (or its web page)
3
+ takes it, as a person taps it in their mail.
4
+
5
+ The link is read from the login's own mailbox, the same one its one-time codes come to (``code: email``,
6
+ ``forgeqe_engine/otp.py``), at the moment the step runs: the newest message since the step before it, and in it only an
7
+ https link to one of the login's sites (``otp.link_in``). It is opened with Appium's deep link for the app under test
8
+ (``AppiumDriver.open_link``). The workflow keeps only ``open_link: {login: NAME}``; the link itself is never logged,
9
+ shown, emitted or kept, and one already opened in the run is not opened again.
10
+
11
+ The logins come from ForgeQE's settings (``src/mobile/run.ts`` sends only those with an email code): a name, its sites,
12
+ and its mailbox settings with the credentials as environment variables' names.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ import time
18
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
19
+
20
+ from forgeqe_desktop.workflow import WorkflowError
21
+ from forgeqe_engine.otp import CodeError, CodeSource, fetch_link, parse_source
22
+
23
+ LOGIN_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
24
+
25
+
26
+ def _hosts(domains: Any) -> List[str]:
27
+ """
28
+ A login's sites as hosts (otp.link_in): an exact host stays exact, a ``*.`` pattern keeps its star for its
29
+ subdomains (https://*.shop.example → *.shop.example). Anything else is left out.
30
+ """
31
+ out: List[str] = []
32
+ for pattern in domains if isinstance(domains, list) else []:
33
+ host = str(pattern).split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0].strip().lower()
34
+ star = host.startswith("*.")
35
+ base = host[2:] if star else host
36
+ if re.fullmatch(r"[a-z0-9-]+(\.[a-z0-9-]+)+", base):
37
+ out.append(f"*.{base}" if star else base)
38
+ return out
39
+
40
+
41
+ def mail_logins(raw: Any) -> Dict[str, Tuple[CodeSource, List[str]]]:
42
+ """The logins whose mail can be read for a link, by name: their mailbox (an email code source) and their sites."""
43
+ out: Dict[str, Tuple[CodeSource, List[str]]] = {}
44
+ for d in raw if isinstance(raw, list) else []:
45
+ if not isinstance(d, Mapping) or not isinstance(d.get("name"), str) or not LOGIN_NAME.match(d["name"]):
46
+ continue
47
+ if not isinstance(d.get("code"), Mapping) or d["code"].get("kind") != "email":
48
+ continue
49
+ try:
50
+ src = parse_source(d["code"])
51
+ except CodeError:
52
+ continue
53
+ hosts = _hosts(d.get("domains"))
54
+ if hosts:
55
+ out[d["name"]] = (src, hosts)
56
+ return out
57
+
58
+
59
+ class LinkOpener:
60
+ """Opens a login's newest magic link on the device; a link opened already in this run is skipped."""
61
+
62
+ def __init__(self, driver: Any, logins: Mapping[str, Tuple[CodeSource, List[str]]], fetch: Callable[..., str] = fetch_link, sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.time) -> None:
63
+ self.driver, self.logins, self.fetch, self.sleep, self.clock = driver, dict(logins), fetch, sleep, clock
64
+ self.used: Dict[str, List[str]] = {}
65
+
66
+ def names(self) -> List[str]:
67
+ return sorted(self.logins)
68
+
69
+ def open(self, login: str, since: float) -> None:
70
+ """The link `login`'s site sent since `since`, opened on the device. Raises WorkflowError when it cannot be."""
71
+ if not isinstance(login, str) or login not in self.logins:
72
+ raise WorkflowError(f"login {login!r} has no mailbox to read a link from: give it code: email settings and sites in forgeqe.yaml logins")
73
+ src, hosts = self.logins[login]
74
+ try:
75
+ link = self.fetch(src, hosts, since, used=self.used.get(login), sleep=self.sleep, clock=self.clock)
76
+ except CodeError as e:
77
+ raise WorkflowError(str(e)) from None
78
+ self.used.setdefault(login, []).append(link)
79
+ self.driver.open_link(link)