@capagents/forgeqe 2.10.4 → 3.0.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 (162) hide show
  1. package/HOW_TO_USE.md +119 -16
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/dist/docs-site/docs/architecture/index.html +1 -0
  5. package/dist/docs-site/docs/cost-architecture/index.html +1 -1
  6. package/dist/docs-site/docs/index.html +158 -19
  7. package/dist/docs-site/docs/mobile/index.html +38 -2
  8. package/dist/docs-site/docs/search.js +1 -1
  9. package/dist/forgeqe.js +2121 -1947
  10. package/dist/web/assets/Agent-DISh0THc.js +8 -0
  11. package/dist/web/assets/ApiTests-CK0HqEH4.js +10 -0
  12. package/dist/web/assets/Browse-WylAQZvD.js +2 -0
  13. package/dist/web/assets/Chat-B7IOg3I3.js +5 -0
  14. package/dist/web/assets/CommandPalette-CkreEJ8R.js +1 -0
  15. package/dist/web/assets/Compare-CgOfZofk.js +1 -0
  16. package/dist/web/assets/Cost-Dl5-viu4.js +1 -0
  17. package/dist/web/assets/Data-Bv2S5wkW.js +6 -0
  18. package/dist/web/assets/Desktop-CifPwy5u.js +1 -0
  19. package/dist/web/assets/DesktopReview-fpGdtU4r.js +1 -0
  20. package/dist/web/assets/Evidence-hOZDzfKt.js +1 -0
  21. package/dist/web/assets/Explore-c85VGE9Q.js +2 -0
  22. package/dist/web/assets/Features-DXL_vSjn.js +1 -0
  23. package/dist/web/assets/Flags-B7x2pDud.js +2 -0
  24. package/dist/web/assets/Flaky-BM3syqCt.js +1 -0
  25. package/dist/web/assets/Impact-BUCh8OAI.js +3 -0
  26. package/dist/web/assets/Jobs-B8sBDYRI.js +5 -0
  27. package/dist/web/assets/KindPage-yVmpQm7L.js +6 -0
  28. package/dist/web/assets/Migration-BOLN1duU.js +2 -0
  29. package/dist/web/assets/Product-C0FeEaJg.js +7 -0
  30. package/dist/web/assets/Production-BSMQyWKd.js +1 -0
  31. package/dist/web/assets/Quality-DsM9gWZb.js +1 -0
  32. package/dist/web/assets/Readiness-BhqkAJYN.js +1 -0
  33. package/dist/web/assets/Record-CPx-lK53.js +2 -0
  34. package/dist/web/assets/Regression-BXbX46nO.js +5 -0
  35. package/dist/web/assets/{RelationGraph-D_ZVeOBh.js → RelationGraph-eoGXXz5t.js} +1 -1
  36. package/dist/web/assets/Reports-36YQzVhA.js +2 -0
  37. package/dist/web/assets/Response-DplUOsue.js +4 -0
  38. package/dist/web/assets/RunDiff-D0fDhRmK.js +1 -0
  39. package/dist/web/assets/Runs-Bv1Ef8zq.js +2 -0
  40. package/dist/web/assets/Steps-Cm-atRtk.js +2 -0
  41. package/dist/web/assets/TestCases-B9x9W3zJ.js +1 -0
  42. package/dist/web/assets/TestData-DsJ6Z2YI.js +2 -0
  43. package/dist/web/assets/TestDebt-B_FUbMOb.js +1 -0
  44. package/dist/web/assets/Tosca-nxVCubA5.js +3 -0
  45. package/dist/web/assets/WhatsNew-CdnbMvrr.js +1 -0
  46. package/dist/web/assets/agentLink-BGKAF6xd.js +1 -0
  47. package/dist/web/assets/capture.worklet-C2TjBQ56.js +11 -0
  48. package/dist/web/assets/capture.worklet-UcNywATd.js +1 -0
  49. package/dist/web/assets/dataParts-Bn-tzbKg.js +3 -0
  50. package/dist/web/assets/{families-zlLgApNV.js → families-DPlFfKf2.js} +1 -1
  51. package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
  52. package/dist/web/assets/fold-BhRpA0sy.js +1 -0
  53. package/dist/web/assets/frame-D_TPoUTD.js +16 -0
  54. package/dist/web/assets/index-BRB-oAMd.js +67 -0
  55. package/dist/web/assets/index-CIw5WfL8.css +2 -0
  56. package/dist/web/assets/{line-icons-CQ-3V8ax.js → line-icons-DBwNPSmu.js} +1 -1
  57. package/dist/web/assets/{logos-DfCytw3-.js → logos-839CfoKx.js} +1 -1
  58. package/dist/web/assets/{markdown-nTIj9lyp.js → markdown-6z0km3hN.js} +7 -7
  59. package/dist/web/assets/paletteCommands-CZFdKGhh.js +1 -0
  60. package/dist/web/assets/parts-VPcxh6Jc.js +1 -0
  61. package/dist/web/assets/{productParts-DK3ULNpv.js → productParts-BjfWgMtq.js} +1 -1
  62. package/dist/web/assets/qualityParts-PGN65yfI.js +1 -0
  63. package/dist/web/assets/{recordTest-CqxnF953.js → recordTest-EkxSMWbe.js} +1 -1
  64. package/dist/web/assets/rows-uLoguIo5.js +1 -0
  65. package/dist/web/assets/segmented-DphDskQz.js +1 -0
  66. package/dist/web/assets/{usePageChat-Dl2aUtHP.js → usePageChat-DqEwGcyO.js} +1 -1
  67. package/dist/web/index.html +6 -6
  68. package/docs/ARCHITECTURE.md +1 -0
  69. package/docs/COST_ARCHITECTURE.md +1 -1
  70. package/docs/MOBILE.md +40 -0
  71. package/docs/user-guide.html +158 -19
  72. package/evals/prompts/brain/browser-narrow-with-filters.yaml +20 -0
  73. package/forgeqe.example.yaml +11 -1
  74. package/package.json +4 -1
  75. package/prompts/brain.md +4 -0
  76. package/prompts/browser-goal-verification.md +2 -0
  77. package/prompts/refine.md +2 -0
  78. package/prompts/requests-rule.md +1 -1
  79. package/prompts/talk-summary.md +43 -0
  80. package/prompts/talk.md +49 -0
  81. package/prompts/test-agent.md +1 -0
  82. package/prompts/test-reviewer.md +2 -1
  83. package/prompts/test-rules.md +3 -0
  84. package/py/forgeqe_data/__init__.py +1 -0
  85. package/py/forgeqe_data/__main__.py +12 -0
  86. package/py/forgeqe_data/connect.py +290 -0
  87. package/py/forgeqe_data/connstr.py +169 -0
  88. package/py/forgeqe_data/flows.py +603 -0
  89. package/py/forgeqe_data/guard.py +214 -0
  90. package/py/forgeqe_data/mongo.py +219 -0
  91. package/py/forgeqe_data/schema.py +431 -0
  92. package/py/forgeqe_data/service.py +651 -0
  93. package/py/forgeqe_data/streams.py +400 -0
  94. package/py/forgeqe_data/subset.py +299 -0
  95. package/py/forgeqe_data/testdata.py +861 -0
  96. package/py/forgeqe_data/vector.py +113 -0
  97. package/py/forgeqe_desktop/workflow.py +6 -4
  98. package/py/forgeqe_engine/capture.py +5 -4
  99. package/py/forgeqe_engine/diagnostics.py +2 -2
  100. package/py/forgeqe_engine/lenient_json.py +96 -0
  101. package/py/forgeqe_engine/llm.py +4 -0
  102. package/py/forgeqe_engine/network.py +93 -15
  103. package/py/forgeqe_engine/neutral_log.py +16 -1
  104. package/py/forgeqe_engine/recordsession.py +54 -1
  105. package/py/forgeqe_engine/service.py +22 -3
  106. package/py/forgeqe_mobile/appium_driver.py +9 -0
  107. package/py/forgeqe_mobile/apps.py +4 -0
  108. package/py/forgeqe_mobile/maestro.py +3 -0
  109. package/py/forgeqe_mobile/record.py +610 -0
  110. package/py/forgeqe_mobile/service.py +37 -7
  111. package/py/forgeqe_talk/__init__.py +1 -0
  112. package/py/forgeqe_talk/__main__.py +65 -0
  113. package/py/forgeqe_voice/worker.py +141 -0
  114. package/skills/dotnet-nunit-playwright/SKILL.md +1 -0
  115. package/skills/playwright-typescript/SKILL.md +1 -1
  116. package/dist/web/assets/Agent-DaA5WhAY.js +0 -8
  117. package/dist/web/assets/ApiTests-B7xsTGyo.js +0 -10
  118. package/dist/web/assets/Browse-ByYCyAwd.js +0 -2
  119. package/dist/web/assets/Chat-D1-cYNBr.js +0 -3
  120. package/dist/web/assets/CommandPalette-DbxKJJJB.js +0 -1
  121. package/dist/web/assets/Compare-CYLFEtJl.js +0 -1
  122. package/dist/web/assets/Cost-Csz0jMHo.js +0 -1
  123. package/dist/web/assets/Data-BWTme_Yw.js +0 -6
  124. package/dist/web/assets/Desktop-rZ0vB6Ie.js +0 -1
  125. package/dist/web/assets/DesktopReview-_Xha22_d.js +0 -1
  126. package/dist/web/assets/Evidence-DmUyZy9F.js +0 -1
  127. package/dist/web/assets/Explore-2wzgwz3J.js +0 -2
  128. package/dist/web/assets/Features-DazEWqYu.js +0 -1
  129. package/dist/web/assets/Flags-BTt0-pqd.js +0 -2
  130. package/dist/web/assets/Flaky-CjkQp73T.js +0 -1
  131. package/dist/web/assets/Impact-De87sv5J.js +0 -3
  132. package/dist/web/assets/Jobs-aiNGBVHL.js +0 -5
  133. package/dist/web/assets/KindPage-CrGoFeSa.js +0 -6
  134. package/dist/web/assets/Migration-BAhQ1DZO.js +0 -2
  135. package/dist/web/assets/Product-DpK-PIxV.js +0 -7
  136. package/dist/web/assets/Production-D6A89rZZ.js +0 -1
  137. package/dist/web/assets/Quality-Bc5wCsog.js +0 -1
  138. package/dist/web/assets/Readiness-CoVgZw2X.js +0 -1
  139. package/dist/web/assets/Record-DcgBatJJ.js +0 -2
  140. package/dist/web/assets/Regression-BJLYrqST.js +0 -5
  141. package/dist/web/assets/Reports-DYfyfEDy.js +0 -2
  142. package/dist/web/assets/Response-CNLi9Dqu.js +0 -4
  143. package/dist/web/assets/RunDiff-BMTdRhii.js +0 -1
  144. package/dist/web/assets/Runs-lb78rvPV.js +0 -2
  145. package/dist/web/assets/Steps-BDSeIznj.js +0 -2
  146. package/dist/web/assets/TestCases-CfUwd67O.js +0 -1
  147. package/dist/web/assets/TestData-DP7cvW48.js +0 -2
  148. package/dist/web/assets/TestDebt-CqARxL7k.js +0 -1
  149. package/dist/web/assets/Tosca-CLAz9tWT.js +0 -3
  150. package/dist/web/assets/WhatsNew-1lhTRE5Z.js +0 -1
  151. package/dist/web/assets/dataParts-DI_OJhy5.js +0 -3
  152. package/dist/web/assets/filters-CflRmNDz.js +0 -1
  153. package/dist/web/assets/fold-pOBiaSlF.js +0 -1
  154. package/dist/web/assets/frame-CYYiRu5P.js +0 -4
  155. package/dist/web/assets/index-CNDoTeRV.css +0 -2
  156. package/dist/web/assets/index-D4a0w3Vl.js +0 -67
  157. package/dist/web/assets/palette-Cj4CUs0K.js +0 -1
  158. package/dist/web/assets/parts-C53RxMcR.js +0 -1
  159. package/dist/web/assets/qualityParts-C9FItsTg.js +0 -1
  160. package/dist/web/assets/rows-D6rPRkHl.js +0 -1
  161. package/dist/web/assets/segmented-CAf_qz5Z.js +0 -1
  162. package/dist/web/assets/thread-DQdyL3Sv.js +0 -5
@@ -0,0 +1,610 @@
1
+ """
2
+ Recording a mobile app by hand, through Appium: the device's screen is shown on the Record page, the tester taps,
3
+ types and swipes on it there, and each action becomes a step of a ``forgeqe-mobile-v1`` workflow. No model is involved.
4
+ It works the same on a device on this computer and on a device cloud's (TestMu AI, BrowserStack), since nothing is read
5
+ from the device but Appium's screenshot and page source.
6
+
7
+ What the page sends is a command (``run_record`` reads them from stdin, the gateway checks them first,
8
+ ``src/mobile/record.ts``), never a locator or a point: a control is named by its number in the screen ForgeQE sent last
9
+ (``seq`` and ``el``), and the locator is ForgeQE's own, from the page source. Each action is done on the device through
10
+ the locator it records (``driver.find``), so a step that would not replay is never kept.
11
+
12
+ - a tap, double tap or long press on a control → ``tap``, ``double_tap``, ``long_press``; a tap on a permission prompt's
13
+ answer (Android's permission controller, iOS's own alert) → the workflow's ``dismiss`` list, since a replay on another
14
+ device may not be asked;
15
+ - text typed into a field → ``type``. A password field takes only a saved secret, by its name (``{{secret:NAME}}``):
16
+ the value is read here from the environment and never reaches the page; plain text equal to a secret is written as
17
+ its placeholder;
18
+ - a check → ``expect`` with the text the control shows now; ``wait_for`` waits for a control;
19
+ - swipe, scroll, back, hide the keyboard, a key (enter, search, …), wait.
20
+
21
+ A control with neither an id nor a text cannot be recorded (a replay could not find it again): one inside it that has
22
+ is used, else the tap is refused and listed. Undo and delete remove a step from the workflow; they cannot undo what
23
+ was done on the device.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ import queue
30
+ import re
31
+ import struct
32
+ import time
33
+ import xml.etree.ElementTree as ET
34
+ from pathlib import Path
35
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
36
+
37
+ from forgeqe_desktop.record import _mask, target_of
38
+ from forgeqe_desktop.workflow import MAX_WAIT_SECONDS, MOBILE_FORMAT, MOBILE_KEYS, SWIPE_DIRECTIONS, WorkflowError, save, validate
39
+
40
+ from .appium_driver import IOS_PERMISSION_ANSWERS, _walk, element_props
41
+
42
+ MAX_ELEMENTS = 400
43
+ MAX_STEPS = 500
44
+ MAX_TEXT = 2000
45
+ MAX_CHECK_TEXT = 200
46
+ # A control's name longer than this is its content, not a label (explore's rule): left out when it has an id.
47
+ MAX_NAME = 80
48
+ # A name longer than this is never a locator: a control named only by a paragraph is not recorded.
49
+ MAX_LOCATOR_NAME = 300
50
+ MAX_LABEL = 80
51
+ # How long an action's control is looked for: it was on screen a moment ago.
52
+ FIND_SECONDS = 8.0
53
+ # How long the app is given to draw what an action changed before the screen is read again.
54
+ SETTLE = 0.8
55
+ # With no command, the screen is read again this often (a page that loads, an animation, a toast).
56
+ REFRESH_SECONDS = 3.0
57
+ # How many screens back a click still counts, when its control is on the screen now.
58
+ RECENT_SCREENS = 5
59
+
60
+ SECRET_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
61
+ # Android's permission prompts: their answers go to dismiss, never to steps.
62
+ PERMISSION_PACKAGES = frozenset({
63
+ "com.android.permissioncontroller", "com.google.android.permissioncontroller",
64
+ "com.android.packageinstaller", "com.google.android.packageinstaller",
65
+ })
66
+ ANDROID_FIELDS = ("android.widget.EditText", "android.widget.AutoCompleteTextView", "android.widget.MultiAutoCompleteTextView")
67
+ IOS_FIELDS = ("XCUIElementTypeTextField", "XCUIElementTypeSecureTextField", "XCUIElementTypeTextView", "XCUIElementTypeSearchField")
68
+ # iOS controls a tap is meant for: the page source has no "clickable" there.
69
+ IOS_TAPPABLE = ("XCUIElementTypeButton", "XCUIElementTypeCell", "XCUIElementTypeSwitch", "XCUIElementTypeLink", "XCUIElementTypeSegmentedControl", "XCUIElementTypeTab", "XCUIElementTypeMenuItem", "XCUIElementTypeKey")
70
+ # A drop-down: a tap on it and then on one of its items is one select step (the item by its text), not two taps.
71
+ def is_dropdown(kind: str) -> bool:
72
+ k = kind.rsplit(".", 1)[-1].lower()
73
+ return "spinner" in k or "dropdown" in k or k == "xcuielementtypepopupbutton"
74
+
75
+
76
+ # A box larger than this share of the screen is a layout, not a control, unless it can be tapped.
77
+ LAYOUT_SHARE = 0.5
78
+ _BOUNDS = re.compile(r"^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$")
79
+ _CONTROL_CHARS = re.compile(r"[\u0000-\u001f\u007f]")
80
+
81
+ ELEMENT_COMMANDS = ("tap", "double_tap", "long_press", "type", "check", "wait_for")
82
+ COMMANDS = (*ELEMENT_COMMANDS, "swipe", "scroll", "back", "hide_keyboard", "keys", "wait", "undo", "delete", "refresh", "stop")
83
+
84
+
85
+ class RecordRefused(ValueError):
86
+ """A command that cannot be recorded as asked; the message says why, for the tester."""
87
+
88
+
89
+ def png_size(png: bytes) -> Optional[Tuple[int, int]]:
90
+ """A PNG's width and height from its header, or None when it is not a PNG."""
91
+ if len(png) >= 24 and png[:8] == b"\x89PNG\r\n\x1a\n" and png[12:16] == b"IHDR":
92
+ w, h = struct.unpack(">II", png[16:24])
93
+ return int(w), int(h)
94
+ return None
95
+
96
+
97
+ def _box(node: ET.Element, platform: str) -> Optional[List[int]]:
98
+ a = node.attrib
99
+ if platform == "android":
100
+ m = _BOUNDS.match(a.get("bounds", ""))
101
+ if not m:
102
+ return None
103
+ x1, y1, x2, y2 = (int(v) for v in m.groups())
104
+ box = [x1, y1, x2 - x1, y2 - y1]
105
+ else:
106
+ try:
107
+ box = [int(float(a.get(k, ""))) for k in ("x", "y", "width", "height")]
108
+ except ValueError:
109
+ return None
110
+ return box if box[2] > 0 and box[3] > 0 else None
111
+
112
+
113
+ def _locator(props: Mapping[str, str]) -> Optional[Dict[str, Any]]:
114
+ target = target_of(props)
115
+ if target is None:
116
+ return None
117
+ name = str(target.get("name") or "")
118
+ if target.get("automation_id") and len(name) > MAX_NAME:
119
+ target.pop("name", None)
120
+ elif len(name) > MAX_LOCATOR_NAME or _CONTROL_CHARS.search(name):
121
+ return None
122
+ return target
123
+
124
+
125
+ def _matches(props: Mapping[str, str], node: ET.Element, target: Mapping[str, Any], platform: str) -> bool:
126
+ """Whether ``node`` is one the target's XPath finds (appium_driver.target_xpath), from its attributes."""
127
+ a = node.attrib
128
+ aid, name, kind = target.get("automation_id"), target.get("name"), target.get("control_type")
129
+ if platform == "android":
130
+ rid = a.get("resource-id", "")
131
+ if aid and not (rid == aid or rid.endswith(":id/" + str(aid))):
132
+ return False
133
+ if name and name not in (a.get("text"), a.get("content-desc")):
134
+ return False
135
+ return not kind or a.get("class") == kind
136
+ if a.get("visible") != "true":
137
+ return False
138
+ if aid and a.get("name") != aid:
139
+ return False
140
+ if name and name not in (a.get("label"), a.get("name"), a.get("value")):
141
+ return False
142
+ return not kind or a.get("type") == kind
143
+
144
+
145
+ def parse_screen(source: str, platform: str, app_id: str) -> List[Dict[str, Any]]:
146
+ """
147
+ The controls on screen, in document order, each with where it is (``box``: x, y, width, height in the page
148
+ source's units), its locator (``target``, with ``index`` when an earlier control matches it too, or None when it
149
+ cannot be recorded), a short ``label`` and what it is (``field``, ``secure``, ``prompt``: a permission prompt's
150
+ answer). The page source is the app's, so every text in it is data.
151
+ """
152
+ try:
153
+ root = ET.fromstring(source.encode("utf-8") if isinstance(source, str) else source)
154
+ except ET.ParseError:
155
+ return []
156
+ nodes: List[Tuple[ET.Element, bool, Dict[str, str]]] = []
157
+ for node, in_alert in _walk(root):
158
+ if platform == "ios" and node.attrib.get("visible") == "false":
159
+ continue
160
+ nodes.append((node, in_alert, element_props(node, platform)))
161
+
162
+ def is_field(kind: str) -> bool:
163
+ return (kind in ANDROID_FIELDS or "EditText" in kind) if platform == "android" else kind in IOS_FIELDS
164
+
165
+ def locate(node: ET.Element, props: Mapping[str, str]) -> Optional[Dict[str, Any]]:
166
+ target = _locator(props)
167
+ if target is None:
168
+ return None
169
+ if target.get("automation_id") and is_field(props.get("control_type", "")):
170
+ # A field's text is its hint now and what is typed later: its id alone finds it either way.
171
+ target.pop("name", None)
172
+ earlier = 0
173
+ for other, _, other_props in nodes:
174
+ if other is node:
175
+ break
176
+ if _matches(other_props, other, target, platform):
177
+ earlier += 1
178
+ return {**target, **({"index": earlier} if earlier else {})}
179
+
180
+ def tappable(node: ET.Element) -> bool:
181
+ a = node.attrib
182
+ if platform == "android":
183
+ return any(a.get(k) == "true" for k in ("clickable", "long-clickable", "checkable"))
184
+ return a.get("type", node.tag) in IOS_TAPPABLE
185
+
186
+ boxes = [b for b in (_box(n, platform) for n, _, _ in nodes) if b]
187
+ screen_area = max((b[2] * b[3] for b in boxes), default=0)
188
+ out: List[Dict[str, Any]] = []
189
+ for node, in_alert, props in nodes:
190
+ box = _box(node, platform)
191
+ if box is None:
192
+ continue
193
+ kind = props.get("control_type", "")
194
+ target = locate(node, props)
195
+ via = False
196
+ if target is None and tappable(node):
197
+ # A container with no id or text of its own (a list row, a React Native touchable): the first control
198
+ # inside it that has one, where it lies inside it, is what a replay taps.
199
+ for child in node.iter():
200
+ if child is node:
201
+ continue
202
+ cbox = _box(child, platform)
203
+ if cbox is None or not (box[0] <= cbox[0] and box[1] <= cbox[1] and cbox[0] + cbox[2] <= box[0] + box[2] and cbox[1] + cbox[3] <= box[1] + box[3]):
204
+ continue
205
+ cprops = element_props(child, platform)
206
+ target = locate(child, cprops)
207
+ if target is not None:
208
+ via = True
209
+ # What the tester sees named is the text inside it.
210
+ props = {**props, **{k: v for k, v in cprops.items() if k in ("name", "automation_id")}}
211
+ break
212
+ field = is_field(kind)
213
+ if platform == "android":
214
+ secure = node.attrib.get("password") == "true"
215
+ prompt = props.get("package", "") in PERMISSION_PACKAGES
216
+ else:
217
+ secure = kind == "XCUIElementTypeSecureTextField"
218
+ prompt = in_alert and props.get("name") in IOS_PERMISSION_ANSWERS
219
+ if target is not None and not field and not tappable(node) and screen_area and box[2] * box[3] > screen_area * LAYOUT_SHARE:
220
+ # A layout over most of the screen (content, a fragment's frame): a click on empty space is not a step.
221
+ target = None
222
+ label = (props.get("name") or props.get("automation_id") or "").replace("\n", " ").strip()
223
+ out.append({
224
+ "box": box,
225
+ "target": target,
226
+ "label": label[: MAX_LABEL - 1] + "…" if len(label) > MAX_LABEL else label,
227
+ # What it shows, for a check added in the review (steps/NNN.json); never sent to the live page.
228
+ "text": (props.get("text") or "").replace("\n", " ").strip()[:MAX_CHECK_TEXT],
229
+ "kind": kind.rsplit(".", 1)[-1].replace("XCUIElementType", "")[:40],
230
+ **({"field": True} if field else {}),
231
+ **({"secure": True} if secure else {}),
232
+ **({"prompt": True} if prompt else {}),
233
+ **({"inner": True} if via else {}),
234
+ **({"other_app": True} if props.get("package") and props.get("package") != app_id and platform == "android" else {}),
235
+ })
236
+ if len(out) >= MAX_ELEMENTS:
237
+ break
238
+ return out
239
+
240
+
241
+ def _int(cmd: Mapping[str, Any], key: str, lo: int, hi: int) -> int:
242
+ v = cmd.get(key)
243
+ if not isinstance(v, int) or isinstance(v, bool) or not lo <= v <= hi:
244
+ raise RecordRefused(f"{key} must be a whole number from {lo} to {hi}")
245
+ return v
246
+
247
+
248
+ class MobileRecorder:
249
+ """One recording: the device session, the screen last sent, and the steps so far."""
250
+
251
+ def __init__(self, driver: Any, spec: Any, name: str, secrets: Mapping[str, str], out_dir: Path, emit: Callable[[Dict[str, Any]], None], log: Callable[..., None], settle: float = SETTLE, sleep: Callable[[float], None] = time.sleep) -> None:
252
+ self.driver = driver
253
+ self.spec = spec
254
+ self.name = name
255
+ # name → value, of mobile.secrets that are set: typed by name, matched to keep plain text from holding one.
256
+ self.secrets = {k: v for k, v in secrets.items() if v}
257
+ self.out = out_dir
258
+ self.emit = emit
259
+ self.log = log
260
+ self.settle = settle
261
+ self.sleep = sleep
262
+ self.steps: List[Dict[str, Any]] = [{"op": "launch"}]
263
+ # Each step's picture and the controls it shows (steps/NNN.png and .json): the app after the step.
264
+ self.shots: List[Optional[Tuple[bytes, str]]] = [None]
265
+ self.dismiss: List[Dict[str, Any]] = []
266
+ self.skipped: List[Dict[str, str]] = []
267
+ self.used_secrets: List[str] = []
268
+ self.seq = 0
269
+ self.frame = 0
270
+ # The step this command recorded, whose picture is taken once the app has drawn what it did.
271
+ self.fresh: Optional[int] = None
272
+ # The last few screens' controls, by number: a click made on one of them is matched to the screen now.
273
+ self.recent: Dict[int, List[Dict[str, Any]]] = {}
274
+ self.size: Optional[Tuple[int, int]] = None
275
+ self.elements: List[Dict[str, Any]] = []
276
+ self.png: Optional[bytes] = None
277
+ (out_dir / "live").mkdir(parents=True, exist_ok=True)
278
+ (out_dir / "steps").mkdir(exist_ok=True)
279
+
280
+ # -- the screen ---------------------------------------------------------------------------------------------
281
+
282
+ def snapshot(self) -> None:
283
+ """
284
+ Read the screen and send it: its picture as live/screen.png (one file, replaced, numbered by ``frame``), its
285
+ controls as an event. ``seq`` names the controls: it changes only when they do, so a click the page made on a
286
+ screen read again since, unchanged, still counts.
287
+ """
288
+ png = self.driver.screenshot_png() or b""
289
+ source = self.driver.source()
290
+ platform = self.spec.platform
291
+ elements = parse_screen(source, platform, self.spec.app_id)
292
+ size = png_size(png)
293
+ if platform == "ios" or size is None:
294
+ # XCUITest's page source is in points, its screenshot in pixels: boxes are drawn over the window's size.
295
+ r = self.driver.window_size()
296
+ size = (int(r.get("width", 0)), int(r.get("height", 0)))
297
+ if not self.seq or elements != self.elements or size != self.size:
298
+ self.seq += 1
299
+ self.recent[self.seq] = elements
300
+ for old in [k for k in self.recent if k <= self.seq - RECENT_SCREENS]:
301
+ del self.recent[old]
302
+ self.elements = elements
303
+ self.size = size
304
+ self.frame += 1
305
+ self.png = png or None
306
+ if png:
307
+ tmp = self.out / "live" / "screen.tmp"
308
+ tmp.write_bytes(png)
309
+ os.replace(tmp, self.out / "live" / "screen.png")
310
+ if self.fresh is not None and self.png and self.fresh <= len(self.shots):
311
+ # The last step's picture is the app after it (what a check is picked from in the review): it follows the
312
+ # screen until the next step, so a page that was still loading is shown as it ended up.
313
+ self.shots[self.fresh - 1] = (self.png, self._controls())
314
+ self._write_shot(self.fresh, self.shots[self.fresh - 1])
315
+ self.emit({
316
+ "type": "screen",
317
+ "seq": self.seq,
318
+ "frame": self.frame,
319
+ "width": size[0],
320
+ "height": size[1],
321
+ "image": bool(png),
322
+ "elements": [{"box": e["box"], "label": e["label"], "kind": e["kind"], "usable": e["target"] is not None, **{k: True for k in ("field", "secure", "prompt", "inner", "other_app") if e.get(k)}} for e in self.elements],
323
+ })
324
+
325
+ def _element(self, cmd: Mapping[str, Any]) -> Dict[str, Any]:
326
+ seq = _int(cmd, "seq", 1, 10**9)
327
+ el = _int(cmd, "el", 0, MAX_ELEMENTS - 1)
328
+ if seq != self.seq:
329
+ # A screen read a moment ago (a carousel that turns, a clock): the control clicked there counts when one
330
+ # with the very same locator is on the screen now.
331
+ old = self.recent.get(seq)
332
+ picked = old[el] if old is not None and el < len(old) else None
333
+ now = next((e for e in self.elements if picked and picked["target"] is not None and e["target"] == picked["target"]), None)
334
+ if now is None:
335
+ raise RecordRefused("The screen changed before that reached the device: do it again on the screen shown now.")
336
+ return now
337
+ if el >= len(self.elements):
338
+ raise RecordRefused("That control is not on the screen shown now.")
339
+ return self.elements[el]
340
+
341
+ # -- steps ----------------------------------------------------------------------------------------------------
342
+
343
+ def _record(self, step: Dict[str, Any], shot: Optional[bytes], *, dismiss: bool = False) -> None:
344
+ if dismiss:
345
+ target = step["target"]
346
+ if target not in self.dismiss:
347
+ self.dismiss.append(target)
348
+ self.emit({"type": "recorded", "index": 0, "op": "dismiss", "target": target})
349
+ return
350
+ if len(self.steps) >= MAX_STEPS:
351
+ raise RecordRefused(f"A recording holds at most {MAX_STEPS} steps: stop it and record the rest as another.")
352
+ self.steps.append(step)
353
+ # The screen it was done on, until the screen after it is read (command()).
354
+ kept = (shot, self._controls()) if shot else None
355
+ self.shots.append(kept)
356
+ index = len(self.steps)
357
+ self._write_shot(index, kept)
358
+ self.fresh = index
359
+ self.emit({"type": "recorded", "index": index, "op": step["op"], **({"target": step["target"]} if step.get("target") else {}), **({"value": step["text"]} if isinstance(step.get("text"), str) else {}), **({"keys": step["keys"]} if step.get("keys") else {}), **({"direction": step["direction"]} if step.get("direction") else {}), **({"seconds": step["seconds"]} if step.get("seconds") is not None else {})})
360
+
361
+ def _renumber(self) -> None:
362
+ """After a step was removed: the step pictures by their new numbers, and the page's list again."""
363
+ for f in [*(self.out / "steps").glob("*.png"), *(self.out / "steps").glob("*.json")]:
364
+ f.unlink()
365
+ for i, kept in enumerate(self.shots, 1):
366
+ self._write_shot(i, kept)
367
+ self.emit({"type": "renumbered", "steps": [{"index": i, "op": s["op"], **({"target": s["target"]} if s.get("target") else {}), **({"value": s["text"]} if isinstance(s.get("text"), str) else {"value": s["value"]} if isinstance(s.get("value"), str) else {}), **({"keys": s["keys"]} if s.get("keys") else {}), **({"direction": s["direction"]} if s.get("direction") else {})} for i, s in enumerate(self.steps, 1)]})
368
+
369
+ def _controls(self) -> str:
370
+ """The controls on the screen shown, as the review reads them (steps/NNN.json: its size and each control's box,
371
+ locator and text), only those a step could use."""
372
+ w, h = self.size or (0, 0)
373
+ controls = []
374
+ for e in self.elements:
375
+ t = e.get("target")
376
+ if not t or "index" in t:
377
+ continue # one of several alike: the review's check could not tell them apart
378
+ x, y, bw, bh = e["box"]
379
+ if x < 0 or y < 0 or x + bw > w or y + bh > h:
380
+ continue
381
+ controls.append({"x": x, "y": y, "w": bw, "h": bh, **{k: t[k] for k in ("automation_id", "name", "control_type") if t.get(k)}, **({"text": e["text"]} if e.get("text") else {})})
382
+ return json.dumps({"w": w, "h": h, "controls": controls[:300]}, ensure_ascii=False)
383
+
384
+ def _write_shot(self, index: int, kept: Optional[Tuple[bytes, str]]) -> None:
385
+ if not kept:
386
+ return
387
+ (self.out / "steps" / f"{index:03d}.png").write_bytes(kept[0])
388
+ (self.out / "steps" / f"{index:03d}.json").write_text(kept[1], encoding="utf-8")
389
+
390
+ def write_shots(self) -> None:
391
+ """shots.json: which picture is each step's, by what it does and to which control (library.ts recordingShots)."""
392
+ rows = [{"index": i, "file": f"steps/{i:03d}.png", "op": s["op"], **({"target": s["target"]} if s.get("target") else {})} for i, (s, kept) in enumerate(zip(self.steps, self.shots), 1) if kept]
393
+ (self.out / "shots.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8")
394
+
395
+ def _find(self, target: Mapping[str, Any]) -> Any:
396
+ try:
397
+ return self.driver.find(target, FIND_SECONDS)
398
+ except Exception as e: # noqa: BLE001 - said to the tester, the step not kept
399
+ raise RecordRefused(f"That control could not be found again by what identifies it ({_describe(target)}), so a replay would not find it either; nothing was done.") from e
400
+
401
+ def command(self, cmd: Mapping[str, Any]) -> bool:
402
+ """Carry out one command from the page. False when it was stop."""
403
+ op = cmd.get("cmd")
404
+ if op not in COMMANDS:
405
+ raise RecordRefused("The recorder does not take that command.")
406
+ if op == "stop":
407
+ return False
408
+ if op == "refresh":
409
+ self.snapshot()
410
+ return True
411
+ if op == "undo":
412
+ if len(self.steps) <= 1:
413
+ raise RecordRefused("Nothing to undo: the recording has only the app's start.")
414
+ self.steps.pop()
415
+ self.shots.pop()
416
+ self.fresh = None
417
+ self._renumber()
418
+ self.log("Removed the last step from the recording (what it did on the device stays done).")
419
+ return True
420
+ if op == "delete":
421
+ if len(self.steps) <= 1:
422
+ raise RecordRefused("Nothing to remove: the recording has only the app's start.")
423
+ n = _int(cmd, "n", 2, len(self.steps))
424
+ del self.steps[n - 1]
425
+ del self.shots[n - 1]
426
+ self.fresh = None
427
+ self._renumber()
428
+ return True
429
+ shot = self.png
430
+ if op in ELEMENT_COMMANDS:
431
+ el = self._element(cmd)
432
+ target = el["target"]
433
+ if target is None:
434
+ self.skipped.append({"action": f"{op} on {el['label'] or el['kind'] or 'a control'}", "reason": "it has neither an id nor a text, so a replay could not find it"})
435
+ raise RecordRefused("That control has neither an id nor a text, so a replay could not find it: tap something with a label, or ask the app's developers for an accessibility id.")
436
+ self._element_command(op, cmd, el, target, shot)
437
+ elif op in ("swipe", "scroll"):
438
+ direction = cmd.get("direction")
439
+ if direction not in SWIPE_DIRECTIONS:
440
+ raise RecordRefused("A swipe or scroll goes up, down, left or right.")
441
+ target = None
442
+ if op == "swipe" and cmd.get("el") is not None:
443
+ el = self._element(cmd)
444
+ target = el["target"]
445
+ if target is None:
446
+ raise RecordRefused("That control has neither an id nor a text: swipe across the screen instead.")
447
+ control = self._find(target) if target else None
448
+ (self.driver.swipe if op == "swipe" else self.driver.scroll)(direction, control)
449
+ self._record({"op": op, "direction": direction, **({"target": target} if target else {})}, shot)
450
+ elif op == "back":
451
+ self.driver.back()
452
+ self._record({"op": "back"}, shot)
453
+ elif op == "hide_keyboard":
454
+ self.driver.hide_keyboard()
455
+ self._record({"op": "hide_keyboard"}, shot)
456
+ elif op == "keys":
457
+ key = cmd.get("key")
458
+ if key not in MOBILE_KEYS:
459
+ raise RecordRefused(f"A key on a phone is one of {', '.join(MOBILE_KEYS)}.")
460
+ self.driver.press_key(key)
461
+ self._record({"op": "keys", "keys": key}, shot)
462
+ elif op == "wait":
463
+ seconds = _int(cmd, "seconds", 1, int(MAX_WAIT_SECONDS))
464
+ self.sleep(seconds)
465
+ self._record({"op": "wait", "seconds": seconds}, shot)
466
+ self.sleep(self.settle)
467
+ self.snapshot()
468
+ return True
469
+
470
+ def _element_command(self, op: str, cmd: Mapping[str, Any], el: Mapping[str, Any], target: Dict[str, Any], shot: Optional[bytes]) -> None:
471
+ if op == "check":
472
+ control = self._find(target)
473
+ text = (self.driver.text_of(control) or "").split("\n")[0].strip()
474
+ masked = _mask(text, self.secrets)
475
+ step: Dict[str, Any] = {"op": "expect", "target": target}
476
+ if text and len(text) <= MAX_CHECK_TEXT and masked == text and not el.get("secure"):
477
+ step["text"] = text
478
+ self._record(step, shot)
479
+ self.log(f"Check: {_describe(target)}" + (f" shows “{step['text']}”" if step.get("text") else " is on screen"))
480
+ return
481
+ if op == "wait_for":
482
+ self._find(target)
483
+ self._record({"op": "wait_for", "target": target}, shot)
484
+ return
485
+ if op == "type":
486
+ if not el.get("field"):
487
+ raise RecordRefused("That is not a text field: tap the field to type into.")
488
+ secret = cmd.get("secret")
489
+ if secret is not None:
490
+ if not isinstance(secret, str) or not SECRET_NAME.match(secret) or secret not in self.secrets:
491
+ raise RecordRefused("That secret is not one of mobile.secrets or the environment's secrets that is set here.")
492
+ value, text = self.secrets[secret], "{{secret:%s}}" % secret
493
+ if secret not in self.used_secrets:
494
+ self.used_secrets.append(secret)
495
+ else:
496
+ raw = cmd.get("text")
497
+ if not isinstance(raw, str) or not raw or len(raw) > MAX_TEXT or _CONTROL_CHARS.search(raw):
498
+ raise RecordRefused(f"Type text of one line, up to {MAX_TEXT} characters.")
499
+ if el.get("secure"):
500
+ raise RecordRefused("That is a password field: type one of the saved secrets, by its name, so the password is never written in the test.")
501
+ if "{{" in raw or "}}" in raw:
502
+ raise RecordRefused("Text with {{ or }} would be read as a placeholder: leave them out.")
503
+ value, text = raw, _mask(raw, self.secrets)
504
+ for name in self.secrets:
505
+ if "{{secret:%s}}" % name in text and name not in self.used_secrets:
506
+ self.used_secrets.append(name)
507
+ control = self._find(target)
508
+ self.driver.type_text(control, value)
509
+ self._record({"op": "type", "target": target, "text": text}, shot)
510
+ return
511
+ control = self._find(target)
512
+ if op == "tap":
513
+ self.driver.click(control)
514
+ elif op == "double_tap":
515
+ self.driver.click(control, double=True)
516
+ else:
517
+ self.driver.long_press(control)
518
+ last = self.steps[-1] if len(self.steps) > 1 else None
519
+ if op == "tap" and not el.get("prompt") and last and last["op"] == "tap" and is_dropdown(str(last["target"].get("control_type") or "")) and isinstance(target.get("name"), str) and target["name"].strip():
520
+ # The item picked in the drop-down the last step opened: one step that picks it by its text.
521
+ self.steps[-1] = {"op": "select", "target": last["target"], "value": target["name"]}
522
+ index = len(self.steps)
523
+ self.fresh = index
524
+ self.emit({"type": "recorded", "index": index, "op": "select", "target": last["target"], "value": target["name"]})
525
+ self.log(f"Choose “{target['name']}” in {_describe(last['target'])}: kept as one step.")
526
+ elif op == "tap" and el.get("prompt"):
527
+ self._record({"op": "tap", "target": target}, shot, dismiss=True)
528
+ self.log(f"“{el['label']}” answers a system prompt: kept in the workflow's dismiss list, tapped whenever a replay is asked.")
529
+ else:
530
+ self._record({"op": op, "target": target}, shot)
531
+
532
+ def workflow(self) -> Dict[str, Any]:
533
+ return validate({"format": MOBILE_FORMAT, "name": self.name, "app": self.spec.name, **({"dismiss": self.dismiss} if self.dismiss else {}), "steps": self.steps})
534
+
535
+
536
+ def _describe(target: Mapping[str, Any]) -> str:
537
+ parts = [f"id {target['automation_id']}" if target.get("automation_id") else "", f"“{str(target['name'])[:60]}”" if target.get("name") else ""]
538
+ return " ".join(p for p in parts if p) or "the control"
539
+
540
+
541
+ def run_record(req: Mapping[str, Any], events: Any, stop: Any, commands: "queue.Queue[Mapping[str, Any]]", driver_factory: Callable[[], Any], apps: Mapping[str, Any], secret_names: List[str], out: Path, sleep: Callable[[float], None] = time.sleep, refresh: float = REFRESH_SECONDS, settle: float = SETTLE) -> Dict[str, Any]:
542
+ app = str(req.get("app") or "")
543
+ if app not in apps:
544
+ raise WorkflowError(f"app {app!r} is not in mobile.apps or the environment's mobile apps (configured: {', '.join(sorted(apps)) or 'none'})")
545
+ spec = apps[app]
546
+ name = str(req.get("name") or app).strip()[:200] or app
547
+ secrets = {n: os.environ.get(n, "") for n in secret_names}
548
+ started = time.time()
549
+ driver = driver_factory()
550
+ recorder: Optional[MobileRecorder] = None
551
+ error = ""
552
+ stopped_by = "stopped"
553
+ try:
554
+ events.log(f"Starting {app} on the device (a device cloud can take a minute or two)…")
555
+ driver.launch(spec)
556
+ recorder = MobileRecorder(driver, spec, name, secrets, out, events.emit, events.log, settle=settle, sleep=sleep)
557
+ recorder.snapshot()
558
+ events.log("Recording: tap, type and swipe on the screen here; each action is done on the device and becomes a step.")
559
+ while not stop.is_set():
560
+ try:
561
+ cmd = commands.get(timeout=refresh)
562
+ except queue.Empty:
563
+ recorder.snapshot()
564
+ continue
565
+ try:
566
+ if not recorder.command(cmd):
567
+ break
568
+ except RecordRefused as e:
569
+ events.emit({"type": "refused", "text": str(e)})
570
+ events.log(str(e), "warn")
571
+ except Exception as e: # noqa: BLE001 - the device said no: the recording goes on
572
+ events.log(f"That did not work on the device: {str(e)[:300]}", "warn")
573
+ try:
574
+ recorder.snapshot()
575
+ except Exception:
576
+ pass
577
+ except Exception as e: # noqa: BLE001 - what was recorded is kept
578
+ error = f"The recording stopped with an error: {type(e).__name__}: {e}"[:2000]
579
+ stopped_by = "error"
580
+ events.log(error, "error")
581
+ finally:
582
+ try:
583
+ driver.close()
584
+ except Exception:
585
+ pass
586
+ try:
587
+ (out / "live" / "screen.png").unlink()
588
+ except OSError:
589
+ pass
590
+ workflow_file = out / "workflow.yaml"
591
+ recorded = len(recorder.steps) - 1 if recorder else 0
592
+ checks = sum(1 for s in recorder.steps if s["op"] == "expect") if recorder else 0
593
+ if recorder and recorded:
594
+ save(recorder.workflow(), workflow_file)
595
+ recorder.write_shots()
596
+ return {
597
+ "mode": "record",
598
+ "ok": recorded > 0 and not error,
599
+ "app": app,
600
+ "name": name,
601
+ "seconds": int(time.time() - started),
602
+ "recorded": recorded,
603
+ "checks": checks,
604
+ "secrets": recorder.used_secrets if recorder else [],
605
+ "skipped": recorder.skipped if recorder else [],
606
+ "stopped_by": stopped_by,
607
+ "workflow": str(workflow_file) if recorder and recorded else None,
608
+ "steps": [{"index": i, "op": s["op"], "ok": True, "ms": 0, "target": s.get("target"), "screenshot": f"steps/{i:03d}.png" if (out / "steps" / f"{i:03d}.png").is_file() else None} for i, s in enumerate(recorder.steps, 1)] if recorder else [],
609
+ "error": error or ("" if recorded else "Nothing was recorded."),
610
+ }