@capagents/forgeqe 3.2.2 → 3.2.4

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 (94) hide show
  1. package/HOW_TO_USE.md +9 -1
  2. package/dist/docs-site/docs/area-api/index.html +1 -1
  3. package/dist/docs-site/docs/get-started/index.html +7 -0
  4. package/dist/docs-site/docs/search.js +1 -1
  5. package/dist/forgeqe.js +1836 -1832
  6. package/dist/web/assets/{3d-force-graph-CTC0tr_c.js → 3d-force-graph-iP39yI0v.js} +1 -1
  7. package/dist/web/assets/{Agent-wRS-AWzy.js → Agent-COXI7WgW.js} +6 -6
  8. package/dist/web/assets/{AgentWork-GXWfoD_Z.js → AgentWork-LD5CQxet.js} +1 -1
  9. package/dist/web/assets/ApiTests-Dpwqmpr1.js +14 -0
  10. package/dist/web/assets/{Browse-B5RXYaB5.js → Browse-DIcTvI-C.js} +1 -1
  11. package/dist/web/assets/Chat-DNw_jYbD.js +3 -0
  12. package/dist/web/assets/{CommandPalette-BipNmH6a.js → CommandPalette-B6QRxOka.js} +1 -1
  13. package/dist/web/assets/{Compare-FHtKxtLJ.js → Compare-hz0ft2yP.js} +1 -1
  14. package/dist/web/assets/Cost-C231Bf_A.js +1 -0
  15. package/dist/web/assets/{Data-Ctg96el3.js → Data-DODs050c.js} +3 -3
  16. package/dist/web/assets/Desktop-CUV43rdi.js +1 -0
  17. package/dist/web/assets/DesktopReview-WEIFBq-L.js +2 -0
  18. package/dist/web/assets/{DeviceScreen-CoArZGyY.js → DeviceScreen-ClPTc5Ot.js} +1 -1
  19. package/dist/web/assets/{Evidence-D_90W10z.js → Evidence-DhN_bTZ-.js} +1 -1
  20. package/dist/web/assets/{Explore-CD7Mq4il.js → Explore-CjowiWJe.js} +2 -2
  21. package/dist/web/assets/{Features-CLHC2bGL.js → Features-BnagyBie.js} +1 -1
  22. package/dist/web/assets/Flags-DlkY7U4M.js +2 -0
  23. package/dist/web/assets/{Flaky-Bzt9VcYv.js → Flaky-BkD01mRw.js} +1 -1
  24. package/dist/web/assets/Impact-BM4_vIEv.js +3 -0
  25. package/dist/web/assets/Jobs-U9kJUVM9.js +5 -0
  26. package/dist/web/assets/{KindPage-CJcRnrTe.js → KindPage-BkK5AQw0.js} +3 -3
  27. package/dist/web/assets/{LiveDevice-BP47IrPa.js → LiveDevice-Bjc2r797.js} +1 -1
  28. package/dist/web/assets/{Migration-BaVfcEYa.js → Migration-BDDE_0TS.js} +5 -5
  29. package/dist/web/assets/{Mobile-CLoZlBuq.js → Mobile-D2qAF8X5.js} +1 -1
  30. package/dist/web/assets/{Observability-CaRIhlKg.js → Observability-CLFC0ze7.js} +1 -1
  31. package/dist/web/assets/PageAgent-Dz5CuEUe.js +1 -0
  32. package/dist/web/assets/{Product-BdY0j-z8.js → Product-DkEI-0vu.js} +4 -4
  33. package/dist/web/assets/Production-CgfLjbSa.js +1 -0
  34. package/dist/web/assets/Quality-8E667GJi.js +1 -0
  35. package/dist/web/assets/{Readiness-D4nY3Nr1.js → Readiness-Bbkq2lNV.js} +1 -1
  36. package/dist/web/assets/Record-JR4HeyTe.js +1 -0
  37. package/dist/web/assets/{Regression-DhNAgDgD.js → Regression-_9u6qDMk.js} +3 -3
  38. package/dist/web/assets/{RelationGraph-UXFyQOKO.js → RelationGraph-BnhbeI6t.js} +1 -1
  39. package/dist/web/assets/{Reports-D4-y2w-2.js → Reports-DxjHb0vA.js} +2 -2
  40. package/dist/web/assets/Response-BvQV20vS.js +9 -0
  41. package/dist/web/assets/{Responsive-DljiUZXJ.js → Responsive-DNC31nTr.js} +2 -2
  42. package/dist/web/assets/{RunDiff-DjUiMBsq.js → RunDiff-BXqh9adv.js} +1 -1
  43. package/dist/web/assets/Runs-PsPMVpQl.js +2 -0
  44. package/dist/web/assets/{Settings-CD1RbHXf.js → Settings-DEOCWX5o.js} +15 -15
  45. package/dist/web/assets/{Steps-DG1WYfYK.js → Steps-C18OGSAM.js} +3 -3
  46. package/dist/web/assets/{TestCases-BfZzshUI.js → TestCases-MIOqrvt0.js} +1 -1
  47. package/dist/web/assets/TestData-DtPsGVwq.js +2 -0
  48. package/dist/web/assets/TestDebt-C8zEVY4j.js +1 -0
  49. package/dist/web/assets/TestManagement-cXbBFksQ.js +4 -0
  50. package/dist/web/assets/{WhatsNew-ZorWOqDL.js → WhatsNew-vGPOJXT2.js} +1 -1
  51. package/dist/web/assets/{dataParts-CeMHTXLx.js → dataParts-D08j24QD.js} +2 -2
  52. package/dist/web/assets/{desktopAppPath-BVJxel_D.js → desktopAppPath-DyQr1aFk.js} +1 -1
  53. package/dist/web/assets/{diff-BXu8cULX.js → diff-CVufIkRR.js} +1 -1
  54. package/dist/web/assets/{highlight-Cd5aQvev.js → highlight-BpaRxd70.js} +1 -1
  55. package/dist/web/assets/index-FhirFP-O.css +2 -0
  56. package/dist/web/assets/{index-F95avSUY.js → index-q1r33z9g.js} +12 -12
  57. package/dist/web/assets/input-ChhA0xMm.js +1 -0
  58. package/dist/web/assets/{pageBack-BNLSF2VR.js → pageBack-Dhl5PHZE.js} +1 -1
  59. package/dist/web/assets/{palette-BS9ixqiJ.js → palette-CpGAHix6.js} +1 -1
  60. package/dist/web/assets/{paletteCommands-DferMQDH.js → paletteCommands-Der7qNEc.js} +1 -1
  61. package/dist/web/assets/{parts-69Ei7EPi.js → parts-eyvIPENF.js} +1 -1
  62. package/dist/web/assets/{productParts-PERPm-xD.js → productParts-2Y8IjOa0.js} +1 -1
  63. package/dist/web/assets/{qualityParts-BRZOCiQs.js → qualityParts-CdoLEG3a.js} +1 -1
  64. package/dist/web/assets/{recordTest-DVJCNI0y.js → recordTest-vps_1X_-.js} +1 -1
  65. package/dist/web/assets/{stepper-t0O_8eQo.js → stepper-Cb6rnj2p.js} +1 -1
  66. package/dist/web/index.html +5 -5
  67. package/docs/user-guide.html +8 -1
  68. package/package.json +1 -1
  69. package/prompts/brain.md +1 -1
  70. package/py/forgeqe_engine/copilot_gateway.py +81 -2
  71. package/py/forgeqe_engine/copilot_models.py +37 -1
  72. package/py/forgeqe_engine/llm.py +10 -1
  73. package/py/forgeqe_engine/recordsession.py +2 -2
  74. package/py/forgeqe_engine/webrecord.py +9 -3
  75. package/py/forgeqe_engine/webrecord_page.py +87 -10
  76. package/dist/web/assets/ApiTests-BH_mbOVX.js +0 -10
  77. package/dist/web/assets/Chat-CVF0hHdk.js +0 -3
  78. package/dist/web/assets/Cost-BDwt86M-.js +0 -1
  79. package/dist/web/assets/Desktop-B2k0qH7c.js +0 -1
  80. package/dist/web/assets/DesktopReview-CE65JglI.js +0 -2
  81. package/dist/web/assets/Flags-FpR9O_13.js +0 -2
  82. package/dist/web/assets/Impact-BC8w7uQ5.js +0 -3
  83. package/dist/web/assets/Jobs-DeBncFIN.js +0 -5
  84. package/dist/web/assets/PageAgent-C_oSStNT.js +0 -1
  85. package/dist/web/assets/Production-BhDff1v6.js +0 -1
  86. package/dist/web/assets/Quality-EATW3zGE.js +0 -1
  87. package/dist/web/assets/Record-CIf6M72U.js +0 -1
  88. package/dist/web/assets/Response-CpHrRtzJ.js +0 -9
  89. package/dist/web/assets/Runs-DC0tJWvX.js +0 -2
  90. package/dist/web/assets/TestData-BoyXYHtp.js +0 -2
  91. package/dist/web/assets/TestDebt-CX1XT-CA.js +0 -1
  92. package/dist/web/assets/TestManagement-BTdMN3Bl.js +0 -4
  93. package/dist/web/assets/index-CgpH1pj9.css +0 -2
  94. package/dist/web/assets/input-BmJ7dt1C.js +0 -1
@@ -35,7 +35,18 @@ import uuid
35
35
  from logging.handlers import RotatingFileHandler
36
36
  from typing import Any, Callable, Dict, List, Optional, TextIO, Tuple
37
37
 
38
- from .copilot_models import AUTO, ModelHealth, client_outdated, model_failed, route, stand_in
38
+ from .copilot_models import (
39
+ AUTO,
40
+ SHOT_LEVELS,
41
+ ModelHealth,
42
+ client_outdated,
43
+ model_failed,
44
+ network_failed,
45
+ route,
46
+ screenshot_level,
47
+ screenshots_failed,
48
+ stand_in,
49
+ )
39
50
  from .systemcerts import use_system_certificates
40
51
 
41
52
  TOKEN_ENV = "COPILOT_GITHUB_TOKEN"
@@ -426,6 +437,52 @@ def runtime_load_hint(message: str, probe: Callable[[str], Optional[int]] = prob
426
437
  return f"Windows error {code}. If it persists, {redo}."
427
438
 
428
439
 
440
+ # A smaller screenshot: its longest side at most this, as JPEG, for a network that does not let a full one through.
441
+ SMALL_SIDE = 1024
442
+ SMALL_QUALITY = 60
443
+ # Words the gateway starts an error with when it changed what the next requests send; the engine gives such a failure
444
+ # room to try again (ModelFailures, llm.py).
445
+ ADJUSTED = "GitHub Copilot adjusted the next requests"
446
+ NO_SHOT_NOTE = "[screenshot not sent: this network does not let requests with one reach GitHub Copilot; work from the page's text]"
447
+
448
+
449
+ def smaller_image(data_b64: str) -> Optional[Tuple[str, str]]:
450
+ """A screenshot made smaller with Pillow (the engine has it, pinned by browser-use): ("image/jpeg", base64), or None
451
+ when it cannot be read as an image (it is then left out, never sent as it came)."""
452
+ import base64
453
+ import io as _io
454
+
455
+ try:
456
+ from PIL import Image
457
+
458
+ raw = base64.b64decode(data_b64, validate=True)
459
+ with Image.open(_io.BytesIO(raw)) as im:
460
+ im.load()
461
+ im = im.convert("RGB")
462
+ im.thumbnail((SMALL_SIDE, SMALL_SIDE))
463
+ out = _io.BytesIO()
464
+ im.save(out, format="JPEG", quality=SMALL_QUALITY, optimize=True)
465
+ return "image/jpeg", base64.b64encode(out.getvalue()).decode("ascii")
466
+ except Exception:
467
+ return None
468
+
469
+
470
+ def with_screenshots(req: Dict[str, Any], level: int) -> Dict[str, Any]:
471
+ """The request with its screenshots as `level` says (screenshot_level): as they are, smaller, or none."""
472
+ if level <= 0 or not req.get("attachments"):
473
+ return req
474
+ if level == 1:
475
+ kept = []
476
+ for a in req["attachments"]:
477
+ small = smaller_image(str(a.get("data") or ""))
478
+ if small:
479
+ kept.append({**a, "mimeType": small[0], "data": small[1]})
480
+ if len(kept) == len(req["attachments"]):
481
+ return {**req, "attachments": kept}
482
+ prompt = re.sub(r"\[image attached: screenshot-\d+\]", NO_SHOT_NOTE, req["prompt"])
483
+ return {**req, "attachments": [], "prompt": prompt}
484
+
485
+
429
486
  def websockets_on(env: Optional[Dict[str, str]] = None) -> bool:
430
487
  return str((os.environ if env is None else env).get(WEBSOCKETS_ENV, "")).strip().lower() in ("1", "true", "yes", "on")
431
488
 
@@ -664,6 +721,11 @@ class Copilot:
664
721
  if why:
665
722
  gateway_log(rid, why)
666
723
  req = {**req, "model": model}
724
+ # Screenshots as this network lets them through (smaller, or none, after requests carrying them could not be sent).
725
+ shots = screenshot_level(self.health) if needs_vision else 0
726
+ if shots:
727
+ req = with_screenshots(req, shots)
728
+ gateway_log(rid, f"screenshots sent {SHOT_LEVELS[shots]}: requests carrying them did not reach GitHub Copilot from this computer")
667
729
  # Whether any text went to the caller: once it has, the request cannot be sent again to another model.
668
730
  sent = {"text": False}
669
731
  if on_text is not None:
@@ -678,6 +740,23 @@ class Copilot:
678
740
  try:
679
741
  out = await self._complete(rid, req, on_text, gone)
680
742
  except GatewayError as e:
743
+ if network_failed(e.message):
744
+ # The request never reached GitHub's Copilot server: every model is behind it, so no model is to
745
+ # blame. What got through when this happened was requests without a screenshot.
746
+ if needs_vision and shots < 2:
747
+ now = screenshots_failed(self.health, shots)
748
+ gateway_log(rid, f"could not send the request with its screenshot: the next requests send screenshots {SHOT_LEVELS[now]}")
749
+ raise GatewayError(
750
+ e.status,
751
+ f"{ADJUSTED}: this request, with its screenshot, could not be sent to GitHub Copilot from this computer, so the next "
752
+ f"ones send {'a smaller screenshot' if now == 1 else 'no screenshot'}. A company network or proxy that limits "
753
+ f"uploads to api.business.githubcopilot.com does this. {e.message}"[:2000],
754
+ )
755
+ raise GatewayError(
756
+ e.status,
757
+ f"GitHub Copilot's server could not be reached from this computer: check the network or proxy for "
758
+ f"api.business.githubcopilot.com. {e.message}"[:2000],
759
+ )
681
760
  if not model_failed(e.status, e.message):
682
761
  raise
683
762
  self.health.fail(model)
@@ -713,7 +792,7 @@ class Copilot:
713
792
  gateway_log(rid, f"{model} gave no answer in {took:.0f}s: avoided for a while")
714
793
  raise
715
794
  except GatewayError as e:
716
- gateway_log(rid, f"error {e.status} after {time.monotonic() - started:.1f}s: {e.message[:300]}")
795
+ gateway_log(rid, f"error {e.status} after {time.monotonic() - started:.1f}s: {e.message[:1200]}")
717
796
  raise
718
797
  self.health.recovered(model)
719
798
  calls = out["choices"][0]["message"].get("tool_calls") or []
@@ -55,13 +55,49 @@ def client_outdated(message: str) -> bool:
55
55
  return bool(_OUTDATED.search(message or ""))
56
56
 
57
57
 
58
+ # Copilot's runtime could not send the request to GitHub's Copilot server at all (2026-11-20 on, from one company
59
+ # network: "Failed native model HTTP request: error sending request for url (https://api.business.githubcopilot.com/
60
+ # responses): client error (SendRequest)"). Every model is reached at that address, so another model fails the same way;
61
+ # what got through was the requests without a screenshot.
62
+ _NETWORK = re.compile(r"failed native model http request|error sending request for url|client error \(sendrequest\)", re.I)
63
+
64
+
65
+ def network_failed(message: str) -> bool:
66
+ """Whether Copilot's error says the request could not be sent to GitHub's Copilot server (the network, not a model)."""
67
+ return bool(_NETWORK.search(message or ""))
68
+
69
+
58
70
  def model_failed(status: Optional[int], message: str) -> bool:
59
71
  """Whether a failed request says the model itself is not working: a time-out, or a model error of Copilot's."""
60
72
  if status == 504:
61
73
  return True
62
74
  if status != 502:
63
75
  return False
64
- return not _NOT_THE_MODEL.search(message or "") and not client_outdated(message)
76
+ return not _NOT_THE_MODEL.search(message or "") and not client_outdated(message) and not network_failed(message)
77
+
78
+
79
+ # How screenshots go to Copilot while requests carrying them do not get through (`screenshot_level`): kept like a model's
80
+ # health, by these names, for COOLDOWN_S, then screenshots go as they are again.
81
+ SMALLER_SHOTS = "screenshots:smaller"
82
+ NO_SHOTS = "screenshots:none"
83
+ SHOT_LEVELS = ("as they are", "smaller", "not at all")
84
+
85
+
86
+ def screenshot_level(health: "ModelHealth") -> int:
87
+ """0: screenshots as they are; 1: smaller (one side at most SMALL_SIDE, JPEG); 2: none, the page's text only."""
88
+ if not health.healthy(NO_SHOTS):
89
+ return 2
90
+ if not health.healthy(SMALLER_SHOTS):
91
+ return 1
92
+ return 0
93
+
94
+
95
+ def screenshots_failed(health: "ModelHealth", level: int) -> int:
96
+ """A request with screenshots at `level` could not be sent: the next ones go one level down. Returns the new level."""
97
+ if level >= 2:
98
+ return 2
99
+ health.fail(NO_SHOTS if level == 1 else SMALLER_SHOTS)
100
+ return level + 1
65
101
 
66
102
 
67
103
  def health_file() -> str:
@@ -255,10 +255,17 @@ class ModelFailures:
255
255
  self.timeout_s = timeout_s
256
256
  self.count = 0
257
257
  self.reason = ""
258
+ # Failures after which the gateway changed what the next request sends (another model, a smaller screenshot or
259
+ # none): each gives one more try, at most MAX_ROOM, so a run is not stopped just before the change is tried.
260
+ self.room = 0
261
+
262
+ MAX_ROOM = 3
263
+ _CHANGED = ("GitHub Copilot adjusted the next requests", "GitHub Copilot switched models")
258
264
 
259
265
  def answered(self) -> None:
260
266
  self.count = 0
261
267
  self.reason = ""
268
+ self.room = 0
262
269
 
263
270
  def failed(self, error: BaseException, elapsed_s: float = 0.0) -> None:
264
271
  import asyncio
@@ -271,10 +278,12 @@ class ModelFailures:
271
278
  return
272
279
  self.count += 1
273
280
  self.reason = reason
281
+ if any(w in str(getattr(error, "message", "") or error) for w in self._CHANGED):
282
+ self.room = min(self.MAX_ROOM, self.room + 1)
274
283
 
275
284
  @property
276
285
  def stuck(self) -> bool:
277
- return self.count >= self.limit
286
+ return self.count >= self.limit + self.room
278
287
 
279
288
  def message(self) -> str:
280
289
  where = (
@@ -126,7 +126,7 @@ SNAPSHOT_FN = r"""function (dx, dy, f, VW, VH) {
126
126
  }
127
127
  for (const el of all('input,textarea,select')) {
128
128
  if (out.fields.length >= 60 || skip(el)) continue;
129
- const type = (el.getAttribute('type') || el.tagName).toLowerCase();
129
+ const type = (el.tagName === 'INPUT' ? (el.type || 'text') : el.tagName).toLowerCase();
130
130
  if (/^(hidden|submit|button|image|reset|file)$/.test(type)) continue;
131
131
  const box = seen(el); if (!box) continue;
132
132
  const label = (el.getAttribute('aria-label') || (el.labels && el.labels[0] && el.labels[0].innerText) || el.getAttribute('placeholder') || el.name || '').replace(/\s+/g, ' ').trim().slice(0, 80);
@@ -1005,7 +1005,7 @@ class RecordSession:
1005
1005
  opts = data.get("options")
1006
1006
  msg = rec.on_select(await target(data), str(data.get("text") or ""), options=opts if isinstance(opts, list) else None)
1007
1007
  elif kind == "press":
1008
- msg = rec.on_press(str(data.get("keys") or ""), in_field=bool(data.get("in_field")), autocomplete=bool(data.get("autocomplete")))
1008
+ msg = rec.on_press(str(data.get("keys") or ""), in_field=bool(data.get("in_field")), autocomplete=bool(data.get("autocomplete")), effect=data.get("effect") is True)
1009
1009
  elif kind == "upload":
1010
1010
  msg = await self._uploaded(sid, data, ctx, target)
1011
1011
  elif kind == "unsupported":
@@ -49,6 +49,7 @@ MAX_DIALOG_MESSAGE = 300
49
49
  # Keys recorded inside a text field; any other key there is typing.
50
50
  FIELD_KEYS = ("Enter", "Escape")
51
51
  AUTOCOMPLETE_KEYS = ("ArrowDown", "ArrowUp")
52
+ TAB_KEYS = ("Tab", "Shift+Tab")
52
53
  _NAME = re.compile(r"[^a-z0-9_]+")
53
54
  # Files never recorded for an upload, as ForgeQE's attachments refuse them (src/mcp/attachtools.ts): credentials and keys.
54
55
  SECRET_FILE = re.compile(r"^(?:forgeqe\.ya?ml|credentials\.json|application_default_credentials\.json|auth\.json|llms\.json|id_(?:rsa|dsa|ecdsa|ed25519)|.*\.(?:pem|key|pfx|p12|kdbx))$", re.I)
@@ -717,17 +718,22 @@ class WebRecorder:
717
718
  self._add(step)
718
719
  return describe(step)
719
720
 
720
- def on_press(self, keys: str, *, in_field: bool = False, autocomplete: bool = False) -> Optional[str]:
721
+ def on_press(self, keys: str, *, in_field: bool = False, autocomplete: bool = False, effect: bool = False) -> Optional[str]:
722
+ """
723
+ A key the tester pressed. `effect`: a Tab the page reacted to (a suggestion accepted, a field checked as the focus
724
+ left it: the page script's watchTab); a Tab that only moves on is never sent.
725
+ """
721
726
  if self.paused or not keys:
722
727
  return None
723
728
  key = keys.split("+")[-1]
724
- if in_field and "+" not in keys and key not in FIELD_KEYS and not (autocomplete and key in AUTOCOMPLETE_KEYS):
729
+ tab = effect and keys in TAB_KEYS
730
+ if in_field and "+" not in keys and key not in FIELD_KEYS and not (autocomplete and key in AUTOCOMPLETE_KEYS) and not tab:
725
731
  return None
726
732
  self._last_action = self._now()
727
733
  self._last_click = None
728
734
  step: Dict[str, Any] = {"op": "press", "keys": keys}
729
735
  # An arrow key in a field that suggests as it is typed in: the replay waits for the suggestions first.
730
- if in_field and autocomplete and key in AUTOCOMPLETE_KEYS and self.steps[-1].get("op") in ("input", "press"):
736
+ if in_field and autocomplete and (key in AUTOCOMPLETE_KEYS or tab) and self.steps[-1].get("op") in ("input", "press"):
731
737
  step["suggestions"] = True
732
738
  self._add(step)
733
739
  return describe(self.steps[-1])
@@ -36,7 +36,11 @@ RECORDER_JS = r"""(() => {
36
36
  // marked as a frame's, and ForgeQE finds the frame's place in the page through the DevTools protocol. The Recorder
37
37
  // panel and badge are the top page's only; a frame shows only the pick highlight while one is picked in it.
38
38
  const inFrame = window.top !== window;
39
- const send = (ev) => { try { globalThis[CFG.binding](JSON.stringify(inFrame ? { ...ev, frame: true } : ev)); } catch (e) {} };
39
+ const post = (ev) => { try { globalThis[CFG.binding](JSON.stringify(inFrame ? { ...ev, frame: true } : ev)); } catch (e) {} };
40
+ // A Tab being watched (watchTab below) is settled before anything else is sent, so its step comes in the order it was
41
+ // pressed; the fill of the field it left, sent as the focus leaves, comes first.
42
+ let tabWatch = null, flushing = null, settleTab = () => {};
43
+ const send = (ev) => { if (tabWatch && !(ev.kind === 'fill' && flushing === tabWatch.e)) settleTab(); post(ev); };
40
44
  const norm = (s) => String(s || '').replace(/\s+/g, ' ').trim();
41
45
 
42
46
  // ---- web components: open shadow roots -----------------------------------------------------------------------
@@ -83,12 +87,15 @@ RECORDER_JS = r"""(() => {
83
87
  for (let i = 0, c = e; c && i <= 5; i++, c = up(c)) if (actionable(c)) return c;
84
88
  return e;
85
89
  };
90
+ // An input's type as the browser treats it (`e.type`), never the raw attribute: a type it does not know
91
+ // (type="input", as some date fields have) or none is a text field, and the attribute would hide that.
92
+ const inType = (e) => (e && e.tagName === 'INPUT' ? String(e.type || 'text') : '').toLowerCase();
86
93
  const TEXT_TYPES = new Set(['', 'text', 'search', 'email', 'tel', 'url', 'number', 'password', 'date', 'time', 'datetime-local', 'month', 'week']);
87
- const isField = (e) => !!e && ((e.tagName === 'INPUT' && TEXT_TYPES.has((e.getAttribute('type') || '').toLowerCase())) || e.tagName === 'TEXTAREA' || e.isContentEditable);
88
- const isPassword = (e) => !!e && e.tagName === 'INPUT' && (e.getAttribute('type') || '').toLowerCase() === 'password';
94
+ const isField = (e) => !!e && ((e.tagName === 'INPUT' && TEXT_TYPES.has(inType(e))) || e.tagName === 'TEXTAREA' || e.isContentEditable);
95
+ const isPassword = (e) => !!e && e.tagName === 'INPUT' && inType(e) === 'password';
89
96
  const autocomplete = (e) => !!e && (e.getAttribute('role') === 'combobox' || e.hasAttribute('aria-autocomplete') || e.hasAttribute('aria-expanded') || e.hasAttribute('list'));
90
97
  const implicitRole = (e) => {
91
- const t = e.tagName, type = (e.getAttribute('type') || '').toLowerCase();
98
+ const t = e.tagName, type = inType(e);
92
99
  if (t === 'A') return e.hasAttribute('href') ? 'link' : '';
93
100
  if (t === 'BUTTON' || t === 'SUMMARY') return 'button';
94
101
  if (t === 'SELECT') return e.multiple || e.size > 1 ? 'listbox' : 'combobox';
@@ -128,7 +135,7 @@ RECORDER_JS = r"""(() => {
128
135
  if (l) return l;
129
136
  const t = e.tagName;
130
137
  if (t === 'INPUT') {
131
- const type = (e.getAttribute('type') || '').toLowerCase();
138
+ const type = inType(e);
132
139
  if (['button', 'submit', 'reset'].includes(type)) return norm(e.value || (type === 'submit' ? 'Submit' : ''));
133
140
  if (type === 'image') return norm(e.getAttribute('alt'));
134
141
  return norm(e.getAttribute('placeholder') || e.getAttribute('title'));
@@ -822,14 +829,21 @@ RECORDER_JS = r"""(() => {
822
829
  // Texts the person kept from the page as variables (a one-time code it shows): typed into a password field, the
823
830
  // step types the variable, not a secret (the text is the variable's, kept with the recording already).
824
831
  const keptTexts = [];
832
+ // Typing a person started with a key only (a mask took the key and wrote the field itself): the field's text then, so
833
+ // a key that changed nothing (a field that takes none) is no step.
834
+ let keysOnly = false, before = '';
835
+ const fieldText = (e) => (e.isContentEditable ? norm(e.innerText) : String(e.value || ''));
825
836
  const flush = () => {
826
837
  const e = dirty;
827
838
  dirty = null;
828
839
  if (!e) return;
840
+ if (keysOnly && fieldText(e) === before) return;
841
+ flushing = e;
829
842
  const pw = isPassword(e);
830
843
  const typed = pw ? String(e.value || '').trim() : '';
831
844
  const kept = pw && typed && keptTexts.includes(typed);
832
845
  send({ kind: 'fill', ...describeEl(e), password: pw && !kept, value: pw && !kept ? null : (e.isContentEditable ? norm(e.innerText) : kept ? typed : e.value), ...(kept ? { kept: true } : pw ? whosePassword(e) : {}) });
846
+ flushing = null;
833
847
  };
834
848
  window.addEventListener('input', (ev) => {
835
849
  if (!ev.isTrusted || picking || ours(ev) || paused) return;
@@ -839,7 +853,27 @@ RECORDER_JS = r"""(() => {
839
853
  if (dirty && dirty !== e) flush();
840
854
  if (isPassword(e)) printPassword(e);
841
855
  dirty = e;
856
+ keysOnly = false;
842
857
  }, true);
858
+ // A field that takes the person's key or edit itself (a phone, card or date mask cancels it and writes the value with
859
+ // its own script, whose input event is not the person's): the typing starts at the person's own key or edit, and the
860
+ // field's text is read when they move on, as for any field. Only a trusted key starts it: the page cannot make a step.
861
+ const typedIn = (ev) => {
862
+ if (!ev.isTrusted || picking || ours(ev) || paused) return;
863
+ if (ev.type === 'keydown' && (ev.ctrlKey || ev.metaKey || ev.altKey || !(ev.key.length === 1 || ev.key === 'Backspace' || ev.key === 'Delete'))) return;
864
+ const t = deep(ev);
865
+ const e = t && t.nodeType === 1 && t.isContentEditable ? editableRoot(t) : t;
866
+ if (!isField(e) || e.readOnly || e.disabled) return;
867
+ if (dirty === e) return;
868
+ if (dirty) flush();
869
+ dirty = e;
870
+ keysOnly = true;
871
+ before = fieldText(e);
872
+ };
873
+ window.addEventListener('keydown', typedIn, true);
874
+ window.addEventListener('beforeinput', typedIn, true);
875
+ // A password the mask wrote: fingerprinted once the key is done, as typing fingerprints it.
876
+ window.addEventListener('keyup', (ev) => { if (ev.isTrusted && keysOnly && dirty && isPassword(dirty) && deep(ev) === dirty) printPassword(dirty); }, true);
843
877
  window.addEventListener('focusout', (ev) => { if (dirty && (deep(ev) === dirty || ev.target === dirty)) flush(); }, true);
844
878
  window.addEventListener('pagehide', flush, true);
845
879
  window.addEventListener('submit', (ev) => { if (ev.isTrusted !== false) flush(); }, true);
@@ -850,7 +884,7 @@ RECORDER_JS = r"""(() => {
850
884
  const e = deep(ev);
851
885
  if (e.tagName === 'SELECT') { flush(); send({ kind: 'select', ...describeEl(e), text: shown(e), ...(e.multiple ? { options: [...e.selectedOptions].slice(0, 50).map((o) => norm(o.text)) } : {}) }); return; }
852
886
  // The files' paths are read by ForgeQE through the DevTools protocol: the page itself only sees their names.
853
- if (e.tagName === 'INPUT' && (e.getAttribute('type') || '').toLowerCase() === 'file') { send({ kind: 'upload', ...describeEl(e), count: e.files ? e.files.length : 0 }); return; }
887
+ if (e.tagName === 'INPUT' && inType(e) === 'file') { send({ kind: 'upload', ...describeEl(e), count: e.files ? e.files.length : 0 }); return; }
854
888
  if (dirty === e) flush();
855
889
  }
856
890
  window.addEventListener('change', onChange, true);
@@ -1018,7 +1052,7 @@ RECORDER_JS = r"""(() => {
1018
1052
  if (e === p.src) break;
1019
1053
  }
1020
1054
  const role = roleOf(p.src);
1021
- return ['listitem', 'option', 'row', 'treeitem', 'slider', 'img'].includes(role) || /^(LI|TR|IMG|CANVAS)$/.test(p.src.tagName) || (p.src.tagName === 'INPUT' && (p.src.getAttribute('type') || '').toLowerCase() === 'range');
1055
+ return ['listitem', 'option', 'row', 'treeitem', 'slider', 'img'].includes(role) || /^(LI|TR|IMG|CANVAS)$/.test(p.src.tagName) || (p.src.tagName === 'INPUT' && inType(p.src) === 'range');
1022
1056
  };
1023
1057
  window.addEventListener('pointermove', (ev) => {
1024
1058
  if (press && !press.moved && ev.isTrusted && (ev.buttons & 1) && Math.hypot(ev.clientX - press.x, ev.clientY - press.y) >= DRAG_MIN) press.moved = true;
@@ -1071,14 +1105,52 @@ RECORDER_JS = r"""(() => {
1071
1105
  const WIDGET_ROLES = new Set(['combobox', 'listbox', 'option', 'menu', 'menubar', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'slider', 'spinbutton', 'tab', 'tablist', 'tree', 'treeitem', 'grid', 'gridcell', 'treegrid', 'radiogroup', 'application']);
1072
1106
  const WIDGET_KEYS = new Set(['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Space', 'Enter', 'Escape', 'Tab']);
1073
1107
  // A native slider too (its keys change it, as dragging does); never a native select list, whose choice is a step.
1074
- const keyWidget = (e) => !!e && e.nodeType === 1 && (WIDGET_ROLES.has(e.getAttribute('role')) || e.tagName === 'CANVAS' || (e.tagName === 'INPUT' && (e.getAttribute('type') || '').toLowerCase() === 'range'));
1108
+ const keyWidget = (e) => !!e && e.nodeType === 1 && (WIDGET_ROLES.has(e.getAttribute('role')) || e.tagName === 'CANVAS' || (e.tagName === 'INPUT' && inType(e) === 'range'));
1075
1109
  // What the browser itself clicks on Enter (that click is recorded): a link, a button, a summary.
1076
1110
  const clicksOnEnter = (e) => {
1077
1111
  if (!e || e.nodeType !== 1 || keyWidget(e)) return false;
1078
1112
  if (e.tagName === 'A') return e.hasAttribute('href');
1079
- if (e.tagName === 'INPUT') return /^(submit|button|reset|image)$/i.test(e.getAttribute('type') || '');
1113
+ if (e.tagName === 'INPUT') return /^(submit|button|reset|image)$/.test(inType(e));
1080
1114
  return e.tagName === 'BUTTON' || e.tagName === 'SUMMARY' || actionable(e);
1081
1115
  };
1116
+ // ---- Tab: a step only when it does something on the page. Moving on to the next field needs none (the next step
1117
+ // names its field), but a Tab that accepts a suggestion, or leaves a field that is checked as the focus leaves it (a
1118
+ // message shows, the field is marked invalid), is part of the test: a check after it fails if the replay never left
1119
+ // the field. Within TAB_MS of the key: the field's text changed, text came or went near it, or one of TAB_ATTRS
1120
+ // changed there. Only the person's key is watched; what the page changed decides only whether that key is kept.
1121
+ const TAB_MS = 600;
1122
+ const TAB_ATTRS = ['aria-invalid', 'aria-expanded', 'aria-hidden', 'hidden', 'disabled'];
1123
+ const tabScope = (e) => {
1124
+ const f = e.closest && e.closest('form, fieldset, [role=form], [role=dialog]');
1125
+ if (f) return f;
1126
+ let c = e;
1127
+ for (let i = 0; i < 4 && c.parentElement && c.parentElement !== document.body; i++) c = c.parentElement;
1128
+ return c;
1129
+ };
1130
+ const tabDid = (recs, scope) => recs.some((r) => {
1131
+ const n = r.target.nodeType === 1 ? r.target : r.target.parentElement;
1132
+ if (!n || n === host || host.contains(n) || !scope.contains(n)) return false;
1133
+ if (r.type === 'attributes') return true;
1134
+ if (r.type === 'characterData') return norm(r.target.data) !== norm(r.oldValue);
1135
+ return [...r.addedNodes, ...r.removedNodes].some((x) => x !== host && !!norm(x.textContent));
1136
+ });
1137
+ settleTab = () => {
1138
+ const w = tabWatch;
1139
+ if (!w) return;
1140
+ tabWatch = null;
1141
+ clearTimeout(w.timer);
1142
+ const recs = w.recs.concat(w.obs.takeRecords());
1143
+ w.obs.disconnect();
1144
+ if ((w.text !== null && fieldText(w.e) !== w.text) || tabDid(recs, w.scope)) post({ kind: 'press', keys: w.keys, in_field: w.inField, autocomplete: w.auto, effect: true });
1145
+ };
1146
+ const watchTab = (e, keys, inField) => {
1147
+ settleTab();
1148
+ const w = { e, keys, inField, auto: autocomplete(e), text: inField ? fieldText(e) : null, scope: tabScope(e), recs: [] };
1149
+ w.obs = new MutationObserver((rs) => { w.recs.push(...rs); });
1150
+ w.obs.observe(document.documentElement, { subtree: true, childList: true, characterData: true, characterDataOldValue: true, attributes: true, attributeFilter: TAB_ATTRS });
1151
+ w.timer = setTimeout(settleTab, TAB_MS);
1152
+ tabWatch = w;
1153
+ };
1082
1154
  let leader = 0;
1083
1155
  const L = CFG.leader;
1084
1156
  const isLeader = (ev) => ev.code === L.code && !!ev.ctrlKey === !!L.ctrl && !!ev.shiftKey === !!L.shift && !!ev.altKey === !!L.alt && !!ev.metaKey === !!L.meta;
@@ -1120,8 +1192,13 @@ RECORDER_JS = r"""(() => {
1120
1192
  const mods = [ev.ctrlKey && 'Control', ev.altKey && 'Alt', ev.metaKey && 'Meta', ev.shiftKey && ev.key.length > 1 && 'Shift'].filter(Boolean);
1121
1193
  const typed = widget && !mods.length && ev.key.length === 1 && ev.key !== ' ';
1122
1194
  const key = ev.key === ' ' ? 'Space' : typed ? ev.key : ev.key.length === 1 ? ev.key.toLowerCase() : ev.key;
1123
- if (inField && !mods.length && ['Tab'].includes(key)) return;
1124
1195
  const chord = [...mods, key].join('+');
1196
+ // Tab or Shift+Tab (a widget takes Tab as its own key): kept only when it does something (watchTab).
1197
+ if (key === 'Tab' && !widget && !mods.some((m) => m !== 'Shift')) {
1198
+ if (e && dirty && dirty !== e) flush();
1199
+ if (e) watchTab(e, chord, inField);
1200
+ return;
1201
+ }
1125
1202
  if (inField && !mods.length && !['Enter', 'Escape', 'ArrowDown', 'ArrowUp'].includes(key)) return;
1126
1203
  if (inField && mods.length && ['Control', 'Meta'].some((m) => mods.includes(m)) && 'acvxzy'.includes(key)) return;
1127
1204
  if (!inField && !mods.length && !['Enter', 'Escape'].includes(key) && !(widget && (WIDGET_KEYS.has(key) || typed))) return;