@capagents/forgeqe 3.2.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/HOW_TO_USE.md +25 -2
  2. package/dist/docs-site/docs/area-api/index.html +1 -1
  3. package/dist/docs-site/docs/area-mobile/index.html +28 -8
  4. package/dist/docs-site/docs/area-quality/index.html +10 -0
  5. package/dist/docs-site/docs/get-started/index.html +4 -1
  6. package/dist/docs-site/docs/mobile/index.html +19 -7
  7. package/dist/docs-site/docs/search.js +1 -1
  8. package/dist/docs-site/docs/web-app/index.html +2 -1
  9. package/dist/forgeqe.js +1895 -1884
  10. package/dist/web/assets/{3d-force-graph-Bhmgjf_7.js → 3d-force-graph-ByL874l5.js} +1 -1
  11. package/dist/web/assets/Agent-Drs4mcil.js +8 -0
  12. package/dist/web/assets/{AgentWork-D0MS10up.js → AgentWork-DLcCZTgu.js} +2 -2
  13. package/dist/web/assets/ApiTests-BcrTspwJ.js +10 -0
  14. package/dist/web/assets/Browse-D9eaDrZT.js +1 -0
  15. package/dist/web/assets/Chat-CMNf9-ys.js +3 -0
  16. package/dist/web/assets/{CommandPalette-rY8rp79k.js → CommandPalette-Bcf1Muan.js} +1 -1
  17. package/dist/web/assets/Compare-V5xKnwGO.js +1 -0
  18. package/dist/web/assets/Cost-DC3DYthD.js +1 -0
  19. package/dist/web/assets/{Data-CFyxbwPS.js → Data-DzrP-MdL.js} +4 -4
  20. package/dist/web/assets/Desktop-DjTq9eAr.js +1 -0
  21. package/dist/web/assets/DesktopReview-Buecn3n5.js +2 -0
  22. package/dist/web/assets/DeviceScreen-CoArZGyY.js +1 -0
  23. package/dist/web/assets/{Evidence-BlTkmzfE.js → Evidence-D6VvlFNK.js} +1 -1
  24. package/dist/web/assets/{Explore-DyGqAEff.js → Explore-YkonRPmA.js} +2 -2
  25. package/dist/web/assets/{Features-BjPR9gCe.js → Features-BKB4iSRj.js} +1 -1
  26. package/dist/web/assets/Flags-4GGW38Xu.js +2 -0
  27. package/dist/web/assets/Flaky-BRcLjYrP.js +1 -0
  28. package/dist/web/assets/Impact-CvuahLDQ.js +3 -0
  29. package/dist/web/assets/Jobs-DBCw8Z8I.js +5 -0
  30. package/dist/web/assets/KindPage-Ige-qO2t.js +6 -0
  31. package/dist/web/assets/LiveDevice-DI7Bq6ag.js +1 -0
  32. package/dist/web/assets/Migration-CEwXGs4c.js +8 -0
  33. package/dist/web/assets/Mobile-BqyFTBeG.js +1 -0
  34. package/dist/web/assets/Observability-B2Y1pHpD.js +1 -0
  35. package/dist/web/assets/PageAgent-BRhWi7LL.js +1 -0
  36. package/dist/web/assets/Product-CXIbmmMF.js +12 -0
  37. package/dist/web/assets/{Production-C8eGcwCi.js → Production-BOy7ew7l.js} +1 -1
  38. package/dist/web/assets/Quality-Dtcq2AWE.js +1 -0
  39. package/dist/web/assets/{Readiness-BWlbiTeu.js → Readiness-B53Drc7i.js} +1 -1
  40. package/dist/web/assets/Record-BuCIDb1d.js +1 -0
  41. package/dist/web/assets/Regression-BpPXCQIv.js +5 -0
  42. package/dist/web/assets/{RelationGraph-CzR_Hs8A.js → RelationGraph-UXFyQOKO.js} +1 -1
  43. package/dist/web/assets/Reports-CWCa9uof.js +2 -0
  44. package/dist/web/assets/Response-C6EmnnQz.js +9 -0
  45. package/dist/web/assets/Responsive-Bl6i7kB3.js +3 -0
  46. package/dist/web/assets/{RunDiff-COaxhvKm.js → RunDiff-CWf9Bkmu.js} +1 -1
  47. package/dist/web/assets/Runs-C0tfrB_j.js +2 -0
  48. package/dist/web/assets/Settings-tgCcBEwu.js +21 -0
  49. package/dist/web/assets/{Steps-CN4n8U1I.js → Steps-xASPoq1N.js} +3 -3
  50. package/dist/web/assets/{TestCases-BEfJFp5h.js → TestCases-Cm4KwWIP.js} +1 -1
  51. package/dist/web/assets/TestData-DMV5S00V.js +2 -0
  52. package/dist/web/assets/{TestDebt-DIYhbhjh.js → TestDebt-D54mt0ZT.js} +1 -1
  53. package/dist/web/assets/TestManagement-DBFlK8Xe.js +4 -0
  54. package/dist/web/assets/WhatsNew-Dp-zP-jw.js +1 -0
  55. package/dist/web/assets/agents-DPabR9dS.js +1 -0
  56. package/dist/web/assets/{coverage-DCtiu73T.js → coverage-xSRsKFL6.js} +1 -1
  57. package/dist/web/assets/dataParts-BPff7ClX.js +3 -0
  58. package/dist/web/assets/desktopAppPath-BVJxel_D.js +1 -0
  59. package/dist/web/assets/{diff-DEgLgw6R.js → diff-BXu8cULX.js} +1 -1
  60. package/dist/web/assets/{highlight-DSLpJ_Dq.js → highlight-DCCKhwHj.js} +1 -1
  61. package/dist/web/assets/index-BsAaOk_G.js +64 -0
  62. package/dist/web/assets/index-CgpH1pj9.css +2 -0
  63. package/dist/web/assets/input-BmJ7dt1C.js +1 -0
  64. package/dist/web/assets/pageBack-BNLSF2VR.js +3 -0
  65. package/dist/web/assets/palette-BS9ixqiJ.js +1 -0
  66. package/dist/web/assets/{paletteCommands-fwv5XVOS.js → paletteCommands-C3knXWbA.js} +1 -1
  67. package/dist/web/assets/{parts-CkI14hIv.js → parts-69Ei7EPi.js} +1 -1
  68. package/dist/web/assets/productParts-CrAb3-j0.js +1 -0
  69. package/dist/web/assets/{qualityParts-8KI3JCY8.js → qualityParts-BQTnBwPs.js} +1 -1
  70. package/dist/web/assets/{recordTest-kf2ykEQF.js → recordTest-DVJCNI0y.js} +1 -1
  71. package/dist/web/assets/{stepper-CQSK6KS0.js → stepper-t0O_8eQo.js} +1 -1
  72. package/dist/web/index.html +6 -6
  73. package/docs/MOBILE.md +22 -7
  74. package/docs/WEB_APP.md +2 -1
  75. package/docs/user-guide.html +23 -2
  76. package/forgeqe.example.yaml +1 -0
  77. package/package.json +1 -1
  78. package/py/forgeqe_engine/copilot_gateway.py +80 -1
  79. package/py/forgeqe_engine/persona.py +197 -10
  80. package/py/forgeqe_engine/service.py +2 -2
  81. package/py/forgeqe_mobile/a11y.py +322 -0
  82. package/py/forgeqe_mobile/appium_driver.py +16 -0
  83. package/py/forgeqe_mobile/live.py +225 -0
  84. package/py/forgeqe_mobile/service.py +102 -4
  85. package/dist/web/assets/Agent-Dx4aOB_h.js +0 -8
  86. package/dist/web/assets/ApiTests-DUoEh0nX.js +0 -10
  87. package/dist/web/assets/Browse-BGgyLuL3.js +0 -1
  88. package/dist/web/assets/Chat-CEHUI2ty.js +0 -3
  89. package/dist/web/assets/Compare-B_NCvogR.js +0 -1
  90. package/dist/web/assets/Cost-sm-6tWRQ.js +0 -1
  91. package/dist/web/assets/Desktop-A_D4LTis.js +0 -1
  92. package/dist/web/assets/DesktopReview-CM7xmpHS.js +0 -2
  93. package/dist/web/assets/Flags-C_DneXS9.js +0 -2
  94. package/dist/web/assets/Flaky-l5ugC_ER.js +0 -1
  95. package/dist/web/assets/Impact-7TXQHcsW.js +0 -3
  96. package/dist/web/assets/Jobs-xRLNI-8l.js +0 -5
  97. package/dist/web/assets/KindPage-BZu1Zo4S.js +0 -6
  98. package/dist/web/assets/Migration-DKsyDwDO.js +0 -8
  99. package/dist/web/assets/Observability-CVwKJ-fI.js +0 -1
  100. package/dist/web/assets/PageAgent-C1X5ot6v.js +0 -1
  101. package/dist/web/assets/Product-iHqLyIhD.js +0 -12
  102. package/dist/web/assets/Quality-BVsN6u0E.js +0 -1
  103. package/dist/web/assets/Record-C7qgNFqs.js +0 -1
  104. package/dist/web/assets/Regression-ChleHlqe.js +0 -5
  105. package/dist/web/assets/Reports-CIcKyoHH.js +0 -2
  106. package/dist/web/assets/Response-D2ZeO8uW.js +0 -9
  107. package/dist/web/assets/Responsive-DCfw-Oz3.js +0 -3
  108. package/dist/web/assets/Runs-3qx2qf56.js +0 -2
  109. package/dist/web/assets/Settings-DG2k3Lno.js +0 -21
  110. package/dist/web/assets/TestData-SO2qqaAF.js +0 -2
  111. package/dist/web/assets/TestManagement-D7q6G3YN.js +0 -4
  112. package/dist/web/assets/WhatsNew-DqBLhhgk.js +0 -1
  113. package/dist/web/assets/agents-BUWN-VJv.js +0 -1
  114. package/dist/web/assets/dataParts-BdmBLsU9.js +0 -3
  115. package/dist/web/assets/index-DAteDsgB.css +0 -2
  116. package/dist/web/assets/index-RJ1kEHuo.js +0 -64
  117. package/dist/web/assets/input-Be3YOEK2.js +0 -1
  118. package/dist/web/assets/logLevel-Dq8s6DZz.js +0 -3
  119. package/dist/web/assets/palette-Dcoz5crU.js +0 -1
  120. package/dist/web/assets/productParts-BOUMBM_H.js +0 -1
@@ -0,0 +1,322 @@
1
+ """
2
+ Accessibility of a native app's screens (mobile.accessibility, on by default): each new screen a replay or an explore
3
+ reaches is checked from its page source, as Appium gives it (Android's UiAutomator2 XML, iOS's XCUITest XML), and on iOS
4
+ also with Apple's own audit (XCUITest's performAccessibilityAudit, Xcode 15 and iOS 17 or later) when the device has it.
5
+
6
+ What is checked from the page source, by rule, each with its WCAG criterion:
7
+ - control-name (4.1.2): a control a person can activate (clickable, checkable; a button, link, switch, cell) that a screen
8
+ reader has nothing to say for: no text, label or content description on it or inside it.
9
+ - image-name (1.1.1): an image a screen reader stops on (focusable or accessible) with no description.
10
+ - field-label (1.3.1): a text field with no label, hint or placeholder.
11
+ - target-size (2.5.8): a control smaller than 24 by 24 (dp on Android, points on iOS); under the platform's own 48 dp or
12
+ 44 pt it is a minor finding (best practice, not a WCAG failure).
13
+ - duplicate-name (2.4.6, minor): several controls on one screen announced by the same name.
14
+
15
+ The page source is the app's own text, so it is read as data: only plain attribute values, clipped, and never run. The
16
+ results are accessibility.json in the run's folder, in the shape the web runs write (src/quality/budgets.ts A11yPage),
17
+ so the Quality pages, budgets and reports read them alike.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import hashlib
23
+ import json
24
+ import logging
25
+ import re
26
+ import xml.etree.ElementTree as ET
27
+ from pathlib import Path
28
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ ENGINE = "ForgeQE mobile checks"
33
+ MAX_SCREENS = 40
34
+ MAX_NODES = 3000
35
+ MAX_EXAMPLES = 5
36
+ ORDER = {"critical": 0, "serious": 1, "moderate": 2, "minor": 3}
37
+
38
+ RULES: Dict[str, Tuple[str, str, str]] = {
39
+ # rule: (WCAG criterion, level, what it means)
40
+ "control-name": ("4.1.2", "A", "Controls must have a name a screen reader can say"),
41
+ "image-name": ("1.1.1", "A", "Images a screen reader stops on must have a description"),
42
+ "field-label": ("1.3.1", "A", "Text fields must have a label, hint or placeholder"),
43
+ "target-size": ("2.5.8", "AA", "Touch targets must be at least 24 by 24"),
44
+ "target-size-platform": ("", "", "Touch targets should meet the platform's size (48 dp on Android, 44 pt on iOS)"),
45
+ "duplicate-name": ("2.4.6", "AA", "Controls on one screen should not share a name"),
46
+ }
47
+
48
+ ANDROID_IMAGE = re.compile(r"(^|\.)(ImageView|ImageButton|AppCompatImageView|AppCompatImageButton)$")
49
+ ANDROID_FIELD = re.compile(r"(^|\.)(EditText|AutoCompleteTextView|AppCompatEditText|TextInputEditText)$")
50
+ ANDROID_BUTTON = re.compile(r"(^|\.)(Button|ImageButton|CheckBox|RadioButton|Switch|ToggleButton|CompoundButton|AppCompatButton|MaterialButton|Chip)$")
51
+ IOS_CONTROLS = {"XCUIElementTypeButton", "XCUIElementTypeLink", "XCUIElementTypeSwitch", "XCUIElementTypeSlider", "XCUIElementTypeSegmentedControl", "XCUIElementTypeStepper", "XCUIElementTypeTab", "XCUIElementTypeMenuItem", "XCUIElementTypeCheckBox", "XCUIElementTypeRadioButton"}
52
+ IOS_FIELDS = {"XCUIElementTypeTextField", "XCUIElementTypeSecureTextField", "XCUIElementTypeSearchField", "XCUIElementTypeTextView"}
53
+ BOUNDS = re.compile(r"^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$")
54
+
55
+ # Apple's audit types (XCUIAccessibilityAuditType), as the WCAG criterion and impact ForgeQE reports them with.
56
+ IOS_AUDIT: Dict[str, Tuple[str, str, str, str]] = {
57
+ "contrast": ("ios-contrast", "1.4.3", "AA", "serious"),
58
+ "elementDetection": ("ios-element-detection", "4.1.2", "A", "serious"),
59
+ "hitRegion": ("ios-hit-region", "2.5.8", "AA", "serious"),
60
+ "sufficientElementDescription": ("ios-element-description", "4.1.2", "A", "critical"),
61
+ "dynamicType": ("ios-dynamic-type", "1.4.4", "AA", "serious"),
62
+ "textClipped": ("ios-text-clipped", "1.4.4", "AA", "moderate"),
63
+ "trait": ("ios-trait", "4.1.2", "A", "moderate"),
64
+ }
65
+
66
+
67
+ def _plain(v: Any, n: int) -> str:
68
+ return " ".join(str(v or "").split())[:n]
69
+
70
+
71
+ def _box(node: ET.Element, platform: str) -> Optional[Tuple[float, float, float, float]]:
72
+ a = node.attrib
73
+ try:
74
+ if platform == "android":
75
+ m = BOUNDS.match(a.get("bounds", ""))
76
+ if not m:
77
+ return None
78
+ x1, y1, x2, y2 = (int(g) for g in m.groups())
79
+ return float(x1), float(y1), float(x2 - x1), float(y2 - y1)
80
+ return float(a.get("x", "")), float(a.get("y", "")), float(a.get("width", "")), float(a.get("height", ""))
81
+ except ValueError:
82
+ return None
83
+
84
+
85
+ def _true(node: ET.Element, key: str) -> bool:
86
+ return node.attrib.get(key) == "true"
87
+
88
+
89
+ def _spoken(node: ET.Element, platform: str) -> str:
90
+ """What a screen reader says for a node on its own."""
91
+ a = node.attrib
92
+ if platform == "android":
93
+ return _plain(a.get("content-desc") or a.get("text") or a.get("hint") or "", 200)
94
+ return _plain(a.get("label") or "", 200)
95
+
96
+
97
+ def _spoken_within(node: ET.Element, platform: str) -> str:
98
+ """What a screen reader says for a control: its own name, else the text of what is inside it."""
99
+ own = _spoken(node, platform)
100
+ if own:
101
+ return own
102
+ for child in node.iter():
103
+ if child is not node:
104
+ said = _spoken(child, platform)
105
+ if said:
106
+ return said
107
+ return ""
108
+
109
+
110
+ def _example(node: ET.Element, platform: str, why: str) -> Dict[str, str]:
111
+ a = node.attrib
112
+ if platform == "android":
113
+ kind, ident = a.get("class") or node.tag, (a.get("resource-id") or "").split(":id/")[-1]
114
+ else:
115
+ kind, ident = a.get("type") or node.tag, a.get("name") or ""
116
+ shown = " ".join(f'{k}="{_plain(a.get(k), 60)}"' for k in ("resource-id", "content-desc", "text", "hint", "name", "label", "value", "bounds") if a.get(k))
117
+ return {"html": _plain(f"<{kind} {shown}>", 160), "target": _plain(ident or kind, 120), "text": _plain(why, 300)}
118
+
119
+
120
+ def _visible(node: ET.Element, platform: str) -> bool:
121
+ if platform == "ios":
122
+ return node.attrib.get("visible") != "false"
123
+ return node.attrib.get("displayed", "true") != "false"
124
+
125
+
126
+ def check_source(source: str, platform: str, density: Optional[float] = None) -> Dict[str, Any]:
127
+ """
128
+ One screen's issues from its page source. density: Android's dots per inch (160 is 1 dp per pixel); unknown, the
129
+ target sizes are not judged on Android. Returns {"issues": [...], "passed": [...]} in accessibility.json's shape.
130
+ """
131
+ try:
132
+ root = ET.fromstring(source.encode("utf-8"))
133
+ except (ET.ParseError, ValueError):
134
+ return {"issues": [], "passed": [], "error": "The screen's page source is not XML."}
135
+ found: Dict[str, List[Dict[str, str]]] = {r: [] for r in RULES}
136
+ checked = {r: 0 for r in RULES}
137
+ names: Dict[str, List[ET.Element]] = {}
138
+ android = platform == "android"
139
+ for i, node in enumerate(root.iter()):
140
+ if i >= MAX_NODES:
141
+ break
142
+ if not _visible(node, platform):
143
+ continue
144
+ a = node.attrib
145
+ kind = a.get("class") or a.get("type") or node.tag
146
+ if android:
147
+ control = (_true(node, "clickable") or _true(node, "checkable") or _true(node, "long-clickable")) and _true(node, "enabled") or bool(ANDROID_BUTTON.search(kind))
148
+ image = bool(ANDROID_IMAGE.search(kind)) and (_true(node, "focusable") or _true(node, "clickable"))
149
+ field = bool(ANDROID_FIELD.search(kind))
150
+ else:
151
+ control = kind in IOS_CONTROLS or (kind == "XCUIElementTypeCell" and a.get("accessible") == "true")
152
+ image = kind == "XCUIElementTypeImage" and a.get("accessible") == "true"
153
+ field = kind in IOS_FIELDS
154
+ if field:
155
+ checked["field-label"] += 1
156
+ label = _plain(a.get("hint") or a.get("content-desc") or a.get("text") if android else a.get("label") or a.get("placeholderValue"), 200)
157
+ # Android gives an empty field's hint as its text, so only a field with no text, hint or description is judged.
158
+ if not label:
159
+ found["field-label"].append(_example(node, platform, "This field has no label, hint or placeholder: a screen reader says only that it is a text field."))
160
+ continue
161
+ if image and not control:
162
+ checked["image-name"] += 1
163
+ if not _spoken(node, platform):
164
+ found["image-name"].append(_example(node, platform, "A screen reader stops on this image and has nothing to say for it."))
165
+ continue
166
+ if not control:
167
+ continue
168
+ checked["control-name"] += 1
169
+ said = _spoken_within(node, platform)
170
+ if not said:
171
+ found["control-name"].append(_example(node, platform, "A person can activate this control, but a screen reader has no name to say for it."))
172
+ else:
173
+ names.setdefault(said.lower(), []).append(node)
174
+ box = _box(node, platform)
175
+ if box and box[2] > 0 and box[3] > 0:
176
+ if android:
177
+ if not density or density <= 0:
178
+ continue
179
+ w, h = box[2] * 160 / density, box[3] * 160 / density
180
+ unit, platform_min = "dp", 48
181
+ else:
182
+ w, h = box[2], box[3]
183
+ unit, platform_min = "pt", 44
184
+ checked["target-size"] += 1
185
+ checked["target-size-platform"] += 1
186
+ if min(w, h) < 24:
187
+ found["target-size"].append(_example(node, platform, f"This control is {round(w)} by {round(h)} {unit}: smaller than 24 by 24, so it is hard to hit."))
188
+ elif min(w, h) < platform_min:
189
+ found["target-size-platform"].append(_example(node, platform, f"This control is {round(w)} by {round(h)} {unit}: under the platform's {platform_min} {unit}."))
190
+ for said, nodes in names.items():
191
+ checked["duplicate-name"] += 1
192
+ if len(nodes) > 1:
193
+ found["duplicate-name"].extend(_example(n, platform, f"{len(nodes)} controls on this screen are announced as {said!r}.") for n in nodes[:MAX_EXAMPLES])
194
+ impact = {"control-name": "critical", "image-name": "serious", "field-label": "serious", "target-size": "serious", "target-size-platform": "minor", "duplicate-name": "minor"}
195
+ issues = []
196
+ for rule, examples in found.items():
197
+ if not examples:
198
+ continue
199
+ wcag, level, help_text = RULES[rule]
200
+ issues.append({"rule": rule, "wcag": wcag, "level": level, "impact": impact[rule], "help": help_text, "helpUrl": "", "count": len(examples), "examples": examples[:MAX_EXAMPLES]})
201
+ issues.sort(key=lambda x: (ORDER[x["impact"]], -x["count"]))
202
+ return {"issues": issues, "passed": [r for r in RULES if checked[r] and not found[r]]}
203
+
204
+
205
+ def audit_issues(raw: Any) -> List[Dict[str, Any]]:
206
+ """Apple's audit results (performAccessibilityAudit), read as data, in accessibility.json's shape."""
207
+ if not isinstance(raw, list):
208
+ return []
209
+ by: Dict[str, Dict[str, Any]] = {}
210
+ for item in raw[:200]:
211
+ if not isinstance(item, Mapping):
212
+ continue
213
+ kind = str(item.get("auditType") or "")
214
+ # The driver names the type as XCUIAccessibilityAuditTypeContrast or contrast, by its version.
215
+ kind = re.sub(r"^XCUIAccessibilityAuditType", "", kind)
216
+ kind = kind[:1].lower() + kind[1:]
217
+ if kind not in IOS_AUDIT:
218
+ continue
219
+ rule, wcag, level, impact = IOS_AUDIT[kind]
220
+ issue = by.setdefault(rule, {"rule": rule, "wcag": wcag, "level": level, "impact": impact, "help": _plain(item.get("compactDescription") or kind, 200), "helpUrl": "", "count": 0, "examples": []})
221
+ issue["count"] += 1
222
+ if len(issue["examples"]) < MAX_EXAMPLES:
223
+ issue["examples"].append({"html": _plain(item.get("elementDescription") or item.get("element") or "", 160), "target": _plain(item.get("elementIdentifier") or "", 120), "text": _plain(item.get("detailedDescription") or "", 300)})
224
+ return sorted(by.values(), key=lambda x: (ORDER[x["impact"]], -x["count"]))
225
+
226
+
227
+ def screen_key(source: str) -> str:
228
+ """A screen's identity: its controls' kinds and ids, not their text or place, so typing into a field is the same screen."""
229
+ try:
230
+ root = ET.fromstring(source.encode("utf-8"))
231
+ except (ET.ParseError, ValueError):
232
+ return hashlib.sha256(source.encode("utf-8", "replace")).hexdigest()
233
+ parts = []
234
+ for i, node in enumerate(root.iter()):
235
+ if i >= MAX_NODES:
236
+ break
237
+ a = node.attrib
238
+ parts.append(f"{a.get('class') or a.get('type') or node.tag}|{a.get('resource-id') or a.get('name') or ''}")
239
+ return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest()
240
+
241
+
242
+ class ScreenChecks:
243
+ """The screens of one run: each new one checked once, at most MAX_SCREENS, then written as accessibility.json."""
244
+
245
+ def __init__(self, app: str, log: Optional[Callable[[str], None]] = None) -> None:
246
+ self.app = re.sub(r"[^\w-]", "", app)[:60] or "app"
247
+ self.log = log or (lambda _t: None)
248
+ self.pages: List[Dict[str, Any]] = []
249
+ self.seen: set = set()
250
+ self.density: Optional[float] = None
251
+ self.audit_ok: Optional[bool] = None
252
+
253
+ def check(self, driver: Any, title: str = "") -> None:
254
+ if len(self.pages) >= MAX_SCREENS:
255
+ return
256
+ try:
257
+ source = driver.source()
258
+ except Exception as ex: # noqa: BLE001 - a screen that cannot be read is skipped, never the run
259
+ logger.debug("accessibility: no page source: %s", ex)
260
+ return
261
+ if not source:
262
+ return
263
+ key = screen_key(source)
264
+ if key in self.seen:
265
+ return
266
+ self.seen.add(key)
267
+ platform = getattr(driver, "platform", "android")
268
+ if platform == "android" and self.density is None:
269
+ self.density = _density(driver)
270
+ result = check_source(source, platform, self.density)
271
+ issues = list(result["issues"])
272
+ engine = ENGINE
273
+ if platform == "ios" and self.audit_ok is not False:
274
+ raw = _audit(driver)
275
+ self.audit_ok = raw is not None
276
+ if raw is None:
277
+ self.log("Apple's accessibility audit is not available on this device (it needs Xcode 15 and iOS 17 or later): the page source checks run alone.")
278
+ else:
279
+ issues += audit_issues(raw)
280
+ engine = f"{ENGINE} + XCUITest audit"
281
+ n = len(self.pages) + 1
282
+ self.pages.append({
283
+ "url": f"app://{self.app}/screen-{n}",
284
+ "title": _plain(title, 120) or f"Screen {n}",
285
+ "engine": engine,
286
+ "tags": [platform],
287
+ "passed": result["passed"],
288
+ "incomplete": [],
289
+ "issues": sorted(issues, key=lambda x: (ORDER.get(x["impact"], 9), -x["count"])),
290
+ })
291
+
292
+ def write(self, out_dir: Path) -> Optional[str]:
293
+ if not self.pages:
294
+ return None
295
+ file = Path(out_dir) / "accessibility.json"
296
+ try:
297
+ file.write_text(json.dumps(self.pages, indent=2), encoding="utf-8")
298
+ except OSError as ex:
299
+ logger.warning("accessibility.json not written: %s", ex)
300
+ return None
301
+ return str(file)
302
+
303
+ def summary(self) -> Dict[str, int]:
304
+ issues = [i for p in self.pages for i in p["issues"]]
305
+ return {"screens": len(self.pages), **{k: sum(i["count"] for i in issues if i["impact"] == k) for k in ORDER}}
306
+
307
+
308
+ def _density(driver: Any) -> Optional[float]:
309
+ try:
310
+ dpi = driver.display_density()
311
+ return float(dpi) if dpi and float(dpi) > 0 else None
312
+ except Exception: # noqa: BLE001
313
+ return None
314
+
315
+
316
+ def _audit(driver: Any) -> Optional[List[Any]]:
317
+ try:
318
+ raw = driver.accessibility_audit()
319
+ except Exception as ex: # noqa: BLE001
320
+ logger.debug("accessibility audit not run: %s", ex)
321
+ return None
322
+ return raw if isinstance(raw, list) else None
@@ -761,6 +761,22 @@ class AppiumDriver:
761
761
  break
762
762
  return out
763
763
 
764
+ def display_density(self) -> Optional[float]:
765
+ """Android's screen density in dots per inch (UiAutomator2's mobile: getDisplayDensity); None elsewhere."""
766
+ if self.platform != "android":
767
+ return None
768
+ self._native()
769
+ dpi = self._script("mobile: getDisplayDensity", {})
770
+ return float(dpi) if isinstance(dpi, (int, float)) and dpi > 0 else None
771
+
772
+ def accessibility_audit(self) -> Optional[List[Any]]:
773
+ """Apple's accessibility audit of the screen (XCUITest's mobile: performAccessibilityAudit); None elsewhere."""
774
+ if self.platform != "ios":
775
+ return None
776
+ self._native()
777
+ out = self._script("mobile: performAccessibilityAudit", {})
778
+ return out if isinstance(out, list) else None
779
+
764
780
  def source(self) -> str:
765
781
  """The screen's page source (XML), as Appium gives it: the app's own text, so data."""
766
782
  self._native()
@@ -0,0 +1,225 @@
1
+ """
2
+ The device's screen while a mobile run is at work, for the web app's live view (the Mobile page, a chat's device pane).
3
+
4
+ One run keeps three small files in its folder's ``live/``, each replaced atomically, never more than the latest:
5
+
6
+ - ``screen.png``: the device's own screenshot (Appium's, or for Maestro on this computer, adb's or simctl's), only when
7
+ its bytes are a PNG;
8
+ - ``state.json``: the picture's frame number and time, the device, the driver and, for a cloud device, the link to its
9
+ own live view (``watch``: https on that cloud's fixed host only, built from the session id);
10
+ - ``step.json``: the step just done (its number, op, result and the control as plain one-line properties) and the one
11
+ next, when the workflow is known. A typed value is never written, only whether a secret was typed and its name.
12
+
13
+ Everything is removed when the run ends (``close``); the run's report keeps its own step pictures. Nothing here reaches
14
+ a model, and the web app reads these files back as untrusted.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ import shutil
22
+ import subprocess
23
+ import tempfile
24
+ import threading
25
+ import time
26
+ from pathlib import Path
27
+ from typing import Any, Callable, Dict, Mapping, Optional
28
+
29
+ PNG = b"\x89PNG\r\n\x1a\n"
30
+ # The longest a picture may be (a 4K screenshot is well under it).
31
+ MAX_PNG = 12 * 1024 * 1024
32
+ # How often the screen is read between steps, at least.
33
+ EVERY_SECONDS = 1.0
34
+ # A target's properties kept for the page: plain names of the workflow's grammar, one line, clipped.
35
+ TARGET_KEYS = ("automation_id", "name", "control_type", "class_name", "index")
36
+ MAX_TEXT = 120
37
+ SESSION = re.compile(r"^[A-Za-z0-9-]{8,80}$")
38
+ DEVICE_ID = re.compile(r"^[A-Za-z0-9._:-]{1,100}$")
39
+ SECRET = re.compile(r"\{\{secret:([A-Z][A-Z0-9_]{0,63})\}\}")
40
+ CONTROL = re.compile(r"[\x00-\x1f\x7f\u2028\u2029]")
41
+
42
+ # A cloud's Appium hub, and the address of its own view of one session.
43
+ CLOUD_VIEWS = {
44
+ "browserstack": ("hub-cloud.browserstack.com", "https://app-automate.browserstack.com/dashboard/v2/sessions/{id}"),
45
+ "testmu": ("mobile-hub.lambdatest.com", "https://appautomation.lambdatest.com/test?testID={id}"),
46
+ }
47
+
48
+
49
+ def _line(v: Any) -> str:
50
+ t = CONTROL.sub(" ", str(v)).strip()
51
+ return t[:MAX_TEXT]
52
+
53
+
54
+ def clean_target(target: Any) -> Dict[str, str]:
55
+ """A step's control as the page may show it: its known properties, plain one-line text, a placeholder kept as is."""
56
+ if not isinstance(target, Mapping):
57
+ return {}
58
+ return {k: _line(target[k]) for k in TARGET_KEYS if isinstance(target.get(k), (str, int)) and _line(target[k])}
59
+
60
+
61
+ def typed_note(step: Mapping[str, Any]) -> str:
62
+ """What a step types, as the page may say it: a secret only by its name, a value by its length, never the value."""
63
+ for k in ("text", "value"):
64
+ v = step.get(k)
65
+ if isinstance(v, str) and v:
66
+ names = SECRET.findall(v)
67
+ if names:
68
+ return f"secret {names[0]}"
69
+ return f"{len(v)} characters"
70
+ return ""
71
+
72
+
73
+ def watch_link(appium_url: str, session: Optional[str]) -> Optional[str]:
74
+ """The cloud's own view of this session, when the Appium hub is that cloud's fixed host and the id is an id."""
75
+ if not session or not SESSION.match(session):
76
+ return None
77
+ m = re.match(r"^https://(?:[^@/]+@)?([^/:]+)", appium_url or "")
78
+ host = m.group(1).lower() if m else ""
79
+ for hub, view in CLOUD_VIEWS.values():
80
+ if host == hub:
81
+ return view.format(id=session)
82
+ return None
83
+
84
+
85
+ def _write(path: Path, data: bytes) -> None:
86
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".live-")
87
+ try:
88
+ with os.fdopen(fd, "wb") as f:
89
+ f.write(data)
90
+ os.replace(tmp, path)
91
+ except BaseException:
92
+ try:
93
+ os.unlink(tmp)
94
+ except OSError:
95
+ pass
96
+ raise
97
+
98
+
99
+ def adb_grab(device: Optional[str], env: Mapping[str, str], run: Callable[..., Any] = subprocess.run) -> Callable[[], Optional[bytes]]:
100
+ """Android on this computer: ``adb [-s <id>] exec-out screencap -p``, an argument list, no shell."""
101
+ adb = shutil.which("adb", path=_android_path(env))
102
+ if device is not None and not DEVICE_ID.match(device):
103
+ raise ValueError("the device id is not an adb device id")
104
+
105
+ def grab() -> Optional[bytes]:
106
+ if not adb:
107
+ return None
108
+ args = [adb, *(["-s", device] if device else []), "exec-out", "screencap", "-p"]
109
+ proc = run(args, env=dict(env), capture_output=True, timeout=15, shell=False)
110
+ return proc.stdout if proc.returncode == 0 else None
111
+
112
+ return grab
113
+
114
+
115
+ def simctl_grab(device: Optional[str], env: Mapping[str, str], out: Path, run: Callable[..., Any] = subprocess.run) -> Callable[[], Optional[bytes]]:
116
+ """An iOS simulator on this Mac: ``xcrun simctl io <udid|booted> screenshot --type=png <file>``, then the file."""
117
+ xcrun = shutil.which("xcrun", path=env.get("PATH"))
118
+ if device is not None and not DEVICE_ID.match(device):
119
+ raise ValueError("the device id is not a simulator id")
120
+ file = out / "live" / ".grab.png"
121
+
122
+ def grab() -> Optional[bytes]:
123
+ if not xcrun:
124
+ return None
125
+ proc = run([xcrun, "simctl", "io", device or "booted", "screenshot", "--type=png", str(file)], env=dict(env), capture_output=True, timeout=15, shell=False)
126
+ if proc.returncode != 0 or not file.is_file() or file.is_symlink():
127
+ return None
128
+ try:
129
+ return file.read_bytes()[: MAX_PNG + 1]
130
+ finally:
131
+ try:
132
+ file.unlink()
133
+ except OSError:
134
+ pass
135
+
136
+ return grab
137
+
138
+
139
+ def _android_path(env: Mapping[str, str]) -> str:
140
+ extra = [str(Path(env[n]) / "platform-tools") for n in ("ANDROID_HOME", "ANDROID_SDK_ROOT") if env.get(n)]
141
+ return os.pathsep.join([*extra, env.get("PATH", "")])
142
+
143
+
144
+ class LiveScreen:
145
+ """The live files of one run. ``start`` reads the screen every second in the background; ``step`` after each step."""
146
+
147
+ def __init__(self, out: Path, grab: Callable[[], Optional[bytes]], *, device: str = "", driver: str = "appium", total: int = 0, steps: Optional[list] = None, every: float = EVERY_SECONDS, watch: Callable[[], Optional[str]] = lambda: None, clock: Callable[[], float] = time.time):
148
+ self.dir = out / "live"
149
+ self.grab = grab
150
+ self.device = _line(device)
151
+ self.driver = driver if driver in ("appium", "maestro") else "appium"
152
+ self.total = int(total) if isinstance(total, int) and total >= 0 else 0
153
+ self.steps = steps or []
154
+ self.every = max(0.5, float(every))
155
+ self.watch = watch
156
+ self.clock = clock
157
+ self.frame = 0
158
+ self.lock = threading.Lock()
159
+ self.stopping = threading.Event()
160
+ self.thread: Optional[threading.Thread] = None
161
+ self.dir.mkdir(parents=True, exist_ok=True)
162
+
163
+ def capture(self) -> bool:
164
+ """Read the screen once and keep it, when it is a PNG; a failed read keeps the last picture."""
165
+ with self.lock:
166
+ try:
167
+ png = self.grab()
168
+ except Exception:
169
+ return False
170
+ if not png or not png.startswith(PNG) or len(png) > MAX_PNG:
171
+ return False
172
+ self.frame += 1
173
+ _write(self.dir / "screen.png", png)
174
+ link = None
175
+ try:
176
+ link = self.watch()
177
+ except Exception:
178
+ link = None
179
+ state = {"frame": self.frame, "at": int(self.clock() * 1000), "device": self.device, "driver": self.driver, **({"watch": link} if link else {})}
180
+ _write(self.dir / "state.json", json.dumps(state).encode())
181
+ return True
182
+
183
+ def step(self, index: int, op: str, ok: bool, target: Any = None, typed: str = "", error: str = "") -> None:
184
+ """The step just done, and the next one of the workflow when it is known; then the screen after it."""
185
+ nxt: Dict[str, Any] = {}
186
+ if 0 <= index < len(self.steps) and isinstance(self.steps[index], Mapping):
187
+ s = self.steps[index]
188
+ nxt = {"index": index + 1, "op": _line(s.get("op", "")), "target": clean_target(s.get("target"))}
189
+ doc = {
190
+ "index": int(index),
191
+ "total": self.total,
192
+ "op": _line(op),
193
+ "ok": bool(ok),
194
+ "target": clean_target(target),
195
+ **({"typed": _line(typed)} if typed else {}),
196
+ **({"error": _line(error)} if error else {}),
197
+ **({"next": nxt} if nxt else {}),
198
+ }
199
+ _write(self.dir / "step.json", json.dumps(doc).encode())
200
+ self.capture()
201
+
202
+ def start(self) -> "LiveScreen":
203
+ def loop() -> None:
204
+ while not self.stopping.wait(self.every):
205
+ self.capture()
206
+
207
+ self.thread = threading.Thread(target=loop, name="forgeqe-live", daemon=True)
208
+ self.thread.start()
209
+ return self
210
+
211
+ def close(self) -> None:
212
+ """Stop reading and remove the live files: the run's report keeps its own pictures."""
213
+ self.stopping.set()
214
+ if self.thread is not None:
215
+ self.thread.join(timeout=5)
216
+ with self.lock:
217
+ for name in ("screen.png", "state.json", "step.json", ".grab.png"):
218
+ try:
219
+ (self.dir / name).unlink()
220
+ except OSError:
221
+ pass
222
+ try:
223
+ self.dir.rmdir()
224
+ except OSError:
225
+ pass