@capagents/forgeqe 2.9.2 → 2.9.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 (117) hide show
  1. package/HOW_TO_USE.md +72 -11
  2. package/README.md +1 -1
  3. package/dist/docs-site/docs/architecture/index.html +6 -0
  4. package/dist/docs-site/docs/index.html +59 -2
  5. package/dist/docs-site/docs/search.js +1 -1
  6. package/dist/docs-site/docs/web-app/index.html +12 -1
  7. package/dist/forgeqe.js +1752 -1681
  8. package/dist/web/assets/Agent-djRg2i0o.js +7 -0
  9. package/dist/web/assets/ApiTests-Becz5PP-.js +10 -0
  10. package/dist/web/assets/Browse-_TcGuZ8l.js +2 -0
  11. package/dist/web/assets/Chat-VERzcB2r.js +3 -0
  12. package/dist/web/assets/CommandPalette-5QEcqEYi.js +1 -0
  13. package/dist/web/assets/{Compare-CGcGp9qD.js → Compare-Dl4z18KO.js} +1 -1
  14. package/dist/web/assets/Cost-B_i8IzAR.js +1 -0
  15. package/dist/web/assets/Data-DKSQEWFO.js +6 -0
  16. package/dist/web/assets/Desktop-DkNohPJ7.js +1 -0
  17. package/dist/web/assets/DesktopReview-BUgkvk9D.js +1 -0
  18. package/dist/web/assets/Evidence-Bmr0i0nA.js +1 -0
  19. package/dist/web/assets/{Explore-2M7wI0Sf.js → Explore-oz_P_CL1.js} +2 -2
  20. package/dist/web/assets/{Features-DmQ5JiMI.js → Features-CxcjdJkb.js} +1 -1
  21. package/dist/web/assets/{Flags-Bg-l5HxL.js → Flags-DF0H61Vl.js} +2 -2
  22. package/dist/web/assets/{Flaky-DJlkxmHT.js → Flaky-DkjqrHrF.js} +1 -1
  23. package/dist/web/assets/{ForceGraph-B5i3Ewd5.js → ForceGraph-i1zlas5l.js} +1 -1
  24. package/dist/web/assets/Impact-DiTAOm8k.js +3 -0
  25. package/dist/web/assets/Jobs-DR_mV4Mu.js +5 -0
  26. package/dist/web/assets/KindPage-CLRfAada.js +6 -0
  27. package/dist/web/assets/Migration-DQgCEr0G.js +2 -0
  28. package/dist/web/assets/{Product-BHqJVCMn.js → Product-165KSr60.js} +3 -3
  29. package/dist/web/assets/{Production-GL8lbwxD.js → Production-DoF4CcF-.js} +1 -1
  30. package/dist/web/assets/{Quality-jI3YgvqZ.js → Quality-CEVce0Rs.js} +1 -1
  31. package/dist/web/assets/{Readiness-B3OZ51FG.js → Readiness-DcnpsaAD.js} +1 -1
  32. package/dist/web/assets/Record-B7hLtTK5.js +2 -0
  33. package/dist/web/assets/Regression-BMftRz5h.js +5 -0
  34. package/dist/web/assets/{Reports-BAat71wo.js → Reports-sL20ZyMf.js} +2 -2
  35. package/dist/web/assets/{Response-DjqmewrL.js → Response-C2roHnWk.js} +2 -2
  36. package/dist/web/assets/{RunDiff-BbBom2fJ.js → RunDiff-C0AZaAAA.js} +1 -1
  37. package/dist/web/assets/{Runs-CIQWWRl3.js → Runs-CIgHrNZ7.js} +2 -2
  38. package/dist/web/assets/Steps-GPPeoUP-.js +2 -0
  39. package/dist/web/assets/{TestCases-8BBW6RSi.js → TestCases-xpJiurmK.js} +1 -1
  40. package/dist/web/assets/TestData-D07oKCRW.js +2 -0
  41. package/dist/web/assets/TestDebt-BaXdxqnZ.js +1 -0
  42. package/dist/web/assets/Tosca-BfIh2vCw.js +3 -0
  43. package/dist/web/assets/{WhatsNew-CBS7kmGu.js → WhatsNew-rQKGxI3X.js} +1 -1
  44. package/dist/web/assets/{dataParts-B3Fz4S59.js → dataParts-D9LZxYD6.js} +3 -3
  45. package/dist/web/assets/{families-BiqSaqoO.js → families-DlfXDoO8.js} +1 -1
  46. package/dist/web/assets/filters-NVjc0d8i.js +1 -0
  47. package/dist/web/assets/{fold-b2g0_ndv.js → fold-D1JElpyx.js} +1 -1
  48. package/dist/web/assets/frame-CgFXIaLn.js +4 -0
  49. package/dist/web/assets/index-BoLw7yMm.js +73 -0
  50. package/dist/web/assets/index-RzPHjTCW.css +2 -0
  51. package/dist/web/assets/{logos-DSveGjIW.js → logos-BGd4nsug.js} +1 -1
  52. package/dist/web/assets/{palette-CF8GLAVN.js → palette-BWPcuOsU.js} +1 -1
  53. package/dist/web/assets/{parts-D7OvxdrL.js → parts-W2J4TR3o.js} +1 -1
  54. package/dist/web/assets/{productParts-BDM3LIjp.js → productParts-_8gKGn4o.js} +1 -1
  55. package/dist/web/assets/{qualityParts-DP09bVel.js → qualityParts-9olnn4fj.js} +1 -1
  56. package/dist/web/assets/recordTest-etYNiLQy.js +1 -0
  57. package/dist/web/assets/{rows-B0vZ5x5N.js → rows-BWeaaykT.js} +1 -1
  58. package/dist/web/assets/{segmented-BfWimTC0.js → segmented-B7n6eLrO.js} +1 -1
  59. package/dist/web/assets/{thread-DASfqw-f.js → thread-B8W__QtF.js} +1 -1
  60. package/dist/web/assets/{usePageChat-BLEUldCJ.js → usePageChat-DvfE62rZ.js} +1 -1
  61. package/dist/web/index.html +4 -4
  62. package/docs/ARCHITECTURE.md +5 -0
  63. package/docs/WEB_APP.md +17 -1
  64. package/docs/user-guide.html +59 -2
  65. package/forgeqe.example.yaml +3 -1
  66. package/package.json +1 -1
  67. package/prompts/README.md +1 -0
  68. package/prompts/brain.md +9 -0
  69. package/prompts/business-persona.md +62 -0
  70. package/py/forgeqe_desktop/agentdesktop_driver.py +69 -0
  71. package/py/forgeqe_desktop/boxes.py +32 -0
  72. package/py/forgeqe_desktop/handhooks.py +55 -5
  73. package/py/forgeqe_desktop/pywinauto_driver.py +25 -0
  74. package/py/forgeqe_desktop/service.py +85 -3
  75. package/py/forgeqe_engine/brand.py +3 -0
  76. package/py/forgeqe_engine/browser.py +46 -6
  77. package/py/forgeqe_engine/cli.py +10 -1
  78. package/py/forgeqe_engine/recordsession.py +92 -2
  79. package/py/forgeqe_engine/video.py +423 -0
  80. package/py/forgeqe_mobile/hyperexecute.py +1 -1
  81. package/py/forgeqe_mobile/maestro.py +1 -1
  82. package/py/forgeqe_tosca/vendored.py +3 -2
  83. package/skills/bdd-gherkin/SKILL.md +141 -0
  84. package/skills/bdd-gherkin/references/cucumber-js.md +52 -0
  85. package/skills/bdd-gherkin/references/cucumber-jvm.md +54 -0
  86. package/skills/bdd-gherkin/references/python-bdd.md +50 -0
  87. package/skills/bdd-gherkin/references/reqnroll-specflow.md +83 -0
  88. package/skills/bdd-gherkin/references/review-checklist.md +37 -0
  89. package/skills/bdd-scenario-design/SKILL.md +50 -0
  90. package/skills/dynamics-365/SKILL.md +30 -15
  91. package/skills/dynamics-365-automation/SKILL.md +72 -0
  92. package/skills/dynamics-365-automation/references/elements.md +187 -0
  93. package/skills/dynamics-365-automation/references/recipes.md +97 -0
  94. package/dist/web/assets/Agent-BFwkMMHm.js +0 -4
  95. package/dist/web/assets/ApiTests-Bgt4R_yB.js +0 -10
  96. package/dist/web/assets/Browse-B3YI1MeV.js +0 -2
  97. package/dist/web/assets/Chat-K3kp-ji2.js +0 -3
  98. package/dist/web/assets/CommandPalette-nmLCmEsp.js +0 -1
  99. package/dist/web/assets/Cost-BvCShgln.js +0 -1
  100. package/dist/web/assets/Data-3EEe7vIz.js +0 -6
  101. package/dist/web/assets/Desktop-Drj-7jBV.js +0 -1
  102. package/dist/web/assets/Evidence-D1HiXQK6.js +0 -1
  103. package/dist/web/assets/Impact-huKs-mOc.js +0 -3
  104. package/dist/web/assets/Jobs-BwK79TQ8.js +0 -5
  105. package/dist/web/assets/KindPage-C0MoC9da.js +0 -6
  106. package/dist/web/assets/Migration-CTVyQeqW.js +0 -2
  107. package/dist/web/assets/Record-Yw-SGwQ9.js +0 -2
  108. package/dist/web/assets/Regression-v2dpbgs4.js +0 -5
  109. package/dist/web/assets/Steps-DfNHCe8N.js +0 -2
  110. package/dist/web/assets/TestData-BFkACDve.js +0 -2
  111. package/dist/web/assets/TestDebt-CUcklHEN.js +0 -1
  112. package/dist/web/assets/Tosca-DTWwUJBW.js +0 -3
  113. package/dist/web/assets/desktopAppPath-CMac6aJ0.js +0 -1
  114. package/dist/web/assets/filters-B4VDnWbr.js +0 -1
  115. package/dist/web/assets/frame-D-hqu7Oi.js +0 -4
  116. package/dist/web/assets/index-CtX74khE.js +0 -45
  117. package/dist/web/assets/index-DUf5ddb0.css +0 -2
@@ -13,7 +13,7 @@ reply from the browser would wait forever. One worker takes the queue in order a
13
13
 
14
14
  Request (stdin line 1): ``start_url``, ``out_dir``, ``name``, ``logins``, ``signed_in`` (start with the saved
15
15
  sessions), ``llm`` (for checks described in words; optional), ``leader`` ({code, ctrl, shift, alt, meta}),
16
- ``max_seconds``, ``case`` (a test case being recorded: {id, title, steps: [{action, expected}]}). Later stdin lines are commands, as the Recorder panel sends them ({"cmd": "stop"}, "chat", "undo"...).
16
+ ``max_seconds``, ``video`` (true: video.mp4 of the tab being recorded, paused with the recording), ``case`` (a test case being recorded: {id, title, steps: [{action, expected}]}). Later stdin lines are commands, as the Recorder panel sends them ({"cmd": "stop"}, "chat", "undo"...).
17
17
  Events: ``log``, ``steps`` (the whole list, after each change), ``call`` (one model call's time and tokens), ``done``.
18
18
  """
19
19
  from __future__ import annotations
@@ -35,6 +35,11 @@ from . import dynamic
35
35
  from .webrecord import Target, WebRecorder, auto_name, describe, upload_path
36
36
  from .webrecord_page import recorder_js
37
37
 
38
+
39
+ def _utc_now() -> str:
40
+ """Now, as an ISO time in UTC with a Z."""
41
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
42
+
38
43
  logger = logging.getLogger("forgeqe_engine.record")
39
44
 
40
45
  Emit = Callable[[Dict[str, Any]], None]
@@ -44,6 +49,8 @@ CDP_TIMEOUT = 5.0
44
49
  SHOT_SETTLE = 0.7
45
50
  MAX_SHOTS = 400
46
51
  SHOT_QUALITY = 55
52
+ # The tester's tab as a video (browser.video): the page's own screencast, on the recorder's connection (video.py).
53
+ VIDEO_SCREENCAST = {"format": "jpeg", "quality": 60, "maxWidth": 1920, "maxHeight": 1200, "everyNthFrame": 1}
47
54
 
48
55
  # What the page shows after a step, for the review to suggest checks from and to pick an element on the screenshot:
49
56
  # the address and title, the visible text (a leaf's own words, with its box) and the fields with their values, in the
@@ -116,6 +123,8 @@ class RecordSession:
116
123
  self.pages: Dict[str, Dict[str, Any]] = {}
117
124
  self.active: Optional[str] = None
118
125
  self.stop_reason = ""
126
+ # When the tester started and stopped, for how long the recording took (the Record page's Duration).
127
+ self.started_at = ""
119
128
  self.paused = False
120
129
  self.note_next = False
121
130
  # Where the tester put the panel, and whether they made it small: kept across pages.
@@ -139,6 +148,9 @@ class RecordSession:
139
148
  # The page's own API calls after each step (method, path, status), for checks of them in the review.
140
149
  self.calls: Dict[int, List[Dict[str, Any]]] = {}
141
150
  self._requests: Dict[str, str] = {}
151
+ # video.mp4 of the tab being recorded (payload ``video``), following the tester from tab to tab; paused with them.
152
+ self.video: Any = None
153
+ self._video_sid: Optional[str] = None
142
154
 
143
155
  # -- the browser ----------------------------------------------------------------------------------------------
144
156
 
@@ -219,6 +231,7 @@ class RecordSession:
219
231
  await self.send("Page.navigate", {"url": self.start_url}, main)
220
232
  # The start page's picture, once it has loaded.
221
233
  self._schedule_shot(2.0)
234
+ await self._start_video()
222
235
  # Where ForgeQE reaches this browser (on this computer only), to play a block of steps first: never shown.
223
236
  if str(getattr(self.browser, "cdp_url", "") or "").startswith(("http://127.0.0.1:", "ws://127.0.0.1:", "http://localhost:", "ws://localhost:")):
224
237
  self.emit({"type": "browser", "cdp": self.browser.cdp_url})
@@ -226,6 +239,7 @@ class RecordSession:
226
239
  async def close(self) -> None:
227
240
  from .browser import _shutdown_browser_instance
228
241
 
242
+ await self._finish_video()
229
243
  if self.client is not None:
230
244
  try:
231
245
  await self.client.stop()
@@ -236,6 +250,7 @@ class RecordSession:
236
250
  # -- the loop -------------------------------------------------------------------------------------------------
237
251
 
238
252
  async def run(self, max_seconds: float) -> None:
253
+ self.started_at = self.started_at or _utc_now()
239
254
  deadline = time.monotonic() + max_seconds
240
255
  while not self.stop_reason:
241
256
  left = deadline - time.monotonic()
@@ -303,6 +318,7 @@ class RecordSession:
303
318
  except Exception as ex:
304
319
  logger.warning("record: %s not handled: %s", kind, ex)
305
320
  logger.debug("record: details", exc_info=True)
321
+ await self._follow_video()
306
322
 
307
323
  def _response(self, event: Dict[str, Any], sid: Optional[str]) -> None:
308
324
  method = self._requests.pop(str(event.get("requestId") or ""), None)
@@ -634,6 +650,9 @@ class RecordSession:
634
650
  if cmd == "pause":
635
651
  self.paused = not self.paused
636
652
  rec.paused = self.paused
653
+ # Paused, nothing is recorded: the video too (the time paused is not in it).
654
+ if self.video is not None:
655
+ self.video.hold(self.paused)
637
656
  msg = "paused: what you do now is not recorded" if self.paused else "recording again"
638
657
  elif cmd == "undo":
639
658
  msg = rec.undo()
@@ -907,6 +926,73 @@ class RecordSession:
907
926
  self.shot_at[len(rec.steps) - 1] = name
908
927
  return name
909
928
 
929
+ # -- the video -------------------------------------------------------------------------------------------------------
930
+
931
+ async def _start_video(self) -> None:
932
+ if self.payload.get("video") is not True or self.client is None:
933
+ return
934
+ from .video import VIDEO_FILE, FrameVideo
935
+
936
+ video = FrameVideo(self.out_dir / VIDEO_FILE)
937
+ if not video.start():
938
+ self.log(f"No video of this recording: {video.error}", "warn")
939
+ return
940
+ self.video = video
941
+ self.client.register.Page.screencastFrame(self._on_frame)
942
+ await self._follow_video()
943
+
944
+ def _on_frame(self, event: Any, session_id: Optional[str] = None) -> None:
945
+ """A picture of the screencast: kept for the video, and acknowledged (later, never awaited here) so more come."""
946
+ ack = event.get("sessionId") if isinstance(event, dict) else None
947
+ if ack is not None and session_id:
948
+ try:
949
+ asyncio.ensure_future(self.send("Page.screencastFrameAck", {"sessionId": ack}, session_id))
950
+ except RuntimeError:
951
+ pass
952
+ video = self.video
953
+ if video is None or session_id != self._video_sid or self.paused:
954
+ return
955
+ data = event.get("data") if isinstance(event, dict) else None
956
+ if isinstance(data, str):
957
+ import base64
958
+
959
+ try:
960
+ video.frame(base64.b64decode(data, validate=True))
961
+ except ValueError:
962
+ pass
963
+
964
+ async def _follow_video(self) -> None:
965
+ """The video shows the tab the tester is on: the screencast moves when they move."""
966
+ if self.video is None or self.active == self._video_sid:
967
+ return
968
+ old, self._video_sid = self._video_sid, self.active
969
+ if old and old in self.pages:
970
+ try:
971
+ await self.send("Page.stopScreencast", {}, old)
972
+ except Exception:
973
+ pass
974
+ if self.active:
975
+ try:
976
+ await self.send("Page.startScreencast", dict(VIDEO_SCREENCAST), self.active)
977
+ except Exception as ex:
978
+ logger.debug("record: no screencast of the page: %s", ex)
979
+
980
+ async def _finish_video(self) -> Optional[str]:
981
+ video, self.video = self.video, None
982
+ if video is None:
983
+ return None
984
+ sid, self._video_sid = self._video_sid, None
985
+ if sid and sid in self.pages:
986
+ try:
987
+ await self.send("Page.stopScreencast", {}, sid)
988
+ except Exception:
989
+ pass
990
+ path = await asyncio.get_running_loop().run_in_executor(None, video.close)
991
+ if path is None:
992
+ self.log(f"No video of this recording: {video.error or 'nothing was shown'}", "warn")
993
+ return None
994
+ return str(path.resolve())
995
+
910
996
  # -- the run folder -------------------------------------------------------------------------------------------------
911
997
 
912
998
  async def finish(self) -> Dict[str, Any]:
@@ -916,6 +1002,7 @@ class RecordSession:
916
1002
  rec = self.rec
917
1003
  assert rec is not None
918
1004
  self.out_dir.mkdir(parents=True, exist_ok=True)
1005
+ video = await self._finish_video()
919
1006
  # The recorder's own working fields (an element's facts) stay out of the run.
920
1007
  steps = [
921
1008
  {**{k: v for k, v in s.items() if not k.startswith("_")}, **({"shot": self.shot_at[i]} if i in self.shot_at else {}), **({"calls": self.calls[i]} if self.calls.get(i) else {})}
@@ -949,6 +1036,7 @@ class RecordSession:
949
1036
  "usage": dict(self.usage),
950
1037
  "outcome": "passed" if ok else "error",
951
1038
  "browser": profile,
1039
+ **({"started_at": self.started_at, "ended_at": _utc_now()} if self.started_at else {}),
952
1040
  "recording": {
953
1041
  "stopped": self.stop_reason,
954
1042
  "checks": rec.checks,
@@ -963,7 +1051,9 @@ class RecordSession:
963
1051
  }
964
1052
  if not ok:
965
1053
  run["error"] = summary
966
- files = [str((self.out_dir / "run.json").resolve()), *([yaml_path] if yaml_path else []), str((self.out_dir / "trace.md").resolve())]
1054
+ files = [str((self.out_dir / "run.json").resolve()), *([yaml_path] if yaml_path else []), str((self.out_dir / "trace.md").resolve()), *([video] if video else [])]
1055
+ if video:
1056
+ run["video"] = Path(video).name
967
1057
  run["files"] = files
968
1058
  (self.out_dir / "run.json").write_text(json.dumps(run, indent=2, ensure_ascii=False, default=str), encoding="utf-8")
969
1059
  return run
@@ -0,0 +1,423 @@
1
+ """
2
+ Videos of what ForgeQE drives where browser-use's recorder (``start_video`` in browser.py) does not reach: a recording
3
+ by hand (the tester's tab, over the recorder's own DevTools connection), a replay (the frames Playwright's runner kept),
4
+ and a desktop run (the screen).
5
+
6
+ Every video is ``video.mp4`` (H.264), made by the ffmpeg that the pinned ``imageio-ffmpeg`` package ships inside
7
+ itself: found in the package's own ``binaries`` folder, never on PATH and never through ``IMAGEIO_FFMPEG_EXE``, started
8
+ with an argument list and system settings only. Frames reach it on stdin as raw RGB pixels of a fixed size, so nothing
9
+ a page or an app shows ever reaches its command line. A video runs in real time at ``FPS`` frames a second (the
10
+ latest picture is repeated while nothing changes), stops growing after ``MAX_SECONDS``, and a video that could not be
11
+ finished is removed rather than kept half written.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import io
16
+ import json
17
+ import os
18
+ import re
19
+ import subprocess
20
+ import sys
21
+ import threading
22
+ import time
23
+ from pathlib import Path
24
+ from typing import Any, Callable, Dict, List, Optional, Tuple
25
+
26
+ VIDEO_FILE = "video.mp4"
27
+ FPS = 5
28
+ MAX_SECONDS = 3600
29
+ # Pictures are made smaller to fit, never larger: a 4K screen is a 1920-wide video.
30
+ MAX_WIDTH = 1920
31
+ MAX_HEIGHT = 1200
32
+ FINISH_SECONDS = 120.0
33
+ # A replay's frames: <ms since the start>.jpg, written by its runner (src/code/replay.ts).
34
+ FRAME_NAME = re.compile(r"^(\d{1,9})\.jpg$")
35
+ MAX_FRAMES = 20000
36
+ MAX_FRAME_BYTES = 8 * 1024 * 1024
37
+ _ENV_KEEP = ("SYSTEMROOT", "WINDIR", "TMP", "TEMP", "TMPDIR", "LANG", "LC_ALL")
38
+
39
+
40
+ def ffmpeg_exe() -> Optional[str]:
41
+ """The ffmpeg inside the imageio-ffmpeg package, or None when the package (or its binary) is not there."""
42
+ try:
43
+ import imageio_ffmpeg
44
+ except Exception:
45
+ return None
46
+ folder = Path(imageio_ffmpeg.__file__).resolve().parent / "binaries"
47
+ try:
48
+ found = sorted(p for p in folder.iterdir() if p.name.startswith("ffmpeg-") and p.is_file() and not p.is_symlink())
49
+ except OSError:
50
+ return None
51
+ for exe in found:
52
+ if sys.platform == "win32" and exe.suffix.lower() != ".exe":
53
+ continue
54
+ if sys.platform == "win32" or os.access(exe, os.X_OK):
55
+ return str(exe)
56
+ return None
57
+
58
+
59
+ def video_ready() -> bool:
60
+ try:
61
+ import PIL # noqa: F401
62
+ except Exception:
63
+ return False
64
+ return ffmpeg_exe() is not None
65
+
66
+
67
+ def _even(n: int) -> int:
68
+ return max(2, n - (n % 2))
69
+
70
+
71
+ def fit_size(width: int, height: int, max_width: int = MAX_WIDTH, max_height: int = MAX_HEIGHT) -> Tuple[int, int]:
72
+ """The video's size for pictures of this size: as large, or smaller to fit, and even on both sides (H.264 wants it)."""
73
+ width, height = max(2, int(width)), max(2, int(height))
74
+ scale = min(1.0, max_width / width, max_height / height)
75
+ return _even(round(width * scale)), _even(round(height * scale))
76
+
77
+
78
+ def ffmpeg_args(exe: str, size: Tuple[int, int], fps: int, out: Path) -> List[str]:
79
+ w, h = size
80
+ return [
81
+ exe, "-hide_banner", "-loglevel", "error", "-y",
82
+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w}x{h}", "-r", str(fps), "-i", "-",
83
+ "-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p", "-movflags", "+faststart",
84
+ str(out),
85
+ ]
86
+
87
+
88
+ def _child_env() -> Dict[str, str]:
89
+ """System settings only: ffmpeg needs nothing of ForgeQE's."""
90
+ keep = {k.upper() for k in _ENV_KEEP} if sys.platform == "win32" else set(_ENV_KEEP)
91
+ return {k: v for k, v in os.environ.items() if (k.upper() if sys.platform == "win32" else k) in keep}
92
+
93
+
94
+ def _picture(data: Any) -> Any:
95
+ """A PIL image in RGB from an image or the bytes of a JPEG or PNG; None when it is neither."""
96
+ from PIL import Image
97
+
98
+ try:
99
+ if isinstance(data, Image.Image):
100
+ img = data
101
+ else:
102
+ if not isinstance(data, (bytes, bytearray)) or len(data) > MAX_FRAME_BYTES:
103
+ return None
104
+ img = Image.open(io.BytesIO(bytes(data)))
105
+ img.load()
106
+ return img.convert("RGB") if img.mode != "RGB" else img
107
+ except Exception:
108
+ return None
109
+
110
+
111
+ def _letterbox(img: Any, size: Tuple[int, int]) -> bytes:
112
+ """The picture fitted into the video's size, centred on black: raw RGB pixels."""
113
+ from PIL import Image
114
+
115
+ if img.size == size:
116
+ return img.tobytes()
117
+ scale = min(size[0] / img.width, size[1] / img.height)
118
+ w, h = max(1, round(img.width * scale)), max(1, round(img.height * scale))
119
+ canvas = Image.new("RGB", size, (0, 0, 0))
120
+ canvas.paste(img.resize((w, h), Image.Resampling.BILINEAR), ((size[0] - w) // 2, (size[1] - h) // 2))
121
+ return canvas.tobytes()
122
+
123
+
124
+ class FrameVideo:
125
+ """
126
+ A video made as it happens: ``frame`` gives the latest picture (an image, or JPEG or PNG bytes), a thread writes the
127
+ latest one ``fps`` times a second. ffmpeg starts with the first picture, whose size the video takes. ``hold(True)``
128
+ pauses it (nothing is written, and the time held is not in the video); ``close`` finishes the file.
129
+ """
130
+
131
+ def __init__(self, out: Path, *, fps: int = FPS, max_seconds: float = MAX_SECONDS, exe: Optional[str] = None, clock: Callable[[], float] = time.monotonic) -> None:
132
+ self.out = Path(out)
133
+ self.fps = max(1, int(fps))
134
+ self.max_frames = int(max_seconds * self.fps)
135
+ self.exe = exe
136
+ self.clock = clock
137
+ self.size: Optional[Tuple[int, int]] = None
138
+ self.written = 0
139
+ self.error = ""
140
+ self._latest: Any = None
141
+ self._fresh = False
142
+ self._pixels: Optional[bytes] = None
143
+ self._held = False
144
+ self._lock = threading.Lock()
145
+ self._stop = threading.Event()
146
+ self._proc: Optional[subprocess.Popen] = None
147
+ self._thread: Optional[threading.Thread] = None
148
+ self._t0 = 0.0
149
+ self._due_base = 0
150
+
151
+ def start(self) -> bool:
152
+ """Get ready; False (and ``error`` says why) when no video can be made here."""
153
+ self.exe = self.exe or ffmpeg_exe()
154
+ if not self.exe:
155
+ self.error = "the engine's video packages are missing (run forgeqe setup)"
156
+ return False
157
+ try:
158
+ import PIL # noqa: F401
159
+ except Exception:
160
+ self.error = "Pillow is missing (run forgeqe setup)"
161
+ return False
162
+ self.out.parent.mkdir(parents=True, exist_ok=True)
163
+ self._thread = threading.Thread(target=self._run, name="forgeqe-video", daemon=True)
164
+ self._thread.start()
165
+ return True
166
+
167
+ def frame(self, data: Any) -> None:
168
+ """The picture shown now (decoded later, by the writer, at most ``fps`` times a second)."""
169
+ if self._stop.is_set():
170
+ return
171
+ with self._lock:
172
+ if self._held:
173
+ return
174
+ self._latest = data
175
+ self._fresh = True
176
+
177
+ def hold(self, held: bool) -> None:
178
+ with self._lock:
179
+ if held == self._held:
180
+ return
181
+ self._held = held
182
+ if not held:
183
+ # Carry on from where it stopped: the time held is not caught up with repeated pictures.
184
+ self._t0 = self.clock()
185
+ self._due_base = self.written
186
+ self._fresh = self._latest is not None
187
+
188
+ def _pixels_now(self) -> Optional[bytes]:
189
+ with self._lock:
190
+ data, fresh = self._latest, self._fresh
191
+ self._fresh = False
192
+ if fresh and data is not None:
193
+ img = _picture(data)
194
+ if img is not None:
195
+ if self.size is None:
196
+ self.size = fit_size(img.width, img.height)
197
+ self._pixels = _letterbox(img, self.size)
198
+ return self._pixels
199
+
200
+ def _open(self) -> bool:
201
+ assert self.exe and self.size
202
+ try:
203
+ self._proc = subprocess.Popen(
204
+ ffmpeg_args(self.exe, self.size, self.fps, self.out),
205
+ stdin=subprocess.PIPE,
206
+ stdout=subprocess.DEVNULL,
207
+ stderr=subprocess.DEVNULL,
208
+ env=_child_env(),
209
+ shell=False,
210
+ )
211
+ except OSError as ex:
212
+ self.error = f"ffmpeg did not start ({ex.__class__.__name__})"
213
+ return False
214
+ return True
215
+
216
+ def _write(self, pixels: bytes) -> bool:
217
+ try:
218
+ assert self._proc is not None and self._proc.stdin is not None
219
+ self._proc.stdin.write(pixels)
220
+ self.written += 1
221
+ return True
222
+ except (OSError, ValueError):
223
+ self.error = "ffmpeg stopped taking pictures"
224
+ return False
225
+
226
+ def _run(self) -> None:
227
+ step = 1.0 / self.fps
228
+ while not self._stop.is_set():
229
+ pixels = self._pixels_now()
230
+ if pixels is None:
231
+ self._stop.wait(step)
232
+ continue
233
+ if self._proc is None:
234
+ if not self._open():
235
+ return
236
+ with self._lock:
237
+ self._t0, self._due_base = self.clock(), 0
238
+ with self._lock:
239
+ held, t0, base = self._held, self._t0, self._due_base
240
+ if not held:
241
+ due = base + int((self.clock() - t0) * self.fps) + 1
242
+ # Real time: a picture that took long to come is shown for as long as it was there (at most 2 s caught up).
243
+ for _ in range(min(max(0, due - self.written), self.fps * 2)):
244
+ if self.written >= self.max_frames:
245
+ self._stop.set()
246
+ break
247
+ if not self._write(pixels):
248
+ return
249
+ self._stop.wait(step)
250
+
251
+ def close(self, timeout: float = FINISH_SECONDS) -> Optional[Path]:
252
+ """Finish the file: its path, or None (nothing removed is left behind) when no video was made."""
253
+ self._stop.set()
254
+ if self._thread is not None:
255
+ self._thread.join(timeout=10)
256
+ proc = self._proc
257
+ if proc is None:
258
+ return None
259
+ try:
260
+ if proc.stdin is not None:
261
+ proc.stdin.close()
262
+ except OSError:
263
+ pass
264
+ try:
265
+ proc.wait(timeout=timeout)
266
+ except subprocess.TimeoutExpired:
267
+ proc.kill()
268
+ proc.wait()
269
+ ok = proc.returncode == 0 and self.written > 0 and self.out.is_file() and self.out.stat().st_size > 0
270
+ if not ok:
271
+ self.error = self.error or f"ffmpeg ended with {proc.returncode}"
272
+ try:
273
+ self.out.unlink()
274
+ except OSError:
275
+ pass
276
+ return None
277
+ return self.out
278
+
279
+
280
+ def frames_in(folder: Path) -> List[Tuple[int, Path]]:
281
+ """A replay's frames, by their time: only ``<ms>.jpg`` regular files directly in the folder, at most MAX_FRAMES."""
282
+ out: List[Tuple[int, Path]] = []
283
+ try:
284
+ entries = list(os.scandir(folder))
285
+ except OSError:
286
+ return []
287
+ for e in entries:
288
+ m = FRAME_NAME.match(e.name)
289
+ if m and e.is_file(follow_symlinks=False):
290
+ out.append((int(m.group(1)), Path(e.path)))
291
+ out.sort()
292
+ return out[:MAX_FRAMES]
293
+
294
+
295
+ def encode_frames(folder: Path, out: Path, *, fps: int = FPS, max_seconds: float = MAX_SECONDS, exe: Optional[str] = None) -> Tuple[Optional[Path], str]:
296
+ """
297
+ A video of frames kept with their times (a replay's): each moment shows the latest frame taken by then. (path, "")
298
+ or (None, why not).
299
+ """
300
+ frames = frames_in(folder)
301
+ if not frames:
302
+ return None, "no frames were kept"
303
+ exe = exe or ffmpeg_exe()
304
+ if not exe:
305
+ return None, "the engine's video packages are missing (run forgeqe setup)"
306
+ first = _picture(frames[0][1].read_bytes()) if frames[0][1].stat().st_size <= MAX_FRAME_BYTES else None
307
+ if first is None:
308
+ return None, "the first frame is not a picture"
309
+ size = fit_size(first.width, first.height)
310
+ out = Path(out)
311
+ out.parent.mkdir(parents=True, exist_ok=True)
312
+ try:
313
+ proc = subprocess.Popen(ffmpeg_args(exe, size, fps, out), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=_child_env(), shell=False)
314
+ except OSError as ex:
315
+ return None, f"ffmpeg did not start ({ex.__class__.__name__})"
316
+ start = frames[0][0]
317
+ end = min(frames[-1][0] - start, int(max_seconds * 1000))
318
+ count = end * fps // 1000 + 1
319
+ i, pixels, ok = 0, _letterbox(first, size), True
320
+ assert proc.stdin is not None
321
+ try:
322
+ for n in range(count):
323
+ at = start + n * 1000 // fps
324
+ moved = False
325
+ while i + 1 < len(frames) and frames[i + 1][0] <= at:
326
+ i += 1
327
+ moved = True
328
+ if moved:
329
+ p = frames[i][1]
330
+ img = _picture(p.read_bytes()) if p.stat().st_size <= MAX_FRAME_BYTES else None
331
+ if img is not None:
332
+ pixels = _letterbox(img, size)
333
+ proc.stdin.write(pixels)
334
+ except (OSError, ValueError):
335
+ ok = False
336
+ try:
337
+ proc.stdin.close()
338
+ except OSError:
339
+ pass
340
+ try:
341
+ proc.wait(timeout=FINISH_SECONDS)
342
+ except subprocess.TimeoutExpired:
343
+ proc.kill()
344
+ proc.wait()
345
+ if not ok or proc.returncode != 0 or not out.is_file() or not out.stat().st_size:
346
+ try:
347
+ out.unlink()
348
+ except OSError:
349
+ pass
350
+ return None, f"ffmpeg ended with {proc.returncode}"
351
+ return out, ""
352
+
353
+
354
+ class ScreenVideo:
355
+ """
356
+ A video of this computer's screen (a desktop run): Pillow's ImageGrab, the main screen, taken ``fps`` times a
357
+ second on a thread of its own. ``start`` is False (``error`` says why) where the screen cannot be read, such as a
358
+ computer with no display, or macOS before Screen Recording is allowed for the app running ForgeQE.
359
+ """
360
+
361
+ def __init__(self, out: Path, *, fps: int = FPS, grab: Optional[Callable[[], Any]] = None, exe: Optional[str] = None) -> None:
362
+ self.video = FrameVideo(out, fps=fps, exe=exe)
363
+ self.fps = self.video.fps
364
+ self._grab = grab
365
+ self._stop = threading.Event()
366
+ self._thread: Optional[threading.Thread] = None
367
+ self.error = ""
368
+
369
+ def _take(self) -> Any:
370
+ if self._grab is not None:
371
+ return self._grab()
372
+ from PIL import ImageGrab
373
+
374
+ return ImageGrab.grab()
375
+
376
+ def start(self) -> bool:
377
+ try:
378
+ first = self._take()
379
+ except Exception as ex:
380
+ self.error = f"the screen cannot be read here ({ex.__class__.__name__})"
381
+ return False
382
+ if first is None:
383
+ self.error = "the screen cannot be read here"
384
+ return False
385
+ if not self.video.start():
386
+ self.error = self.video.error
387
+ return False
388
+ self.video.frame(first)
389
+ self._thread = threading.Thread(target=self._run, name="forgeqe-screen", daemon=True)
390
+ self._thread.start()
391
+ return True
392
+
393
+ def _run(self) -> None:
394
+ step = 1.0 / self.fps
395
+ while not self._stop.is_set():
396
+ started = time.monotonic()
397
+ try:
398
+ img = self._take()
399
+ except Exception:
400
+ img = None
401
+ if img is not None:
402
+ self.video.frame(img)
403
+ self._stop.wait(max(0.0, step - (time.monotonic() - started)))
404
+
405
+ def close(self) -> Optional[Path]:
406
+ self._stop.set()
407
+ if self._thread is not None:
408
+ self._thread.join(timeout=10)
409
+ path = self.video.close()
410
+ if path is None and not self.error:
411
+ self.error = self.video.error
412
+ return path
413
+
414
+
415
+ def main(args: List[str], out: Any) -> int:
416
+ """``python -m forgeqe_engine video <frames folder> <file.mp4>``: a replay's frames as a video (src/code/replay.ts)."""
417
+ if len(args) != 2 or not args[1].endswith(".mp4"):
418
+ result: Dict[str, Any] = {"success": False, "error": "usage: video <frames folder> <file.mp4>"}
419
+ else:
420
+ path, why = encode_frames(Path(args[0]), Path(args[1]))
421
+ result = {"success": True, "video": str(path)} if path else {"success": False, "error": why}
422
+ out.write(json.dumps({"type": "done", "result": result}) + "\n")
423
+ return 0 if result["success"] else 1
@@ -243,7 +243,7 @@ def run_hyperexecute(
243
243
  args = [settings["cli"], "--user", user, "--key", key, "--config", cfg.name, "--download-artifacts", "--download-artifacts-path", "artifacts", "--force-clean-artifacts"]
244
244
  child_env = {k: v for k, v in env.items() if k not in (settings["username_env"], settings["access_key_env"])}
245
245
  try:
246
- proc = run(args, cwd=str(project), env=child_env, capture_output=True, text=True, timeout=timeout, shell=False)
246
+ proc = run(args, cwd=str(project), env=child_env, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, shell=False)
247
247
  except FileNotFoundError:
248
248
  raise WorkflowError(f"the HyperExecute CLI is not at {settings['cli']}; download it from TestMu (hyperexecute) and set mobile.maestro.testmu.cli")
249
249
  except subprocess.TimeoutExpired:
@@ -358,7 +358,7 @@ def run_maestro(
358
358
  resolved = shutil.which(command[0]) or command[0]
359
359
  args = [resolved, *command[1:], *(["--device", device] if device else []), "test", "--format", "junit", "--output", str(junit), "--debug-output", str(debug), *flows]
360
360
  try:
361
- proc = run(args, env=dict(env), capture_output=True, text=True, timeout=timeout, shell=False)
361
+ proc = run(args, env=dict(env), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, shell=False)
362
362
  except FileNotFoundError:
363
363
  raise WorkflowError(f"Maestro is not installed or not on PATH ({command[0]}); see https://maestro.mobile.dev")
364
364
  except subprocess.TimeoutExpired:
@@ -41,9 +41,10 @@ def manifests(path: Path, test_attributes: Optional[List[str]] = None, skip_modu
41
41
  cfg["skip_modules"] = list(skip_modules)
42
42
  if cfg: # parse_tsu reads parse_tsu.config.json from its output folder (it wins over one next to the .tsu)
43
43
  (out / "parse_tsu.config.json").write_text(json.dumps(cfg), encoding="utf-8")
44
+ # -X utf8: -I ignores PYTHONUTF8, and on Windows the parser's progress marks (✓) would not fit the ANSI code page.
44
45
  r = subprocess.run(
45
- [sys.executable, "-I", str(PARSER), str(linked.resolve()), "--steps-json", "--out-dir", str(out)],
46
- capture_output=True, text=True, timeout=timeout, cwd=tmp, shell=False,
46
+ [sys.executable, "-I", "-X", "utf8", str(PARSER), str(linked.resolve()), "--steps-json", "--out-dir", str(out)],
47
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=tmp, shell=False,
47
48
  )
48
49
  if r.returncode != 0:
49
50
  last = (r.stderr or r.stdout or "").strip().splitlines()