@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
@@ -66,6 +66,7 @@ environments:
66
66
  # hyperexecute: ./hyperexecute # TestMu's program, for Maestro on its devices
67
67
  # secrets: [COURIER_PASSWORD] # the only environment variables {{secret:…}} may read
68
68
  # heal: true
69
+ # accessibility: true # check each new screen of a replay or explore: names, fields, target size (Apple's audit on iOS 17+)
69
70
  # headless: false # true: Appium starts emulators (a device's avd) and iOS simulators without a window
70
71
 
71
72
  # Desktop apps: the apps themselves are in env.yaml (kind: desktop). See docs/DESKTOP.md.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capagents/forgeqe",
3
- "version": "3.2.0",
3
+ "version": "3.2.1",
4
4
  "description": "ForgeQE: a browser agent CLI that runs goals and test cases in local Chrome or Chromium, or BrowserStack and TestMu AI/LambdaTest when configured, and turns passing runs into tests in your repo",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -470,6 +470,80 @@ def outdated_error(message: str) -> "GatewayError":
470
470
  )
471
471
 
472
472
 
473
+ # A runtime version as Copilot's releases name them (1.0.105, 1.0.64-1).
474
+ _RUNTIME_VERSION = re.compile(r"^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}(?:-[0-9]{1,4})?$")
475
+
476
+
477
+ def _version_key(v: str) -> Tuple[int, ...]:
478
+ return tuple(int(p) for p in re.split(r"[.-]", v))
479
+
480
+
481
+ def cached_runtimes(root: Any, platform: str, wrapper: str) -> List[Tuple[str, str]]:
482
+ """
483
+ The Copilot runtimes the SDK already keeps on this computer (<root>/<version>/prebuilds/<platform>/), newest first,
484
+ as (version, wrapper path): a folder of a version's shape, no link on the way, the wrapper and runtime.node both
485
+ regular, non-empty files.
486
+ """
487
+ out: List[Tuple[str, str]] = []
488
+ try:
489
+ names = os.listdir(root)
490
+ except OSError:
491
+ return out
492
+ for name in names:
493
+ if not _RUNTIME_VERSION.match(name):
494
+ continue
495
+ pair = os.path.join(root, name, "prebuilds", platform)
496
+ try:
497
+ if any(os.path.islink(p) for p in (os.path.join(root, name), os.path.join(root, name, "prebuilds"), pair)):
498
+ continue
499
+ files = [os.path.join(pair, wrapper), os.path.join(pair, "runtime.node")]
500
+ if all(os.path.isfile(f) and not os.path.islink(f) and os.path.getsize(f) > 0 for f in files):
501
+ out.append((name, files[0]))
502
+ except OSError:
503
+ continue
504
+ out.sort(key=lambda vp: _version_key(vp[0]), reverse=True)
505
+ return out
506
+
507
+
508
+ def runtime_fallback(env: Optional[Dict[str, str]] = None) -> Optional[Dict[str, str]]:
509
+ """
510
+ Makes sure the SDK has a runtime before it starts. The pinned one is used when it is here or can be downloaded;
511
+ when it cannot be downloaded (a company network that blocks GitHub's downloads), the newest runtime the SDK already
512
+ keeps on this computer runs instead, through the SDK's own COPILOT_CLI_PATH. Returns {"pinned", "used", "reason"}
513
+ when it fell back, None otherwise; raises with a clear reason when there is nothing to fall back to. A
514
+ COPILOT_CLI_PATH the person set is left alone.
515
+ """
516
+ env = os.environ if env is None else env
517
+ if env.get("COPILOT_CLI_PATH"):
518
+ return None
519
+ try:
520
+ from copilot._cli_download import ensure_runtime_wrapper, get_cache_dir
521
+ from copilot._cli_version import CLI_VERSION, get_runtime_platform
522
+ except ImportError:
523
+ return None
524
+ try:
525
+ ensure_runtime_wrapper()
526
+ return None
527
+ except Exception as e: # The download failed: anything else here is no better reason to stop.
528
+ reason = " ".join(str(e).split())[:300]
529
+ try:
530
+ platform = get_runtime_platform()
531
+ root = str(get_cache_dir(None))
532
+ except Exception:
533
+ raise RuntimeError(f"Copilot's runtime {CLI_VERSION} could not be downloaded: {reason}") from e
534
+ wrapper = "copilot-runtime.exe" if sys.platform == "win32" else "copilot-runtime"
535
+ older = [(v, p) for v, p in cached_runtimes(root, platform, wrapper) if v != CLI_VERSION]
536
+ if not older:
537
+ raise RuntimeError(
538
+ f"Copilot's runtime {CLI_VERSION} could not be downloaded, and no earlier one is on this computer: {reason}. "
539
+ "A company network that blocks GitHub's downloads does this: ask IT to allow github.com and "
540
+ "release-assets.githubusercontent.com, or set FORGEQE_GITHUB_MIRROR to your company's GitHub mirror."
541
+ ) from e
542
+ version, path = older[0]
543
+ env["COPILOT_CLI_PATH"] = path
544
+ return {"pinned": str(CLI_VERSION), "used": version, "reason": reason}
545
+
546
+
473
547
  def client_options(token: Optional[str], home: str, workdir: str) -> Dict[str, Any]:
474
548
  """With a token, that token only; without one, the signed-in user, as the Copilot SDK recommends on a user's machine."""
475
549
  auth: Dict[str, Any] = {"github_token": token, "use_logged_in_user": False} if token else {"use_logged_in_user": True}
@@ -490,6 +564,10 @@ class Copilot:
490
564
  if not self.websockets:
491
565
  # The runtime the SDK starts reads this too, for every request it makes (the model list included).
492
566
  os.environ[SDK_NO_WEBSOCKETS_ENV] = "1"
567
+ # Before the client: it looks for (and downloads) its runtime as it is made.
568
+ self.runtime = runtime_fallback()
569
+ if self.runtime:
570
+ gateway_log("gateway", f"runtime {self.runtime['pinned']} could not be downloaded: running {self.runtime['used']} from this computer ({self.runtime['reason']})")
493
571
  self.client = CopilotClient(**client_options(token, home, self.workdir))
494
572
  self.health = ModelHealth()
495
573
  self._seat: List[Dict[str, Any]] = []
@@ -1212,7 +1290,8 @@ async def serve(out: TextIO, copilot: Any = None) -> int:
1212
1290
  server = await asyncio.start_server(lambda r, w: handle(r, w, copilot, key), host="127.0.0.1", port=0, limit=64 * 1024)
1213
1291
  port = server.sockets[0].getsockname()[1]
1214
1292
  gateway_log("gateway", f"listening on 127.0.0.1:{port}")
1215
- out.write(json.dumps({"port": port, "login": getattr(copilot, "login", "")}) + "\n")
1293
+ runtime = getattr(copilot, "runtime", None)
1294
+ out.write(json.dumps({"port": port, "login": getattr(copilot, "login", ""), **({"runtime": runtime} if runtime else {})}) + "\n")
1216
1295
  out.flush()
1217
1296
  loop = asyncio.get_running_loop()
1218
1297
  # Stop when ForgeQE closes stdin (or exits).
@@ -8,6 +8,10 @@ that changes the browser or the agent's actions comes from fixed lists, never fr
8
8
  page's markup (find_elements).
9
9
  - input "keyboard": the mouse actions (click, input, select_dropdown, upload, scripts) are taken away; the agent moves
10
10
  with press_key and types with type_text into the focused field.
11
+ - input "touch": a touchscreen, no keyboard (no press_key). With a screen reader (VoiceOver, TalkBack) the agent moves
12
+ a reading cursor with swipe_next and swipe_previous and activates what it is on with double_tap, never a tap by sight.
13
+ - device: a phone or tablet of ForgeQE's list (src/responsive/devices.ts): its size, pixel ratio, touch and user agent;
14
+ text_scale: the system's larger text, as the browser's default font size.
11
15
  - vision, zoom and media: Chrome's own emulation (a colour vision deficiency or blur, a zoomed page, reduced motion,
12
16
  forced colours), applied to each page before the agent's step.
13
17
 
@@ -15,6 +19,7 @@ This is not functional testing: whether the feature works is not judged, only wh
15
19
  operate and understand it. Each barrier is recorded with record_accessibility_issue into persona-findings.json.
16
20
  """
17
21
 
22
+ import asyncio
18
23
  import json
19
24
  import logging
20
25
  import re
@@ -28,7 +33,9 @@ from .prompts import text as prompt_text
28
33
  logger = logging.getLogger(__name__)
29
34
 
30
35
  PERCEPTIONS = ("sight", "screen_reader")
31
- INPUTS = ("any", "keyboard")
36
+ INPUTS = ("any", "keyboard", "touch")
37
+ # A device's user agent: ForgeQE's own fixed strings (src/responsive/devices.ts userAgentOf), checked to be plain text.
38
+ UA = re.compile(r"[A-Za-z0-9 ()/;:._,+-]{1,300}")
32
39
  # Chrome's Emulation.setEmulatedVisionDeficiency types, by the persona's name for them.
33
40
  VISION = {
34
41
  "none": "none",
@@ -106,6 +113,21 @@ You have no mouse. You MUST move with press_key (Tab, Shift+Tab, the arrow keys,
106
113
  """.strip()
107
114
 
108
115
 
116
+ TOUCH_READER_MESSAGE = """
117
+ ## You use a screen reader on a touchscreen
118
+ You use VoiceOver or TalkBack on a phone or tablet. You have no keyboard and you do not tap by sight.
119
+ - You MUST move with swipe_next and swipe_previous: each moves the screen reader's cursor to the next or previous item in reading order and says it, as a swipe right or left does.
120
+ - You MUST activate the item under the cursor with double_tap, and type into a field with type_text after double_tap has put focus in it.
121
+ - An item you cannot reach by swiping, an item announced with no name, a control that does nothing on double_tap, and a dialog or new content that the cursor does not move into are barriers.
122
+ """.strip()
123
+
124
+ TOUCH_MESSAGE = """
125
+ ## You use a touchscreen
126
+ You have no keyboard and no mouse: you tap, and you type on the on-screen keyboard.
127
+ - Targets that are small or close together, actions that need a precise gesture (drag, swipe, pinch) with no simple alternative, and content that appears only on hover are barriers.
128
+ """.strip()
129
+
130
+
109
131
  def parse_persona(raw: Any) -> Optional[Dict[str, Any]]:
110
132
  """The persona of the run request, with each setting from its fixed list; None for no persona."""
111
133
  if not isinstance(raw, dict):
@@ -127,11 +149,54 @@ def parse_persona(raw: Any) -> Optional[Dict[str, Any]]:
127
149
  "zoom": min(4.0, max(1.0, zoom)),
128
150
  "media": list(dict.fromkeys(media)),
129
151
  "watch_for": watch,
152
+ "text_scale": _number(raw.get("text_scale"), 1.0, 1.0, 3.0),
153
+ "device": parse_device(raw.get("device")),
154
+ }
155
+
156
+
157
+ def _number(v: Any, default: float, low: float, high: float) -> float:
158
+ try:
159
+ n = float(v if v not in (None, "") else default)
160
+ except (TypeError, ValueError):
161
+ return default
162
+ return min(high, max(low, n)) if n == n else default
163
+
164
+
165
+ def parse_device(raw: Any) -> Optional[Dict[str, Any]]:
166
+ """A phone or tablet to emulate, each value in range and the user agent plain text; None for the browser's own."""
167
+ if not isinstance(raw, dict):
168
+ return None
169
+ try:
170
+ width, height = int(raw.get("width")), int(raw.get("height"))
171
+ except (TypeError, ValueError):
172
+ return None
173
+ if not (240 <= width <= 3000 and 240 <= height <= 3000):
174
+ return None
175
+ ua = str(raw.get("ua") or "")
176
+ return {
177
+ "id": re.sub(r"[^a-z0-9-]", "", str(raw.get("id") or "").lower())[:40],
178
+ "label": " ".join(str(raw.get("label") or "").split())[:60],
179
+ "width": width,
180
+ "height": height,
181
+ "scale": _number(raw.get("scale"), 1.0, 1.0, 4.0),
182
+ "mobile": raw.get("mobile") is True,
183
+ "ua": ua if UA.fullmatch(ua) else "",
130
184
  }
131
185
 
132
186
 
133
187
  def keyboard_only(persona: Dict[str, Any]) -> bool:
134
- return persona["input"] == "keyboard" or persona["perception"] == "screen_reader"
188
+ """Moves with keys: a keyboard user, and a screen reader user who is not on a touchscreen."""
189
+ return persona["input"] == "keyboard" or (persona["perception"] == "screen_reader" and persona["input"] != "touch")
190
+
191
+
192
+ def touch_reader(persona: Dict[str, Any]) -> bool:
193
+ """A screen reader on a touchscreen (VoiceOver, TalkBack): swipes and double taps, never a tap by sight."""
194
+ return persona["perception"] == "screen_reader" and persona["input"] == "touch"
195
+
196
+
197
+ def no_pointer(persona: Dict[str, Any]) -> bool:
198
+ """Has no mouse or tap by sight: the pointer actions are taken away."""
199
+ return keyboard_only(persona) or touch_reader(persona)
135
200
 
136
201
 
137
202
  def uses_vision(persona: Dict[str, Any]) -> bool:
@@ -146,6 +211,11 @@ def system_message(persona: Dict[str, Any]) -> str:
146
211
  setting = []
147
212
  if persona["zoom"] > 1:
148
213
  setting.append(f"The page is zoomed to {round(persona['zoom'] * 100)}%, as this person zooms it. Text that is cut off or overlaps, and content that needs scrolling sideways, are barriers.")
214
+ if persona.get("device"):
215
+ d = persona["device"]
216
+ setting.append(f"You use {d['label'] or 'a handheld device'}: the page is shown at its size ({d['width']}×{d['height']} CSS pixels){', with touch' if d['mobile'] else ''}. Content that does not fit, needs scrolling sideways, or is hidden behind fixed bars is a barrier.")
217
+ if persona.get("text_scale", 1) > 1:
218
+ setting.append(f"Your system's text size is {round(persona['text_scale'] * 100)}%. Text that does not grow, is cut off, or overlaps is a barrier.")
149
219
  if persona["vision"] != "none":
150
220
  setting.append(f"The screenshots show the page as this person sees it ({persona['vision'].replace('_', ' ')}). Information that you can tell only by colour, and text that you cannot read, are barriers.")
151
221
  for m in persona["media"]:
@@ -163,9 +233,13 @@ def system_message(persona: Dict[str, Any]) -> str:
163
233
  who += ["", "Barriers that this person meets often (look for them, but record only what you meet):", *[f"- {w}" for w in persona["watch_for"]]]
164
234
  parts = [prompt_text("browser-persona", PERSONA_SYSTEM_MESSAGE)]
165
235
  if persona["perception"] == "screen_reader":
166
- parts.append(SCREEN_READER_MESSAGE)
167
- if keyboard_only(persona):
236
+ parts.append(SCREEN_READER_MESSAGE.replace("what press_key announces", "what swipe_next and double_tap announce") if touch_reader(persona) else SCREEN_READER_MESSAGE)
237
+ if touch_reader(persona):
238
+ parts.append(TOUCH_READER_MESSAGE)
239
+ elif keyboard_only(persona):
168
240
  parts.append(KEYBOARD_MESSAGE)
241
+ elif persona["input"] == "touch":
242
+ parts.append(TOUCH_MESSAGE)
169
243
  parts.append("\n".join(who))
170
244
  return "\n\n".join(parts)
171
245
 
@@ -186,7 +260,9 @@ async def _cdp(browser_session: BrowserSession):
186
260
 
187
261
  async def apply_emulation(browser_session: BrowserSession, persona: Dict[str, Any], viewport: Optional[List[int]], applied: Dict[str, Any]) -> None:
188
262
  """Vision, zoom and media of the persona on the page in focus: vision and media once per tab, zoom whenever it is gone."""
189
- if persona["vision"] == "none" and persona["zoom"] <= 1 and not persona["media"]:
263
+ device = persona.get("device")
264
+ scale = persona.get("text_scale", 1)
265
+ if persona["vision"] == "none" and persona["zoom"] <= 1 and not persona["media"] and not device and scale <= 1:
190
266
  return
191
267
  try:
192
268
  cdp = await _cdp(browser_session)
@@ -201,8 +277,26 @@ async def apply_emulation(browser_session: BrowserSession, persona: Dict[str, An
201
277
  await send.Emulation.setEmulatedVisionDeficiency(params={"type": VISION[persona["vision"]]}, session_id=sid)
202
278
  if persona["media"]:
203
279
  await send.Emulation.setEmulatedMedia(params={"features": [{"name": MEDIA[m][0], "value": MEDIA[m][1]} for m in persona["media"]]}, session_id=sid)
280
+ if device and device["mobile"]:
281
+ await send.Emulation.setTouchEmulationEnabled(params={"enabled": True, "maxTouchPoints": 5}, session_id=sid)
282
+ if device and device["ua"]:
283
+ await send.Emulation.setUserAgentOverride(params={"userAgent": device["ua"]}, session_id=sid)
284
+ if scale > 1:
285
+ # The system's larger text, as the browser's default font size: text sized in rem or em grows, px does not.
286
+ await send.Page.setFontSizes(params={"fontSizes": {"standard": round(16 * scale), "fixed": round(13 * scale)}}, session_id=sid)
204
287
  applied[sid] = True
205
- if persona["zoom"] > 1:
288
+ if device:
289
+ # The device's size, at the persona's zoom; the browser library resets the viewport when a tab gains focus, so it is
290
+ # checked before every step and applied again once it is gone.
291
+ z = persona["zoom"]
292
+ width = max(240, round(device["width"] / z))
293
+ # screen.width, not innerWidth: a page with no viewport meta lays out wider (980px) on a phone, as it should.
294
+ now = ((await send.Runtime.evaluate(params={"expression": "screen.width", "returnByValue": True}, session_id=sid)).get("result") or {}).get("value")
295
+ if now != width:
296
+ await send.Emulation.setDeviceMetricsOverride(
297
+ params={"screenWidth": width, "screenHeight": max(240, round(device["height"] / z)), "width": width, "height": max(240, round(device["height"] / z)), "deviceScaleFactor": device["scale"] * z, "mobile": device["mobile"]}, session_id=sid
298
+ )
299
+ elif persona["zoom"] > 1:
206
300
  # Zooming a page is a smaller viewport in CSS pixels at a larger scale: the page reflows as it does at that zoom.
207
301
  w, h = (viewport or [1280, 800])[:2]
208
302
  z = persona["zoom"]
@@ -263,7 +357,14 @@ def announce(node: Dict[str, Any]) -> str:
263
357
  return " ".join(b for b in bits if b)
264
358
 
265
359
 
266
- def render_tree(nodes: List[Dict[str, Any]], view: str) -> str:
360
+ def reading_items(nodes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
361
+ """What a touch screen reader's swipes move through, in reading order: each item as it is said, and its DOM node."""
362
+ items: List[Dict[str, Any]] = []
363
+ render_tree(nodes, "page", items)
364
+ return items
365
+
366
+
367
+ def render_tree(nodes: List[Dict[str, Any]], view: str, items: Optional[List[Dict[str, Any]]] = None) -> str:
267
368
  """The accessibility tree as a screen reader user hears it: the whole page, or one of its rotor lists."""
268
369
  by_id = {str(n.get("nodeId")): n for n in nodes if isinstance(n, dict)}
269
370
  lines: List[str] = []
@@ -285,7 +386,9 @@ def render_tree(nodes: List[Dict[str, Any]], view: str) -> str:
285
386
  if role in ("generic", "none", "presentation", "RootWebArea", "group", "LabelText", "paragraph", "Section") and not _ax_value(n.get("name")):
286
387
  return False
287
388
  if role == "StaticText":
288
- # Text inside a named element is already in that element's name.
389
+ # Empty or blank text is not said; text inside a named element is already in that element's name.
390
+ if not _ax_value(n.get("name")).strip():
391
+ return False
289
392
  parent = by_id.get(str(n.get("parentId")))
290
393
  return not (parent and _ax_value(parent.get("name")) and _ax_value(parent.get("role")) in INTERACTIVE | {"heading", "image", "img"})
291
394
  return True
@@ -299,6 +402,10 @@ def render_tree(nodes: List[Dict[str, Any]], view: str) -> str:
299
402
  role = _ax_value(n.get("role"))
300
403
  line = f"text {' '.join(_ax_value(n.get('name')).split())[:200]!r}" if role == "StaticText" else announce(n)
301
404
  lines.append((" " * min(depth, 8) if view == "page" else "") + line)
405
+ # A swipe stops on what VoiceOver and TalkBack stop on: not the page itself, a landmark, or an unnamed legend.
406
+ if items is not None and role not in LANDMARKS and role not in ("RootWebArea", "Legend"):
407
+ backend = n.get("backendDOMNodeId")
408
+ items.append({"line": line, "backend": backend if isinstance(backend, int) else None})
302
409
  for c in n.get("childIds") or []:
303
410
  walk(str(c), depth + (1 if shown else 0))
304
411
 
@@ -412,12 +519,92 @@ def register_persona_tools(tools: Any, persona: Dict[str, Any], findings: List[D
412
519
  said = f"Pressed {'Shift+' if shift else ''}{name}. {focus_line(f, sighted)}"
413
520
  return ActionResult(extracted_content=said, long_term_memory=said)
414
521
 
415
- @tools.action("Type text into the field that has focus, as a keyboard user does. Move focus to the field with press_key first.")
522
+ if touch_reader(persona):
523
+ cursor: Dict[str, Any] = {"url": "", "at": -1, "line": "", "backend": None}
524
+
525
+ async def _items(browser_session: BrowserSession) -> List[Dict[str, Any]]:
526
+ cdp = await _cdp(browser_session)
527
+ try:
528
+ await cdp.cdp_client.send.Accessibility.enable(session_id=cdp.session_id)
529
+ except Exception:
530
+ pass
531
+ tree = await cdp.cdp_client.send.Accessibility.getFullAXTree(params={}, session_id=cdp.session_id)
532
+ return reading_items(tree.get("nodes") or [])
533
+
534
+ async def _place(browser_session: BrowserSession, items: List[Dict[str, Any]]) -> int:
535
+ """Where the cursor is now: on its item again after the page changed, at the start of a new page."""
536
+ url = ""
537
+ try:
538
+ url = str(await browser_session.get_current_page_url() or "")
539
+ except Exception:
540
+ pass
541
+ if url != cursor["url"]:
542
+ cursor.update({"url": url, "at": -1, "line": "", "backend": None})
543
+ return -1
544
+ for i, it in enumerate(items):
545
+ if cursor["backend"] is not None and it["backend"] == cursor["backend"] and it["line"] == cursor["line"]:
546
+ return i
547
+ return min(cursor["at"], len(items) - 1)
548
+
549
+ async def _swipe(step: int, browser_session: BrowserSession) -> ActionResult:
550
+ try:
551
+ items = await _items(browser_session)
552
+ at = await _place(browser_session, items) + step
553
+ except Exception as ex:
554
+ return ActionResult(error=f"The screen reader could not read the page: {ex}")
555
+ if not items:
556
+ return ActionResult(extracted_content="The screen reader announces nothing on this page.")
557
+ if at < 0 or at >= len(items):
558
+ return ActionResult(extracted_content="Start of the page: nothing before this." if at < 0 else "End of the page: nothing after this.")
559
+ cursor.update({"at": at, "line": items[at]["line"], "backend": items[at]["backend"]})
560
+ said = f"{'Swiped right' if step > 0 else 'Swiped left'}. {items[at]['line']}"
561
+ return ActionResult(extracted_content=said, long_term_memory=said)
562
+
563
+ @tools.action("Swipe right with the screen reader: move to the next item in reading order and hear it.")
564
+ async def swipe_next(browser_session: BrowserSession) -> ActionResult:
565
+ return await _swipe(1, browser_session)
566
+
567
+ @tools.action("Swipe left with the screen reader: move to the previous item in reading order and hear it.")
568
+ async def swipe_previous(browser_session: BrowserSession) -> ActionResult:
569
+ return await _swipe(-1, browser_session)
570
+
571
+ @tools.action("Double tap with the screen reader: activate the item the cursor is on (follow a link, press a button, put focus in a field).")
572
+ async def double_tap(browser_session: BrowserSession) -> ActionResult:
573
+ if cursor["backend"] is None:
574
+ return ActionResult(error="The cursor is on nothing that can be activated: move to an item with swipe_next first.")
575
+ try:
576
+ cdp = await _cdp(browser_session)
577
+ send, sid = cdp.cdp_client.send, cdp.session_id
578
+ await send.DOM.getDocument(params={"depth": 0}, session_id=sid)
579
+ await send.DOM.scrollIntoViewIfNeeded(params={"backendNodeId": cursor["backend"]}, session_id=sid)
580
+ box = ((await send.DOM.getBoxModel(params={"backendNodeId": cursor["backend"]}, session_id=sid)) or {}).get("model") or {}
581
+ quad = box.get("content") or box.get("border") or []
582
+ if len(quad) < 8:
583
+ return ActionResult(error=f"{cursor['line']} has no place on the screen: double tap does nothing on it.")
584
+ x, y = sum(quad[0::2]) / 4, sum(quad[1::2]) / 4
585
+ # A screen reader's double tap activates the item where it is, as a finger's tap there does: a touch, in the
586
+ # page's layout pixels (the input layer maps them onto a page a phone shows scaled). Without touch, a click.
587
+ try:
588
+ await send.Input.dispatchTouchEvent(params={"type": "touchStart", "touchPoints": [{"x": x, "y": y}]}, session_id=sid)
589
+ await send.Input.dispatchTouchEvent(params={"type": "touchEnd", "touchPoints": []}, session_id=sid)
590
+ except Exception:
591
+ for kind in ("mousePressed", "mouseReleased"):
592
+ await send.Input.dispatchMouseEvent(params={"type": kind, "x": x, "y": y, "button": "left", "clickCount": 1}, session_id=sid)
593
+ await asyncio.sleep(0.3)
594
+ f = await focused(browser_session)
595
+ except Exception as ex:
596
+ return ActionResult(error=f"Double tap did not reach {cursor['line']}: {ex}")
597
+ said = f"Double tapped {cursor['line']}. {focus_line(f, False)}"
598
+ return ActionResult(extracted_content=said, long_term_memory=said)
599
+
600
+ if touch_reader(persona) or keyboard_only(persona):
601
+
602
+ @tools.action("Type text into the field that has focus, as on the on-screen or a real keyboard. Put focus in the field first (press_key, or double_tap on a touchscreen).")
416
603
  async def type_text(text: str, browser_session: BrowserSession) -> ActionResult:
417
604
  try:
418
605
  f = await focused(browser_session)
419
606
  if f.get("none"):
420
- return ActionResult(error="Nothing has focus: move to the field with press_key first.")
607
+ return ActionResult(error="Nothing has focus: put focus in the field first.")
421
608
  cdp = await _cdp(browser_session)
422
609
  await cdp.cdp_client.send.Input.insertText(params={"text": str(text or "")}, session_id=cdp.session_id)
423
610
  f = await focused(browser_session)
@@ -1486,13 +1486,13 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
1486
1486
  if persona:
1487
1487
  personas.register_persona_tools(agent_tools, persona, persona_findings, req.out_dir)
1488
1488
  personas.save_findings(req.out_dir, persona, persona_findings)
1489
- if personas.keyboard_only(persona):
1489
+ if personas.no_pointer(persona):
1490
1490
  personas.exclude_mouse(agent_tools)
1491
1491
  if not personas.uses_vision(persona):
1492
1492
  personas.exclude_markup(agent_tools)
1493
1493
  # A screen reader user does not see the page: the agent gets no screenshots.
1494
1494
  agent_kw["use_vision"] = personas.uses_vision(persona)
1495
- emit({"type": "log", "level": "info", "text": f"Accessibility persona: {persona['name']} ({'screen reader' if persona['perception'] == 'screen_reader' else 'sight'}, {'keyboard only' if personas.keyboard_only(persona) else 'mouse and keyboard'})"})
1495
+ emit({"type": "log", "level": "info", "text": f"Accessibility persona: {persona['name']} ({'screen reader' if persona['perception'] == 'screen_reader' else 'sight'}, {'screen reader gestures' if personas.touch_reader(persona) else 'keyboard only' if personas.keyboard_only(persona) else 'touch' if persona['input'] == 'touch' else 'mouse and keyboard'}{', ' + persona['device']['label'] if persona.get('device') and persona['device'].get('label') else ''})"})
1496
1496
  else:
1497
1497
  register_checks(agent_tools, recorded_checks)
1498
1498
  register_click_selector(agent_tools, captured)