@capagents/forgeqe 2.6.2 → 2.6.3
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.
- package/HOW_TO_USE.md +201 -13
- package/README.md +4 -2
- package/THIRD_PARTY_NOTICES.md +9 -0
- package/dist/docs-site/docs/architecture/index.html +2 -1
- package/dist/docs-site/docs/index.html +188 -10
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/docs-site/docs/web-app/index.html +35 -6
- package/dist/forgeqe.js +1316 -1145
- package/dist/template.html +64 -64
- package/dist/web/assets/Agent-yd1DyMzR.js +4 -0
- package/dist/web/assets/ApiTests-BwOGta9J.js +10 -0
- package/dist/web/assets/Chat-P8GH_6gl.js +3 -0
- package/dist/web/assets/Data-D2iCqk3t.js +3 -0
- package/dist/web/assets/Features-Bu38clxs.js +1 -0
- package/dist/web/assets/Jobs-DymuaGeN.js +5 -0
- package/dist/web/assets/KindPage-zl6TBkEl.js +6 -0
- package/dist/web/assets/Migration-Cg_FUqS_.js +2 -0
- package/dist/web/assets/Quality-D3bSHP_B.js +1 -0
- package/dist/web/assets/Record-DkCLJos6.js +2 -0
- package/dist/web/assets/Regression-B2qMKjAE.js +5 -0
- package/dist/web/assets/Reports-D_G9yfDa.js +2 -0
- package/dist/web/assets/Response-BnPAefP-.js +4 -0
- package/dist/web/assets/Runs-DsDj9-LT.js +2 -0
- package/dist/web/assets/Shell-DlZHZN0d.js +3 -0
- package/dist/web/assets/TestData-qI1R5Q9v.js +2 -0
- package/dist/web/assets/WhatsNew-CoCHqSDm.js +1 -0
- package/dist/web/assets/accessibility-CH8EpEAV.svg +1 -0
- package/dist/web/assets/{arrow-down-BX18RHKM.js → arrow-down-BWCXlJU0.js} +1 -1
- package/dist/web/assets/arrow-right-CdxkQBV7.js +1 -0
- package/dist/web/assets/{bot-CLgiKzu9.js → bot-D8486kSA.js} +1 -1
- package/dist/web/assets/capgemini-mark-D6aZFnD3.png +0 -0
- package/dist/web/assets/chevron-up-CQz_ZmIK.js +1 -0
- package/dist/web/assets/circle-BqXBUsQS.js +1 -0
- package/dist/web/assets/{circle-dashed-CtRp9sew.js → circle-dashed-DlOiCbWD.js} +1 -1
- package/dist/web/assets/dataParts-bwNleJYd.js +3 -0
- package/dist/web/assets/forgeqe-logo-D3CwM2Jl.png +0 -0
- package/dist/web/assets/forgeqe-logo-white-CoE-hF2l.png +0 -0
- package/dist/web/assets/forgeqe-mark-ZLd4S3hw.png +0 -0
- package/dist/web/assets/index-Bh4NBbEU.js +37 -0
- package/dist/web/assets/index-DkgUrjyL.css +2 -0
- package/dist/web/assets/keyboard-wpCM6HMa.js +1 -0
- package/dist/web/assets/qualityParts-iy-mouSI.js +1 -0
- package/dist/web/assets/{thread-Y9TDe1cr.js → thread-BfW2V-2U.js} +1 -1
- package/dist/web/assets/upload-CwExsxOd.js +1 -0
- package/dist/web/assets/usePageChat-CzWbP_sa.js +1 -0
- package/dist/web/index.html +3 -3
- package/docs/ARCHITECTURE.md +2 -1
- package/docs/WEB_APP.md +36 -6
- package/docs/security-data-flow.html +3 -3
- package/docs/user-guide.html +188 -10
- package/forgeqe.example.yaml +8 -2
- package/package.json +5 -3
- package/prompts/api-tests.md +1 -1
- package/prompts/brain.md +8 -0
- package/prompts/browser-persona.md +14 -0
- package/prompts/db-agent.md +73 -0
- package/prompts/heal.md +1 -1
- package/prompts/migrate.md +54 -0
- package/prompts/test-agent.md +1 -0
- package/py/forgeqe_engine/cli.py +9 -1
- package/py/forgeqe_engine/copilot_gateway.py +162 -9
- package/py/forgeqe_engine/persona.py +435 -0
- package/py/forgeqe_engine/proceed.py +67 -0
- package/py/forgeqe_engine/service.py +93 -11
- package/skills/test-data/SKILL.md +4 -0
- package/dist/web/assets/Agent-CTDTMH3D.js +0 -3
- package/dist/web/assets/ApiTests-l1gZ56fZ.js +0 -10
- package/dist/web/assets/Chat-Dikg6l8H.js +0 -3
- package/dist/web/assets/Data-BwECmGVi.js +0 -4
- package/dist/web/assets/Features-B79B8aw4.js +0 -1
- package/dist/web/assets/Jobs-B0viFhNH.js +0 -5
- package/dist/web/assets/Quality-CjFsnbA2.js +0 -1
- package/dist/web/assets/Record-B-Eh1bgA.js +0 -2
- package/dist/web/assets/Regression-B7l83v3z.js +0 -5
- package/dist/web/assets/Reports-BuUlCohG.js +0 -2
- package/dist/web/assets/Response-BS_RT6Qd.js +0 -4
- package/dist/web/assets/Runs-C7TPphyI.js +0 -2
- package/dist/web/assets/Shell-Vg5t8ZK3.js +0 -3
- package/dist/web/assets/accessibility-BSaq_4Me.svg +0 -1
- package/dist/web/assets/capgemini-BO8ajcbd.svg +0 -21
- package/dist/web/assets/capgemini-white-ByjwPW8N.svg +0 -21
- package/dist/web/assets/circle-BF-xM9LZ.js +0 -1
- package/dist/web/assets/index-CDCzsK2N.css +0 -2
- package/dist/web/assets/index-DR8clS1u.js +0 -26
- package/dist/web/assets/markdown-CBbHCXbg.js +0 -10
- package/dist/web/assets/trending-up-DMQnalkJ.js +0 -1
- package/dist/web/assets/usePageChat-CSLmKGMO.js +0 -1
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Accessibility testing as a persona: the browser agent does a goal the way one person with a disability would, and records
|
|
3
|
+
each barrier it meets. ForgeQE sends the persona with the run request (src/a11y/personas.ts makes it); everything here
|
|
4
|
+
that changes the browser or the agent's actions comes from fixed lists, never from the persona's text.
|
|
5
|
+
|
|
6
|
+
- perception "screen_reader": no screenshots; the agent reads the page through the accessibility tree
|
|
7
|
+
(screen_reader_view) and what each key press puts in focus, as a screen reader announces it.
|
|
8
|
+
- input "keyboard": the mouse actions (click, input, select_dropdown, upload, scripts) are taken away; the agent moves
|
|
9
|
+
with press_key and types with type_text into the focused field.
|
|
10
|
+
- vision, zoom and media: Chrome's own emulation (a colour vision deficiency or blur, a zoomed page, reduced motion,
|
|
11
|
+
forced colours), applied to each page before the agent's step.
|
|
12
|
+
|
|
13
|
+
This is not functional testing: whether the feature works is not judged, only whether this person can perceive,
|
|
14
|
+
operate and understand it. Each barrier is recorded with record_accessibility_issue into persona-findings.json.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Dict, List, Optional
|
|
21
|
+
|
|
22
|
+
from browser_use import ActionResult, BrowserSession
|
|
23
|
+
|
|
24
|
+
from .prompts import text as prompt_text
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
PERCEPTIONS = ("sight", "screen_reader")
|
|
29
|
+
INPUTS = ("any", "keyboard")
|
|
30
|
+
# Chrome's Emulation.setEmulatedVisionDeficiency types, by the persona's name for them.
|
|
31
|
+
VISION = {
|
|
32
|
+
"none": "none",
|
|
33
|
+
"blurred": "blurredVision",
|
|
34
|
+
"reduced_contrast": "reducedContrast",
|
|
35
|
+
"achromatopsia": "achromatopsia",
|
|
36
|
+
"deuteranopia": "deuteranopia",
|
|
37
|
+
"protanopia": "protanopia",
|
|
38
|
+
"tritanopia": "tritanopia",
|
|
39
|
+
}
|
|
40
|
+
# Media features the persona's browser reports.
|
|
41
|
+
MEDIA = {
|
|
42
|
+
"reduced_motion": ("prefers-reduced-motion", "reduce"),
|
|
43
|
+
"forced_colors": ("forced-colors", "active"),
|
|
44
|
+
"more_contrast": ("prefers-contrast", "more"),
|
|
45
|
+
"dark": ("prefers-color-scheme", "dark"),
|
|
46
|
+
}
|
|
47
|
+
SEVERITIES = ("critical", "serious", "moderate", "minor")
|
|
48
|
+
FINDINGS_FILE = "persona-findings.json"
|
|
49
|
+
|
|
50
|
+
# Actions a person using only the keyboard does not have: each points at an element or runs script, as a mouse would.
|
|
51
|
+
MOUSE_ACTIONS = ("click", "input", "select_dropdown", "dropdown_options", "upload_file", "click_selector", "evaluate")
|
|
52
|
+
|
|
53
|
+
# Keys press_key sends: (key, code, windowsVirtualKeyCode, text).
|
|
54
|
+
KEYS: Dict[str, tuple] = {
|
|
55
|
+
"Tab": ("Tab", "Tab", 9, ""),
|
|
56
|
+
"Enter": ("Enter", "Enter", 13, "\r"),
|
|
57
|
+
"Space": (" ", "Space", 32, " "),
|
|
58
|
+
"Escape": ("Escape", "Escape", 27, ""),
|
|
59
|
+
"ArrowUp": ("ArrowUp", "ArrowUp", 38, ""),
|
|
60
|
+
"ArrowDown": ("ArrowDown", "ArrowDown", 40, ""),
|
|
61
|
+
"ArrowLeft": ("ArrowLeft", "ArrowLeft", 37, ""),
|
|
62
|
+
"ArrowRight": ("ArrowRight", "ArrowRight", 39, ""),
|
|
63
|
+
"Home": ("Home", "Home", 36, ""),
|
|
64
|
+
"End": ("End", "End", 35, ""),
|
|
65
|
+
"PageUp": ("PageUp", "PageUp", 33, ""),
|
|
66
|
+
"PageDown": ("PageDown", "PageDown", 34, ""),
|
|
67
|
+
"Backspace": ("Backspace", "Backspace", 8, ""),
|
|
68
|
+
}
|
|
69
|
+
SHIFT = 8
|
|
70
|
+
|
|
71
|
+
INTERACTIVE = {"button", "link", "textbox", "searchbox", "checkbox", "radio", "combobox", "listbox", "menuitem", "menuitemcheckbox", "menuitemradio", "tab", "switch", "slider", "spinbutton", "option", "treeitem"}
|
|
72
|
+
LANDMARKS = {"banner", "navigation", "main", "contentinfo", "complementary", "search", "form", "region"}
|
|
73
|
+
FORM_ROLES = {"textbox", "searchbox", "checkbox", "radio", "combobox", "listbox", "switch", "slider", "spinbutton", "button"}
|
|
74
|
+
VIEWS = ("page", "headings", "landmarks", "links", "form_controls")
|
|
75
|
+
MAX_VIEW_CHARS = 6000
|
|
76
|
+
|
|
77
|
+
PERSONA_SYSTEM_MESSAGE = """
|
|
78
|
+
## Accessibility testing as a persona (necessary)
|
|
79
|
+
This run is accessibility testing, not functional testing. You act as the person described below and try to reach the goal the way they would. You judge only whether this person can perceive, operate, and understand the page.
|
|
80
|
+
- You MUST NOT judge whether the feature works as specified, such as prices, totals, search results, or business rules. A defect of that kind is out of scope: do not record it.
|
|
81
|
+
- You MUST call record_accessibility_issue one time for each barrier, as soon as you meet it. A barrier is something that stops this person, slows them, or confuses them, and that a page made for them would not do.
|
|
82
|
+
- You MUST set `wcag` to the WCAG success criterion the barrier fails, such as 1.1.1 or 2.4.7, when one applies.
|
|
83
|
+
- You MUST set `severity`: critical when it stops the person from reaching the goal, serious when they get past it only with a lot of effort or help, moderate when it slows or confuses them, minor for an annoyance.
|
|
84
|
+
- When a barrier stops you, you MUST NOT go around it in a way this person could not, such as a mouse click for a keyboard user. Record it, then try another way this person has, such as another link or the browser's back.
|
|
85
|
+
- You MUST finish with done. Start the text with "Goal reached: yes", "Goal reached: partly", or "Goal reached: no", then say in a few sentences how it went for this person. Use success=true when you reached the goal and success=false when a barrier stopped you.
|
|
86
|
+
""".strip()
|
|
87
|
+
|
|
88
|
+
SCREEN_READER_MESSAGE = """
|
|
89
|
+
## You use a screen reader
|
|
90
|
+
You cannot see the page. You MUST perceive it only through screen_reader_view and what press_key announces. The element list and page text that you also get are not what this person perceives: you MUST NOT use a text, an icon, a colour, or a position that the screen reader does not announce.
|
|
91
|
+
- At each new page, you SHOULD first read the headings and the landmarks with screen_reader_view, as a screen reader user does.
|
|
92
|
+
- An image, a button, a link, or a field that is announced with no name is a barrier.
|
|
93
|
+
""".strip()
|
|
94
|
+
|
|
95
|
+
KEYBOARD_MESSAGE = """
|
|
96
|
+
## You use only the keyboard
|
|
97
|
+
You have no mouse. You MUST move with press_key (Tab, Shift+Tab, the arrow keys, Enter, Space, Escape) and type with type_text into the field that has focus.
|
|
98
|
+
- After each press_key, read what it says has focus. Focus that you cannot see, focus that goes to an unexpected place, and a control that you cannot reach or operate with keys are barriers.
|
|
99
|
+
- Focus that you cannot move away from with Tab, Shift+Tab, or Escape is a keyboard trap.
|
|
100
|
+
""".strip()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def parse_persona(raw: Any) -> Optional[Dict[str, Any]]:
|
|
104
|
+
"""The persona of the run request, with each setting from its fixed list; None for no persona."""
|
|
105
|
+
if not isinstance(raw, dict):
|
|
106
|
+
return None
|
|
107
|
+
clip = lambda v, n: " ".join(str(v or "").split())[:n] # noqa: E731
|
|
108
|
+
try:
|
|
109
|
+
zoom = float(raw.get("zoom") or 1)
|
|
110
|
+
except (TypeError, ValueError):
|
|
111
|
+
zoom = 1.0
|
|
112
|
+
media = [m for m in (raw.get("media") or []) if isinstance(m, str) and m in MEDIA] if isinstance(raw.get("media"), list) else []
|
|
113
|
+
watch = [clip(w, 200) for w in (raw.get("watch_for") or []) if isinstance(w, str) and w.strip()][:15] if isinstance(raw.get("watch_for"), list) else []
|
|
114
|
+
return {
|
|
115
|
+
"id": clip(raw.get("id"), 40) or "persona",
|
|
116
|
+
"name": clip(raw.get("name"), 80) or "Persona",
|
|
117
|
+
"description": clip(raw.get("description"), 1200),
|
|
118
|
+
"perception": raw.get("perception") if raw.get("perception") in PERCEPTIONS else "sight",
|
|
119
|
+
"input": raw.get("input") if raw.get("input") in INPUTS else "any",
|
|
120
|
+
"vision": raw.get("vision") if raw.get("vision") in VISION else "none",
|
|
121
|
+
"zoom": min(4.0, max(1.0, zoom)),
|
|
122
|
+
"media": list(dict.fromkeys(media)),
|
|
123
|
+
"watch_for": watch,
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def keyboard_only(persona: Dict[str, Any]) -> bool:
|
|
128
|
+
return persona["input"] == "keyboard" or persona["perception"] == "screen_reader"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def uses_vision(persona: Dict[str, Any]) -> bool:
|
|
132
|
+
return persona["perception"] != "screen_reader"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def system_message(persona: Dict[str, Any]) -> str:
|
|
136
|
+
"""The persona's instructions for the browser agent."""
|
|
137
|
+
who = [f"## The person: {persona['name']}"]
|
|
138
|
+
if persona["description"]:
|
|
139
|
+
who.append(persona["description"])
|
|
140
|
+
setting = []
|
|
141
|
+
if persona["zoom"] > 1:
|
|
142
|
+
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.")
|
|
143
|
+
if persona["vision"] != "none":
|
|
144
|
+
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.")
|
|
145
|
+
for m in persona["media"]:
|
|
146
|
+
setting.append(
|
|
147
|
+
{
|
|
148
|
+
"reduced_motion": "The browser asks for reduced motion. Animation, auto-playing movement, or parallax that still runs is a barrier.",
|
|
149
|
+
"forced_colors": "The browser uses forced colours (a high contrast theme). An icon, a border, a focus indicator, or a state that disappears is a barrier.",
|
|
150
|
+
"more_contrast": "The browser asks for more contrast.",
|
|
151
|
+
"dark": "The browser asks for a dark colour scheme.",
|
|
152
|
+
}[m]
|
|
153
|
+
)
|
|
154
|
+
if setting:
|
|
155
|
+
who += ["", *[f"- {s}" for s in setting]]
|
|
156
|
+
if persona["watch_for"]:
|
|
157
|
+
who += ["", "Barriers that this person meets often (look for them, but record only what you meet):", *[f"- {w}" for w in persona["watch_for"]]]
|
|
158
|
+
parts = [prompt_text("browser-persona", PERSONA_SYSTEM_MESSAGE)]
|
|
159
|
+
if persona["perception"] == "screen_reader":
|
|
160
|
+
parts.append(SCREEN_READER_MESSAGE)
|
|
161
|
+
if keyboard_only(persona):
|
|
162
|
+
parts.append(KEYBOARD_MESSAGE)
|
|
163
|
+
parts.append("\n".join(who))
|
|
164
|
+
return "\n\n".join(parts)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def exclude_mouse(tools: Any) -> None:
|
|
168
|
+
for name in MOUSE_ACTIONS:
|
|
169
|
+
tools.registry.exclude_action(name)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
async def _cdp(browser_session: BrowserSession):
|
|
173
|
+
return await browser_session.get_or_create_cdp_session()
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
async def apply_emulation(browser_session: BrowserSession, persona: Dict[str, Any], viewport: Optional[List[int]], applied: Dict[str, Any]) -> None:
|
|
177
|
+
"""Vision, zoom and media of the persona on the page in focus; each tab once."""
|
|
178
|
+
if persona["vision"] == "none" and persona["zoom"] <= 1 and not persona["media"]:
|
|
179
|
+
return
|
|
180
|
+
try:
|
|
181
|
+
cdp = await _cdp(browser_session)
|
|
182
|
+
except Exception as ex:
|
|
183
|
+
logger.debug("persona emulation: no page: %s", ex)
|
|
184
|
+
return
|
|
185
|
+
sid = cdp.session_id
|
|
186
|
+
if applied.get(sid):
|
|
187
|
+
return
|
|
188
|
+
send = cdp.cdp_client.send
|
|
189
|
+
try:
|
|
190
|
+
if persona["vision"] != "none":
|
|
191
|
+
await send.Emulation.setEmulatedVisionDeficiency(params={"type": VISION[persona["vision"]]}, session_id=sid)
|
|
192
|
+
if persona["media"]:
|
|
193
|
+
await send.Emulation.setEmulatedMedia(params={"features": [{"name": MEDIA[m][0], "value": MEDIA[m][1]} for m in persona["media"]]}, session_id=sid)
|
|
194
|
+
if persona["zoom"] > 1:
|
|
195
|
+
# Zooming a page is a smaller viewport in CSS pixels at a larger scale: the page reflows as it does at that zoom.
|
|
196
|
+
w, h = (viewport or [1280, 800])[:2]
|
|
197
|
+
z = persona["zoom"]
|
|
198
|
+
await send.Emulation.setDeviceMetricsOverride(params={"width": max(320, round(w / z)), "height": max(256, round(h / z)), "deviceScaleFactor": z, "mobile": False}, session_id=sid)
|
|
199
|
+
applied[sid] = True
|
|
200
|
+
except Exception as ex:
|
|
201
|
+
logger.warning("persona emulation not applied: %s", ex)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
_FOCUS_JS = """(function(){
|
|
205
|
+
const el = document.activeElement;
|
|
206
|
+
if (!el || el === document.body || el === document.documentElement) return {none: true};
|
|
207
|
+
const cs = getComputedStyle(el);
|
|
208
|
+
const outline = cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0 && cs.outlineColor !== 'transparent';
|
|
209
|
+
const shadow = cs.boxShadow && cs.boxShadow !== 'none';
|
|
210
|
+
const r = el.getBoundingClientRect();
|
|
211
|
+
const onScreen = r.width > 0 && r.height > 0 && r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth;
|
|
212
|
+
return {none: false, indicator: outline ? 'outline' : shadow ? 'box-shadow' : '', visible: onScreen, tag: el.tagName.toLowerCase()};
|
|
213
|
+
})()"""
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _ax_value(v: Any) -> str:
|
|
217
|
+
return str((v or {}).get("value") or "") if isinstance(v, dict) else ""
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _ax_props(node: Dict[str, Any]) -> Dict[str, Any]:
|
|
221
|
+
out: Dict[str, Any] = {}
|
|
222
|
+
for p in node.get("properties") or []:
|
|
223
|
+
if isinstance(p, dict) and p.get("name"):
|
|
224
|
+
out[str(p["name"])] = (p.get("value") or {}).get("value")
|
|
225
|
+
return out
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def announce(node: Dict[str, Any]) -> str:
|
|
229
|
+
"""One accessibility node as a screen reader says it: role, name, and states."""
|
|
230
|
+
role = _ax_value(node.get("role"))
|
|
231
|
+
name = " ".join(_ax_value(node.get("name")).split())[:150]
|
|
232
|
+
props = _ax_props(node)
|
|
233
|
+
bits = [role or "element"]
|
|
234
|
+
if role == "heading" and props.get("level"):
|
|
235
|
+
bits[0] = f"heading level {props['level']}"
|
|
236
|
+
bits.append(f'"{name}"' if name else ("(no name)" if role in INTERACTIVE or role in ("image", "img") else ""))
|
|
237
|
+
for state in ("checked", "expanded", "pressed", "selected"):
|
|
238
|
+
if state in props and props[state] not in (None, "", "false", False):
|
|
239
|
+
bits.append(state if props[state] in (True, "true") else f"{state}={props[state]}")
|
|
240
|
+
elif state in ("checked", "expanded") and props.get(state) in (False, "false"):
|
|
241
|
+
bits.append(f"not {state}")
|
|
242
|
+
for flag in ("required", "invalid", "disabled"):
|
|
243
|
+
if props.get(flag) not in (None, False, "false", ""):
|
|
244
|
+
bits.append(flag)
|
|
245
|
+
value = _ax_value(node.get("value"))
|
|
246
|
+
if value and role in ("textbox", "searchbox", "combobox", "spinbutton", "slider"):
|
|
247
|
+
bits.append(f"value {value[:80]!r}")
|
|
248
|
+
return " ".join(b for b in bits if b)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def render_tree(nodes: List[Dict[str, Any]], view: str) -> str:
|
|
252
|
+
"""The accessibility tree as a screen reader user hears it: the whole page, or one of its rotor lists."""
|
|
253
|
+
by_id = {str(n.get("nodeId")): n for n in nodes if isinstance(n, dict)}
|
|
254
|
+
lines: List[str] = []
|
|
255
|
+
|
|
256
|
+
def keep(n: Dict[str, Any]) -> bool:
|
|
257
|
+
if n.get("ignored"):
|
|
258
|
+
return False
|
|
259
|
+
role = _ax_value(n.get("role"))
|
|
260
|
+
if view == "headings":
|
|
261
|
+
return role == "heading"
|
|
262
|
+
if view == "landmarks":
|
|
263
|
+
return role in LANDMARKS
|
|
264
|
+
if view == "links":
|
|
265
|
+
return role == "link"
|
|
266
|
+
if view == "form_controls":
|
|
267
|
+
return role in FORM_ROLES
|
|
268
|
+
if role in ("InlineTextBox", "LineBreak"):
|
|
269
|
+
return False
|
|
270
|
+
if role in ("generic", "none", "presentation", "RootWebArea", "group", "LabelText", "paragraph", "Section") and not _ax_value(n.get("name")):
|
|
271
|
+
return False
|
|
272
|
+
if role == "StaticText":
|
|
273
|
+
# Text inside a named element is already in that element's name.
|
|
274
|
+
parent = by_id.get(str(n.get("parentId")))
|
|
275
|
+
return not (parent and _ax_value(parent.get("name")) and _ax_value(parent.get("role")) in INTERACTIVE | {"heading", "image", "img"})
|
|
276
|
+
return True
|
|
277
|
+
|
|
278
|
+
def walk(nid: str, depth: int) -> None:
|
|
279
|
+
n = by_id.get(nid)
|
|
280
|
+
if not n:
|
|
281
|
+
return
|
|
282
|
+
shown = keep(n)
|
|
283
|
+
if shown:
|
|
284
|
+
role = _ax_value(n.get("role"))
|
|
285
|
+
line = f"text {' '.join(_ax_value(n.get('name')).split())[:200]!r}" if role == "StaticText" else announce(n)
|
|
286
|
+
lines.append((" " * min(depth, 8) if view == "page" else "") + line)
|
|
287
|
+
for c in n.get("childIds") or []:
|
|
288
|
+
walk(str(c), depth + (1 if shown else 0))
|
|
289
|
+
|
|
290
|
+
roots = [str(n.get("nodeId")) for n in nodes if isinstance(n, dict) and not n.get("parentId")]
|
|
291
|
+
for r in roots:
|
|
292
|
+
walk(r, 0)
|
|
293
|
+
out = "\n".join(lines)
|
|
294
|
+
if not lines:
|
|
295
|
+
return {"headings": "No headings.", "landmarks": "No landmarks.", "links": "No links.", "form_controls": "No form controls."}.get(view, "The screen reader announces nothing on this page.")
|
|
296
|
+
if len(out) > MAX_VIEW_CHARS:
|
|
297
|
+
out = out[:MAX_VIEW_CHARS] + "\n… (more: read a smaller part with headings, landmarks, links, or form_controls)"
|
|
298
|
+
return out
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
async def focused(browser_session: BrowserSession) -> Dict[str, Any]:
|
|
302
|
+
"""What has focus: as the screen reader announces it, and whether a sighted user can see where it is."""
|
|
303
|
+
cdp = await _cdp(browser_session)
|
|
304
|
+
send, sid = cdp.cdp_client.send, cdp.session_id
|
|
305
|
+
facts = ((await send.Runtime.evaluate(params={"expression": _FOCUS_JS, "returnByValue": True}, session_id=sid)).get("result") or {}).get("value") or {}
|
|
306
|
+
if facts.get("none"):
|
|
307
|
+
return {"none": True, "announce": "Nothing has focus (the page itself)."}
|
|
308
|
+
said = facts.get("tag") or "element"
|
|
309
|
+
try:
|
|
310
|
+
ref = (await send.Runtime.evaluate(params={"expression": "document.activeElement", "returnByValue": False}, session_id=sid)).get("result") or {}
|
|
311
|
+
if ref.get("objectId"):
|
|
312
|
+
tree = await send.Accessibility.getPartialAXTree(params={"objectId": ref["objectId"], "fetchRelatives": False}, session_id=sid)
|
|
313
|
+
nodes = [n for n in tree.get("nodes") or [] if not n.get("ignored")]
|
|
314
|
+
if nodes:
|
|
315
|
+
said = announce(nodes[0])
|
|
316
|
+
except Exception as ex:
|
|
317
|
+
logger.debug("focused: no accessibility node: %s", ex)
|
|
318
|
+
return {"none": False, "announce": said, "indicator": facts.get("indicator") or "", "on_screen": bool(facts.get("visible"))}
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def focus_line(f: Dict[str, Any], sighted: bool) -> str:
|
|
322
|
+
if f.get("none"):
|
|
323
|
+
return f["announce"]
|
|
324
|
+
line = f"Focus: {f['announce']}"
|
|
325
|
+
if sighted:
|
|
326
|
+
if not f.get("on_screen"):
|
|
327
|
+
line += ". It is off screen: a sighted user cannot see where focus is."
|
|
328
|
+
elif not f.get("indicator"):
|
|
329
|
+
line += ". No outline or shadow shows focus (check the screenshot: a focus indicator may still be drawn another way)."
|
|
330
|
+
return line
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def save_findings(out_dir: str, persona: Dict[str, Any], findings: List[Dict[str, Any]]) -> None:
|
|
334
|
+
try:
|
|
335
|
+
Path(out_dir).mkdir(parents=True, exist_ok=True)
|
|
336
|
+
(Path(out_dir) / FINDINGS_FILE).write_text(json.dumps({"persona": persona["id"], "findings": findings}, indent=2), encoding="utf-8")
|
|
337
|
+
except OSError as ex:
|
|
338
|
+
logger.warning("%s not written: %s", FINDINGS_FILE, ex)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def register_persona_tools(tools: Any, persona: Dict[str, Any], findings: List[Dict[str, Any]], out_dir: str) -> None:
|
|
342
|
+
"""record_accessibility_issue always; the keyboard and screen reader actions for a persona that uses them."""
|
|
343
|
+
sighted = uses_vision(persona)
|
|
344
|
+
|
|
345
|
+
@tools.action(
|
|
346
|
+
"Record one accessibility barrier that this person met, as soon as you meet it: title (a few words), "
|
|
347
|
+
"what_happened (what this person met), expected (what a page made for them does), severity (critical, serious, "
|
|
348
|
+
"moderate, minor), wcag (the success criterion, e.g. 2.4.7, when one applies), element (the element as announced or seen)."
|
|
349
|
+
)
|
|
350
|
+
async def record_accessibility_issue(title: str, what_happened: str, severity: str, browser_session: BrowserSession, expected: str = "", wcag: str = "", element: str = "") -> ActionResult:
|
|
351
|
+
clip = lambda v, n: " ".join(str(v or "").split())[:n] # noqa: E731
|
|
352
|
+
title, what = clip(title, 150), clip(what_happened, 600)
|
|
353
|
+
if not title or not what:
|
|
354
|
+
return ActionResult(error="Give a title and what_happened.")
|
|
355
|
+
sev = str(severity or "").lower().strip()
|
|
356
|
+
if sev not in SEVERITIES:
|
|
357
|
+
return ActionResult(error=f"severity is one of {', '.join(SEVERITIES)}.")
|
|
358
|
+
criterion = clip(wcag, 12)
|
|
359
|
+
if criterion and not all(p.isdigit() for p in criterion.split(".")):
|
|
360
|
+
criterion = ""
|
|
361
|
+
url = ""
|
|
362
|
+
try:
|
|
363
|
+
url = await browser_session.get_current_page_url()
|
|
364
|
+
except Exception:
|
|
365
|
+
pass
|
|
366
|
+
item = {"title": title, "what_happened": what, "expected": clip(expected, 400), "severity": sev, "wcag": criterion, "element": clip(element, 200), "url": url}
|
|
367
|
+
if any(f["title"].lower() == title.lower() and f["url"] == url for f in findings):
|
|
368
|
+
return ActionResult(extracted_content=f"Already recorded on this page: {title}")
|
|
369
|
+
findings.append(item)
|
|
370
|
+
save_findings(out_dir, persona, findings)
|
|
371
|
+
return ActionResult(extracted_content=f"Recorded barrier ({sev}{f', WCAG {criterion}' if criterion else ''}): {title}")
|
|
372
|
+
|
|
373
|
+
if keyboard_only(persona):
|
|
374
|
+
|
|
375
|
+
@tools.action("Press one key, as a keyboard user does: Tab, Shift+Tab, Enter, Space, Escape, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown, Backspace. Says what has focus after it.")
|
|
376
|
+
async def press_key(key: str, browser_session: BrowserSession) -> ActionResult:
|
|
377
|
+
raw = str(key or "").strip()
|
|
378
|
+
shift = raw.lower().startswith("shift+")
|
|
379
|
+
name = raw[6:] if shift else raw
|
|
380
|
+
name = {"space": "Space", "spacebar": "Space", "esc": "Escape", "return": "Enter"}.get(name.lower(), name)
|
|
381
|
+
spec = next((v for k, v in KEYS.items() if k.lower() == name.lower()), None)
|
|
382
|
+
if spec is None or (shift and name.lower() != "tab"):
|
|
383
|
+
return ActionResult(error=f"Not a key this person presses: {raw!r}. Use one of: {', '.join(KEYS)}, Shift+Tab.")
|
|
384
|
+
k, code, vk, txt = spec
|
|
385
|
+
try:
|
|
386
|
+
cdp = await _cdp(browser_session)
|
|
387
|
+
send, sid = cdp.cdp_client.send, cdp.session_id
|
|
388
|
+
base = {"key": k, "code": code, "windowsVirtualKeyCode": vk, "nativeVirtualKeyCode": vk, "modifiers": SHIFT if shift else 0}
|
|
389
|
+
await send.Input.dispatchKeyEvent(params={"type": "keyDown", **base, **({"text": txt} if txt else {})}, session_id=sid)
|
|
390
|
+
await send.Input.dispatchKeyEvent(params={"type": "keyUp", **base}, session_id=sid)
|
|
391
|
+
f = await focused(browser_session)
|
|
392
|
+
except Exception as ex:
|
|
393
|
+
return ActionResult(error=f"The key was not pressed: {ex}")
|
|
394
|
+
said = f"Pressed {'Shift+' if shift else ''}{name}. {focus_line(f, sighted)}"
|
|
395
|
+
return ActionResult(extracted_content=said, long_term_memory=said)
|
|
396
|
+
|
|
397
|
+
@tools.action("Type text into the field that has focus, as a keyboard user does. Move focus to the field with press_key first.")
|
|
398
|
+
async def type_text(text: str, browser_session: BrowserSession) -> ActionResult:
|
|
399
|
+
try:
|
|
400
|
+
f = await focused(browser_session)
|
|
401
|
+
if f.get("none"):
|
|
402
|
+
return ActionResult(error="Nothing has focus: move to the field with press_key first.")
|
|
403
|
+
cdp = await _cdp(browser_session)
|
|
404
|
+
await cdp.cdp_client.send.Input.insertText(params={"text": str(text or "")}, session_id=cdp.session_id)
|
|
405
|
+
f = await focused(browser_session)
|
|
406
|
+
except Exception as ex:
|
|
407
|
+
return ActionResult(error=f"Not typed: {ex}")
|
|
408
|
+
said = f"Typed into {f.get('announce', 'the field')}."
|
|
409
|
+
return ActionResult(extracted_content=said, long_term_memory=said)
|
|
410
|
+
|
|
411
|
+
@tools.action("Say what has focus now, as the screen reader announces it, and whether focus can be seen.")
|
|
412
|
+
async def where_is_focus(browser_session: BrowserSession) -> ActionResult:
|
|
413
|
+
try:
|
|
414
|
+
return ActionResult(extracted_content=focus_line(await focused(browser_session), sighted))
|
|
415
|
+
except Exception as ex:
|
|
416
|
+
return ActionResult(error=f"Focus not read: {ex}")
|
|
417
|
+
|
|
418
|
+
@tools.action(
|
|
419
|
+
"What a screen reader announces on this page: view is page (everything in reading order), headings, landmarks, "
|
|
420
|
+
"links, or form_controls (each with its name and state, as a screen reader's lists show them)."
|
|
421
|
+
)
|
|
422
|
+
async def screen_reader_view(browser_session: BrowserSession, view: str = "page") -> ActionResult:
|
|
423
|
+
v = view if view in VIEWS else "page"
|
|
424
|
+
try:
|
|
425
|
+
cdp = await _cdp(browser_session)
|
|
426
|
+
send, sid = cdp.cdp_client.send, cdp.session_id
|
|
427
|
+
try:
|
|
428
|
+
await send.Accessibility.enable(session_id=sid)
|
|
429
|
+
except Exception:
|
|
430
|
+
pass
|
|
431
|
+
tree = await send.Accessibility.getFullAXTree(params={}, session_id=sid)
|
|
432
|
+
except Exception as ex:
|
|
433
|
+
return ActionResult(error=f"The accessibility tree could not be read: {ex}")
|
|
434
|
+
out = render_tree(tree.get("nodes") or [], v)
|
|
435
|
+
return ActionResult(extracted_content=f"Screen reader, {v.replace('_', ' ')}:\n{out}", include_extracted_content_only_once=True)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Asking a person whether a run goes on past a limit, instead of ending it there.
|
|
3
|
+
|
|
4
|
+
When ForgeQE says a person can be asked (the run request's ask_to_continue), a run that reaches its step limit or its
|
|
5
|
+
time limit emits {"type": "continue?", "id", "limit", "text", "more"} and waits. ForgeQE asks the person and writes
|
|
6
|
+
"continue <id> yes" or "continue <id> no" on stdin (cli.py hands the line to receive). Yes gives the run as much again;
|
|
7
|
+
no, or no answer within ANSWER_SECONDS, ends it the way the limit always did, keeping what it did. While a question waits
|
|
8
|
+
the agent is paused, and the wait does not count against the run's time.
|
|
9
|
+
"""
|
|
10
|
+
import asyncio
|
|
11
|
+
import re
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any, Callable, Dict, Optional
|
|
14
|
+
|
|
15
|
+
ANSWER_SECONDS = 600.0
|
|
16
|
+
_LINE = re.compile(r"^continue ([a-z0-9]{1,16}) (yes|no)$")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Answers:
|
|
20
|
+
def __init__(self) -> None:
|
|
21
|
+
self._waiting: Dict[str, asyncio.Future] = {}
|
|
22
|
+
self._n = 0
|
|
23
|
+
# Seconds spent waiting for answers, which the run's own clock leaves out.
|
|
24
|
+
self.waited = 0.0
|
|
25
|
+
|
|
26
|
+
def receive(self, line: str) -> bool:
|
|
27
|
+
"""A stdin line: an answer to a waiting question. Anything else (or an id nobody asked) is ignored."""
|
|
28
|
+
m = _LINE.match(line.strip().lower())
|
|
29
|
+
if not m:
|
|
30
|
+
return False
|
|
31
|
+
fut = self._waiting.get(m.group(1))
|
|
32
|
+
if fut is None or fut.done():
|
|
33
|
+
return False
|
|
34
|
+
fut.set_result(m.group(2) == "yes")
|
|
35
|
+
return True
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def asking(self) -> bool:
|
|
39
|
+
return any(not f.done() for f in self._waiting.values())
|
|
40
|
+
|
|
41
|
+
async def ask(self, emit: Callable[[Dict[str, Any]], None], limit: str, text: str, more: str, timeout: Optional[float] = None, cancel: Optional[asyncio.Event] = None) -> bool:
|
|
42
|
+
"""Ask once; True only on a yes in time. Stopping the run (cancel) answers no."""
|
|
43
|
+
self._n += 1
|
|
44
|
+
qid = f"q{self._n}"
|
|
45
|
+
fut: asyncio.Future = asyncio.get_running_loop().create_future()
|
|
46
|
+
self._waiting[qid] = fut
|
|
47
|
+
emit({"type": "continue?", "id": qid, "limit": limit, "text": text, "more": more})
|
|
48
|
+
t0 = time.monotonic()
|
|
49
|
+
stop = asyncio.ensure_future(cancel.wait()) if cancel is not None else None
|
|
50
|
+
try:
|
|
51
|
+
done, _ = await asyncio.wait({fut, *([stop] if stop else [])}, timeout=ANSWER_SECONDS if timeout is None else timeout, return_when=asyncio.FIRST_COMPLETED)
|
|
52
|
+
if fut in done:
|
|
53
|
+
return bool(fut.result())
|
|
54
|
+
if not done:
|
|
55
|
+
emit({"type": "log", "level": "warn", "text": "No answer in time: the run stops here, keeping what it did."})
|
|
56
|
+
return False
|
|
57
|
+
finally:
|
|
58
|
+
if stop is not None:
|
|
59
|
+
stop.cancel()
|
|
60
|
+
if not fut.done():
|
|
61
|
+
fut.cancel()
|
|
62
|
+
self.waited += time.monotonic() - t0
|
|
63
|
+
self._waiting.pop(qid, None)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# One run per engine process: the stdin reader and the run share this.
|
|
67
|
+
ANSWERS = Answers()
|