@capagents/forgeqe 2.9.0 → 2.9.2

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 (127) hide show
  1. package/HOW_TO_USE.md +251 -23
  2. package/dist/docs-site/docs/desktop/index.html +45 -1
  3. package/dist/docs-site/docs/index.html +262 -5
  4. package/dist/docs-site/docs/search.js +1 -1
  5. package/dist/forgeqe.js +1687 -1633
  6. package/dist/web/assets/Agent-BFwkMMHm.js +4 -0
  7. package/dist/web/assets/ApiTests-Bgt4R_yB.js +10 -0
  8. package/dist/web/assets/Browse-B3YI1MeV.js +2 -0
  9. package/dist/web/assets/{Chat-BcFP0BbA.js → Chat-K3kp-ji2.js} +3 -3
  10. package/dist/web/assets/CommandPalette-nmLCmEsp.js +1 -0
  11. package/dist/web/assets/Compare-CGcGp9qD.js +1 -0
  12. package/dist/web/assets/Cost-BvCShgln.js +1 -0
  13. package/dist/web/assets/Data-3EEe7vIz.js +6 -0
  14. package/dist/web/assets/Desktop-Drj-7jBV.js +1 -0
  15. package/dist/web/assets/Evidence-D1HiXQK6.js +1 -0
  16. package/dist/web/assets/Explore-2M7wI0Sf.js +2 -0
  17. package/dist/web/assets/Features-DmQ5JiMI.js +1 -0
  18. package/dist/web/assets/{Flags-C_Qm0078.js → Flags-Bg-l5HxL.js} +2 -2
  19. package/dist/web/assets/Flaky-DJlkxmHT.js +1 -0
  20. package/dist/web/assets/ForceGraph-B5i3Ewd5.js +1 -0
  21. package/dist/web/assets/Impact-huKs-mOc.js +3 -0
  22. package/dist/web/assets/Jobs-BwK79TQ8.js +5 -0
  23. package/dist/web/assets/KindPage-C0MoC9da.js +6 -0
  24. package/dist/web/assets/Migration-CTVyQeqW.js +2 -0
  25. package/dist/web/assets/Product-BHqJVCMn.js +7 -0
  26. package/dist/web/assets/Production-GL8lbwxD.js +1 -0
  27. package/dist/web/assets/Quality-jI3YgvqZ.js +1 -0
  28. package/dist/web/assets/Readiness-B3OZ51FG.js +1 -0
  29. package/dist/web/assets/Record-Yw-SGwQ9.js +2 -0
  30. package/dist/web/assets/Regression-v2dpbgs4.js +5 -0
  31. package/dist/web/assets/Reports-BAat71wo.js +2 -0
  32. package/dist/web/assets/{Response-DGl2R0A-.js → Response-DjqmewrL.js} +2 -2
  33. package/dist/web/assets/RunDiff-BbBom2fJ.js +1 -0
  34. package/dist/web/assets/Runs-CIQWWRl3.js +2 -0
  35. package/dist/web/assets/Steps-DfNHCe8N.js +2 -0
  36. package/dist/web/assets/TestCases-8BBW6RSi.js +1 -0
  37. package/dist/web/assets/TestData-BFkACDve.js +2 -0
  38. package/dist/web/assets/TestDebt-CUcklHEN.js +1 -0
  39. package/dist/web/assets/Tosca-DTWwUJBW.js +3 -0
  40. package/dist/web/assets/WhatsNew-CBS7kmGu.js +1 -0
  41. package/dist/web/assets/dataParts-B3Fz4S59.js +3 -0
  42. package/dist/web/assets/desktopAppPath-CMac6aJ0.js +1 -0
  43. package/dist/web/assets/families-BiqSaqoO.js +1 -0
  44. package/dist/web/assets/filters-B4VDnWbr.js +1 -0
  45. package/dist/web/assets/fold-b2g0_ndv.js +1 -0
  46. package/dist/web/assets/frame-D-hqu7Oi.js +4 -0
  47. package/dist/web/assets/index-CtX74khE.js +45 -0
  48. package/dist/web/assets/index-DUf5ddb0.css +2 -0
  49. package/dist/web/assets/logos-DSveGjIW.js +1 -0
  50. package/dist/web/assets/palette-CF8GLAVN.js +1 -0
  51. package/dist/web/assets/parts-D7OvxdrL.js +1 -0
  52. package/dist/web/assets/productParts-BDM3LIjp.js +1 -0
  53. package/dist/web/assets/qualityParts-DP09bVel.js +1 -0
  54. package/dist/web/assets/rows-B0vZ5x5N.js +1 -0
  55. package/dist/web/assets/segmented-BfWimTC0.js +1 -0
  56. package/dist/web/assets/{thread-BeaLQ_f4.js → thread-DASfqw-f.js} +2 -2
  57. package/dist/web/assets/usePageChat-BLEUldCJ.js +1 -0
  58. package/dist/web/index.html +4 -3
  59. package/docs/DESKTOP.md +48 -1
  60. package/docs/user-guide.html +262 -5
  61. package/package.json +1 -1
  62. package/prompts/README.md +1 -0
  63. package/prompts/brain.md +4 -3
  64. package/prompts/impact-reader.md +8 -9
  65. package/prompts/tosca-assistant.md +47 -0
  66. package/prompts/tosca.md +3 -1
  67. package/py/forgeqe_desktop/agentdesktop_driver.py +57 -7
  68. package/py/forgeqe_desktop/handhooks.py +71 -22
  69. package/py/forgeqe_desktop/handrecord.py +7 -1
  70. package/py/forgeqe_desktop/heal.py +24 -2
  71. package/py/forgeqe_desktop/memory.py +54 -4
  72. package/py/forgeqe_desktop/pywinauto_driver.py +210 -12
  73. package/py/forgeqe_desktop/replay.py +10 -2
  74. package/py/forgeqe_desktop/service.py +9 -2
  75. package/py/forgeqe_desktop/ufo_runner.py +101 -1
  76. package/py/forgeqe_mobile/service.py +4 -1
  77. package/py/forgeqe_tosca/__init__.py +11 -1
  78. package/py/forgeqe_tosca/app.py +168 -0
  79. package/py/forgeqe_tosca/db.py +131 -0
  80. package/py/forgeqe_tosca/files.py +74 -0
  81. package/py/forgeqe_tosca/ntir.py +357 -5
  82. package/py/forgeqe_tosca/render.py +38 -0
  83. package/py/forgeqe_tosca/tsu.py +110 -0
  84. package/skills/tosca-knowledge/SKILL.md +14 -3
  85. package/skills/tosca-knowledge/references/api.md +54 -0
  86. package/dist/web/assets/Agent-BGwHbXbc.js +0 -4
  87. package/dist/web/assets/ApiTests-DSnZHRlF.js +0 -10
  88. package/dist/web/assets/Browse-Dx3pHGuG.js +0 -2
  89. package/dist/web/assets/CommandPalette-v6mqHZnU.js +0 -1
  90. package/dist/web/assets/Cost-C9LZdx1p.js +0 -1
  91. package/dist/web/assets/Data-DvbaOc9e.js +0 -6
  92. package/dist/web/assets/Evidence-Y1AeSzh5.js +0 -1
  93. package/dist/web/assets/Explore-Dw8S6DG1.js +0 -2
  94. package/dist/web/assets/Features-CjrVraBE.js +0 -1
  95. package/dist/web/assets/Flaky-DYgN586D.js +0 -1
  96. package/dist/web/assets/ForceGraph-CEH86-Z0.js +0 -1
  97. package/dist/web/assets/Impact-dBPp7aM2.js +0 -3
  98. package/dist/web/assets/Jobs-CSyN6YRx.js +0 -5
  99. package/dist/web/assets/KindPage-BQl-5bcd.js +0 -6
  100. package/dist/web/assets/Migration-COly7O-T.js +0 -2
  101. package/dist/web/assets/Product-7mM8tcxH.js +0 -7
  102. package/dist/web/assets/Production-De5CCUoP.js +0 -1
  103. package/dist/web/assets/Quality-Q_iqj3fk.js +0 -1
  104. package/dist/web/assets/Readiness-kU9kum_I.js +0 -1
  105. package/dist/web/assets/Record-CIhINuEz.js +0 -2
  106. package/dist/web/assets/Regression-CMQnH7dN.js +0 -5
  107. package/dist/web/assets/Reports-dUOe6_vN.js +0 -2
  108. package/dist/web/assets/RunDiff-BVRRIz3m.js +0 -1
  109. package/dist/web/assets/Runs-CkNWhAhe.js +0 -2
  110. package/dist/web/assets/TestCases-exR7hRWd.js +0 -1
  111. package/dist/web/assets/TestData-yVPMg9kw.js +0 -2
  112. package/dist/web/assets/TestDebt-C3sM6cH0.js +0 -1
  113. package/dist/web/assets/Tosca-Bcalg1JU.js +0 -2
  114. package/dist/web/assets/WhatsNew-EFSt6xx2.js +0 -1
  115. package/dist/web/assets/dataParts-D33u08WR.js +0 -3
  116. package/dist/web/assets/families-Btjss8bN.js +0 -1
  117. package/dist/web/assets/frame-D3IhgCFt.js +0 -4
  118. package/dist/web/assets/index-D5sya6FK.css +0 -2
  119. package/dist/web/assets/index-v-k_CVn7.js +0 -45
  120. package/dist/web/assets/logos-CfpaNwbY.js +0 -1
  121. package/dist/web/assets/palette-X7hU78Wy.js +0 -1
  122. package/dist/web/assets/parts-B7YrlR3a.js +0 -1
  123. package/dist/web/assets/productParts-CAxyMnWJ.js +0 -1
  124. package/dist/web/assets/qualityParts-CN9JVKZN.js +0 -1
  125. package/dist/web/assets/rows-IEP4Jvfi.js +0 -1
  126. package/dist/web/assets/segmented-DBqHvZW3.js +0 -1
  127. package/dist/web/assets/usePageChat-D_3KsqBU.js +0 -1
@@ -9,7 +9,7 @@ from __future__ import annotations
9
9
 
10
10
  import subprocess
11
11
  import time
12
- from typing import Any, Dict, List, Mapping, Optional
12
+ from typing import Any, Dict, List, Mapping, Optional, Set, Tuple
13
13
 
14
14
  from .apps import AppSpec
15
15
  from .replay import ControlNotFound
@@ -38,6 +38,84 @@ def to_send_keys(chord: List[str]) -> str:
38
38
  return prefix + ("{%s}" % name if name else escape_send_keys(key))
39
39
 
40
40
 
41
+ COVERED = (
42
+ "another program's window is in front of the control, so the click was not sent (it would have gone to that "
43
+ "program); close or move that window"
44
+ )
45
+ MOUSE_REFUSED = (
46
+ "Windows refused to move the mouse. Usually a window of a program running as administrator is in front, and "
47
+ "Windows keeps other programs from controlling it: minimise or close that window, or run ForgeQE as administrator"
48
+ )
49
+
50
+
51
+ NOT_IN_FRONT = (
52
+ "the app's window could not be brought in front of another program's, so no keys were sent (they would have gone "
53
+ "to that program); close or minimise that window"
54
+ )
55
+ # Select the field's whole text and delete it, in single- and multi-line fields alike.
56
+ CLEAR_FIELD = "^{HOME}^+{END}{DELETE}"
57
+ # Seconds between typed characters.
58
+ TYPE_PAUSE = 0.01
59
+
60
+
61
+ def _is_password(control: Any) -> bool:
62
+ try:
63
+ return bool(control.element_info.element.CurrentIsPassword)
64
+ except Exception:
65
+ return False
66
+
67
+
68
+ def foreground_owner() -> Optional[int]:
69
+ """The process id owning the window in front, or None when it cannot be told."""
70
+ try:
71
+ import win32gui
72
+ import win32process
73
+
74
+ hwnd = win32gui.GetForegroundWindow()
75
+ if not hwnd:
76
+ return None
77
+ return int(win32process.GetWindowThreadProcessId(hwnd)[1])
78
+ except Exception:
79
+ return None
80
+
81
+
82
+ def last_active_popup(hwnd: int) -> Optional[int]:
83
+ """The visible, enabled window ``hwnd`` owns that was active last (a modal dialog), or None."""
84
+ try:
85
+ import ctypes
86
+
87
+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]
88
+ popup = int(user32.GetLastActivePopup(hwnd) or 0)
89
+ if popup and user32.IsWindowVisible(popup) and user32.IsWindowEnabled(popup):
90
+ return popup
91
+ except Exception:
92
+ pass
93
+ return None
94
+
95
+
96
+ def _click_point(control: Any) -> Optional[Tuple[int, int]]:
97
+ """The screen point pywinauto clicks: the middle of the control."""
98
+ try:
99
+ r = control.rectangle()
100
+ return (int(r.left + r.right) // 2, int(r.top + r.bottom) // 2)
101
+ except Exception:
102
+ return None
103
+
104
+
105
+ def window_owner_at(point: Tuple[int, int]) -> Optional[int]:
106
+ """The process id owning the window at a screen point, or None when it cannot be told."""
107
+ try:
108
+ import win32gui
109
+ import win32process
110
+
111
+ hwnd = win32gui.WindowFromPoint(point)
112
+ if not hwnd:
113
+ return None
114
+ return int(win32process.GetWindowThreadProcessId(hwnd)[1])
115
+ except Exception:
116
+ return None
117
+
118
+
41
119
  def _criteria(target: Mapping[str, Any]) -> Dict[str, Any]:
42
120
  crit: Dict[str, Any] = {}
43
121
  if target.get("automation_id"):
@@ -53,9 +131,45 @@ def _criteria(target: Mapping[str, Any]) -> Dict[str, Any]:
53
131
  return crit
54
132
 
55
133
 
134
+ def window_is_target(win: Any, target: Mapping[str, Any]) -> bool:
135
+ """Whether ``target`` names the top-level window itself: no path or index, an id or name, every property equal."""
136
+ if target.get("path") or "index" in target or not (target.get("automation_id") or target.get("name")):
137
+ return False
138
+ try:
139
+ info = win.element_info
140
+ have = {"automation_id": info.automation_id, "name": info.name, "control_type": info.control_type, "class_name": info.class_name}
141
+ except Exception:
142
+ return False
143
+ return all(have[k] == target[k] for k in have if target.get(k))
144
+
145
+
146
+ def same_element(infos: List[Any]) -> bool:
147
+ """Whether every element info is the same UI element: one UIA runtime id, known for each."""
148
+ ids = set()
149
+ for info in infos:
150
+ rid = getattr(info, "runtime_id", None)
151
+ if not rid:
152
+ return False
153
+ ids.add(tuple(rid))
154
+ return len(ids) == 1
155
+
156
+
157
+ def _matches_one_control(spec: Any, crit: Mapping[str, Any]) -> bool:
158
+ try:
159
+ from pywinauto.findwindows import find_elements
160
+
161
+ parent = spec.wrapper_object().element_info
162
+ found = find_elements(backend="uia", parent=parent, top_level_only=False, **crit)
163
+ except Exception:
164
+ return False
165
+ return len(found) > 1 and same_element(found)
166
+
167
+
56
168
  class PywinautoDriver:
57
169
  # Drives the real desktop, so a run first checks the session can take input (session.py).
58
170
  needs_desktop = True
171
+ # Seconds a click waits for the app's window to come in front of another program's at the click point.
172
+ cover_timeout = 2.0
59
173
 
60
174
  def __init__(self, launch_timeout: float = 30.0, poll: float = 0.25) -> None:
61
175
  self.launch_timeout = launch_timeout
@@ -87,15 +201,26 @@ class PywinautoDriver:
87
201
  last = "no window"
88
202
  while True:
89
203
  for win in app.windows():
90
- spec = app.window(handle=win.handle)
91
- for part in target.get("path") or []:
92
- spec = spec.child_window(**{k: v for k, v in (("control_type", part.get("control_type")), ("title", part.get("name"))) if v})
204
+ if window_is_target(win, target):
205
+ # A check of the window itself (its title): it is not one of its own descendants.
206
+ return win
93
207
  try:
208
+ spec = app.window(handle=win.handle)
209
+ for part in target.get("path") or []:
210
+ spec = spec.child_window(**{k: v for k, v in (("control_type", part.get("control_type")), ("title", part.get("name"))) if v})
94
211
  return spec.child_window(**_criteria(target)).wrapper_object()
95
212
  except ElementAmbiguousError:
213
+ # UIA lists some controls twice (the items of a WinForms drop-down menu): one control seen twice
214
+ # is not a choice between controls.
215
+ if _matches_one_control(spec, _criteria(target)):
216
+ return spec.child_window(**_criteria(target), found_index=0).wrapper_object()
96
217
  raise ControlNotFound(f"several controls match {dict(target)}; add an index or more properties")
97
218
  except ElementNotFoundError as e:
98
219
  last = str(e) or "not found"
220
+ except Exception as e:
221
+ # The window closed between listing and searching it (a dialog going away answers with a COM
222
+ # error): not found yet, look again.
223
+ last = f"a window went away while it was searched ({type(e).__name__})"
99
224
  if time.time() >= deadline:
100
225
  raise ControlNotFound(f"no control matches {dict(target)} ({last})")
101
226
  time.sleep(self.poll)
@@ -114,21 +239,69 @@ class PywinautoDriver:
114
239
  time.sleep(self.poll)
115
240
 
116
241
  def click(self, control: Any, double: bool = False) -> None:
117
- if double:
118
- control.double_click_input()
119
- else:
120
- control.click_input()
242
+ # pywinauto clicks at screen coordinates: a window of another program in front of the control would take the
243
+ # click. Bring the app's window forward, and send nothing while another program's window holds that point.
244
+ try:
245
+ control.top_level_parent().set_focus()
246
+ except Exception:
247
+ pass
248
+ self._wait_point_is_app(_click_point(control))
249
+ try:
250
+ if double:
251
+ control.double_click_input()
252
+ else:
253
+ control.click_input()
254
+ except Exception as e:
255
+ if "SetCursorPos" in str(e):
256
+ raise RuntimeError(MOUSE_REFUSED) from e
257
+ raise
258
+
259
+ def _app_pids(self) -> Set[int]:
260
+ pids: Set[int] = {self.proc.pid} if self.proc is not None else set()
261
+ try:
262
+ pids.update(int(w.element_info.process_id) for w in self._require_app().windows())
263
+ except Exception:
264
+ pass
265
+ return pids
266
+
267
+ def _wait_point_is_app(self, point: Optional[Tuple[int, int]]) -> None:
268
+ """Wait until the window at ``point`` is the app's own; refuse the click when another program's stays there."""
269
+ if point is None:
270
+ return
271
+ pids = self._app_pids()
272
+ deadline = time.time() + self.cover_timeout
273
+ while True:
274
+ owner = window_owner_at(point)
275
+ if owner is None or owner in pids:
276
+ return
277
+ if time.time() >= deadline:
278
+ raise RuntimeError(COVERED)
279
+ time.sleep(self.poll)
121
280
 
122
281
  def type_text(self, control: Any, text: str) -> None:
123
282
  control.set_focus()
283
+ # Keys go to whatever window is in front: never type (a secret, say) into another program's window.
284
+ self._wait_foreground_is_app()
124
285
  setter = getattr(control, "set_edit_text", None)
125
- if setter is not None:
286
+ if setter is not None and (not text or any(c in text for c in "\r\n\t")):
287
+ # Text over several lines, or with tabs: typed, a line break would press Enter (and submit a form).
126
288
  try:
127
289
  setter(text)
128
290
  return
129
291
  except Exception:
130
292
  pass
131
- control.type_keys(escape_send_keys(text), with_spaces=True, with_tabs=True, with_newlines=True, set_foreground=True)
293
+ # Typed like a person: some controls show text set through UI Automation but act only on typed input (the
294
+ # Windows file dialog saves under its default name).
295
+ control.type_keys(CLEAR_FIELD, set_foreground=False)
296
+ control.type_keys(escape_send_keys(text), with_spaces=True, with_tabs=True, with_newlines=True, set_foreground=False, pause=TYPE_PAUSE)
297
+ if setter is not None and not _is_password(control):
298
+ try:
299
+ landed = text in self.text_of(control)
300
+ except Exception:
301
+ landed = True
302
+ if not landed:
303
+ # Keys lost or changed on the way (an input method, a field that reformats): set the text instead.
304
+ setter(text)
132
305
 
133
306
  def select(self, control: Any, value: str) -> None:
134
307
  control.select(value)
@@ -136,10 +309,35 @@ class PywinautoDriver:
136
309
  def press(self, chord: List[str]) -> None:
137
310
  from pywinauto.keyboard import send_keys
138
311
 
139
- app = self._require_app()
140
- app.top_window().set_focus()
312
+ # The window that takes keyboard input: an open dialog of the app, not its main window behind it.
313
+ self._input_window().set_focus()
314
+ self._wait_foreground_is_app()
141
315
  send_keys(to_send_keys(chord))
142
316
 
317
+ def _input_window(self) -> Any:
318
+ """The app's dialog in front of its main window, else its main window (Windows' GetLastActivePopup)."""
319
+ app = self._require_app()
320
+ top = app.top_window().wrapper_object()
321
+ popup = last_active_popup(top.handle)
322
+ if popup and popup != top.handle:
323
+ try:
324
+ return app.window(handle=popup).wrapper_object()
325
+ except Exception:
326
+ pass
327
+ return top
328
+
329
+ def _wait_foreground_is_app(self) -> None:
330
+ """Wait until the app's window is in front; refuse when another program keeps the keyboard."""
331
+ pids = self._app_pids()
332
+ deadline = time.time() + self.cover_timeout
333
+ while True:
334
+ owner = foreground_owner()
335
+ if owner is None or owner in pids:
336
+ return
337
+ if time.time() >= deadline:
338
+ raise RuntimeError(NOT_IN_FRONT)
339
+ time.sleep(self.poll)
340
+
143
341
  def text_of(self, control: Any) -> str:
144
342
  texts = [str(control.window_text() or "")]
145
343
  try:
@@ -51,6 +51,8 @@ class StepResult:
51
51
  attempts: int = 1
52
52
  # Labels of the dialogs dismissed while this step ran.
53
53
  dismissed: List[str] = field(default_factory=list)
54
+ # A dismiss control found but not clicked, with the reason: told with the step's error, never dropped.
55
+ dismiss_failed: List[str] = field(default_factory=list)
54
56
  # expect_image: the files written for the step (baseline, actual, diff) and how much differed.
55
57
  images: Optional[Dict[str, Any]] = None
56
58
  note: str = ""
@@ -185,6 +187,8 @@ def replay(
185
187
  error = ControlNotFound(f"{error}; the healed target failed too: {e2}")
186
188
  if error is not None:
187
189
  res.ok, res.error = False, str(error) + (f" (after {res.attempts} tries)" if res.attempts > 1 else "")
190
+ if res.dismiss_failed:
191
+ res.error += "; a dialog in dismiss could not be closed (" + "; ".join(res.dismiss_failed) + ")"
188
192
  res.ms = int((clock() - started) * 1000)
189
193
  result.steps.append(res)
190
194
  if on_step is not None:
@@ -234,8 +238,12 @@ class _Runner:
234
238
  self.driver.click(control)
235
239
  self.res.dismissed.append(_label(target))
236
240
  clicked = True
237
- except Exception:
238
- pass
241
+ except Exception as e:
242
+ # Say why the dialog stayed: otherwise the step fails on the control the dialog hides, with no word
243
+ # about the dialog.
244
+ why = f"{_label(target)}: {e}"
245
+ if why not in self.res.dismiss_failed:
246
+ self.res.dismiss_failed.append(why)
239
247
  return clicked
240
248
 
241
249
  def find(self, target: Mapping[str, Any], timeout: float, ready: bool = False) -> Any:
@@ -107,7 +107,7 @@ def run_replay(req: Mapping[str, Any], events: Events, driver: Any, stop: thread
107
107
  desktop = req.get("desktop") or {}
108
108
  workflow_file = str(req.get("workflow") or "")
109
109
  wf = load(workflow_file)
110
- heal = make_heal(_model(req, events, model_factory), driver, log=events.log, images=takes_images(req.get("llm") or {})) if req.get("heal") else None
110
+ heal = make_heal(_model(req, events, model_factory), driver, log=events.log, images=takes_images(req.get("llm") or {}), steps=wf["steps"]) if req.get("heal") else None
111
111
  from .memory import AppMemory, remembered_heal
112
112
 
113
113
  # A control that an earlier heal found is used again without the model (memory heals/<app>.json).
@@ -141,6 +141,9 @@ def run_replay(req: Mapping[str, Any], events: Events, driver: Any, stop: thread
141
141
  should_stop=stop.is_set,
142
142
  compare_image=compare_image,
143
143
  )
144
+ settle = getattr(heal, "settle", None)
145
+ if settle is not None:
146
+ settle(result.ok)
144
147
  steps = []
145
148
  for s in result.steps:
146
149
  shot = f"steps/{s.index:03d}.png"
@@ -201,7 +204,7 @@ def run_explore(
201
204
  if runner is None:
202
205
  from .ufo_runner import run_ufo as runner
203
206
 
204
- from .memory import AppMemory, action_steps, memory_note, replay_known, worked_names
207
+ from .memory import AppMemory, action_steps, memory_note, repeated_replay, replay_known, worked_names
205
208
 
206
209
  _check_desktop(driver)
207
210
  memory = AppMemory.from_request(req, "desktop")
@@ -240,6 +243,10 @@ def run_explore(
240
243
  events.log(ufo_error, "error")
241
244
  workflow, skipped = steps_from_trace(trace, app=app, name=name, secrets=secrets)
242
245
  prefix = action_steps(known["done"])
246
+ again = repeated_replay(known["done"], workflow["steps"][1:])
247
+ if again:
248
+ events.log(f"UFO did the {again} steps replayed from memory again; the workflow keeps them once.")
249
+ workflow = {**workflow, "steps": [workflow["steps"][0], *workflow["steps"][1 + again :]]}
243
250
  if prefix:
244
251
  # The steps replayed from memory come first: the workflow is the whole path, not only what UFO added.
245
252
  flow = known["flow"] or {}
@@ -8,7 +8,9 @@ UFO is a pinned checkout that ForgeQE owns (``forgeqe desktop setup --ufo``); it
8
8
  - starts the app from ``desktop.apps`` itself, so UFO never launches a program;
9
9
  - wraps UFO's ``ActionExecutor.execute`` to record each action with the control's UIA properties (UFO's own log has the
10
10
  control's name and a per-step id, not its AutomationId), and to refuse keys that reach outside the app;
11
- - answers UFO's console questions (its safe guard for sensitive actions) with no, since nobody is at the console.
11
+ - answers UFO's console questions (its safe guard for sensitive actions) with no, since nobody is at the console;
12
+ - keeps UFO in a window that exists: when the window it chose closes (a start-up dialog), it goes on in the app's live
13
+ window (``follow_live_window``).
12
14
  """
13
15
  from __future__ import annotations
14
16
 
@@ -146,6 +148,101 @@ def write_ufo_config(ufo_dir: Path, profile_name: str, profile: Mapping[str, Any
146
148
  (cfg_dir / "mcp.yaml").write_text(yaml.safe_dump(MCP_CONFIG, sort_keys=False), encoding="utf-8")
147
149
 
148
150
 
151
+ def _window_alive(window: Any) -> bool:
152
+ """Whether a window UFO selected still exists and shows (a closed dialog's handle is gone or hidden)."""
153
+ import ctypes
154
+
155
+ try:
156
+ handle = int(window.handle)
157
+ except Exception:
158
+ return False
159
+ user32 = ctypes.windll.user32
160
+ return bool(handle and user32.IsWindow(handle) and user32.IsWindowVisible(handle))
161
+
162
+
163
+ def _live_window_of(pid: int) -> Any:
164
+ """The process's window to work in now: the one in front when it is the app's, else its first visible one."""
165
+ import ctypes
166
+
167
+ from pywinauto import Desktop
168
+
169
+ windows = [w for w in Desktop(backend="uia").windows(process=pid, visible_only=True) if _window_alive(w)]
170
+ front = ctypes.windll.user32.GetForegroundWindow()
171
+ return next((w for w in windows if int(w.handle) == front), windows[0] if windows else None)
172
+
173
+
174
+ def follow_live_window(
175
+ state_cls: Any,
176
+ log: Callable[[str], None] = lambda s: None,
177
+ alive: Callable[[Any], bool] = _window_alive,
178
+ live_window_of: Callable[[int], Any] = _live_window_of,
179
+ ) -> Callable[[], None]:
180
+ """
181
+ Keep UFO in a window that exists. UFO selects a window once (``UIServerState.selected_app_window``) and takes its
182
+ screenshots, its control list and its coordinates from it at every step; when that window is a start-up dialog the
183
+ app opened with (an update question), it closes after the first click, and every later click lands at (0, 0) until
184
+ the step limit. Reading the selected window now gives, when it has closed, the same process's live window (UFO's
185
+ ``initialize_for_window``, as its own selection does). Returns a function that undoes it.
186
+ """
187
+ store, pid_store = "_forgeqe_selected_window", "_forgeqe_selected_pid"
188
+
189
+ def get(self: Any) -> Any:
190
+ window = self.__dict__.get(store)
191
+ if window is None or alive(window):
192
+ return window
193
+ pid = self.__dict__.get(pid_store)
194
+ replacement = None
195
+ if pid:
196
+ try:
197
+ replacement = live_window_of(pid)
198
+ except Exception:
199
+ replacement = None
200
+ if replacement is None:
201
+ return window # the app itself has gone: nothing to move to
202
+ try:
203
+ title = str(replacement.window_text() or "")
204
+ except Exception:
205
+ title = ""
206
+ log(f"The window UFO was working in has closed; it carries on in {title or 'the app'}'s window.")
207
+ self.initialize_for_window(replacement)
208
+ return self.__dict__.get(store)
209
+
210
+ def set_(self: Any, window: Any) -> None:
211
+ self.__dict__[store] = window
212
+ pid = None
213
+ if window is not None:
214
+ try:
215
+ pid = int(window.element_info.process_id)
216
+ except Exception:
217
+ pid = None
218
+ self.__dict__[pid_store] = pid
219
+
220
+ had = "selected_app_window" in state_cls.__dict__
221
+ original = state_cls.__dict__.get("selected_app_window")
222
+ instance = getattr(state_cls, "_instance", None)
223
+ if instance is not None and "selected_app_window" in instance.__dict__:
224
+ moved = instance.__dict__.pop("selected_app_window")
225
+ state_cls.selected_app_window = property(get, set_)
226
+ instance.selected_app_window = moved
227
+ else:
228
+ state_cls.selected_app_window = property(get, set_)
229
+
230
+ def restore() -> None:
231
+ # UFO may have made its singleton during the run: look it up now.
232
+ now = getattr(state_cls, "_instance", None)
233
+ current = now.__dict__.get(store) if now is not None else None
234
+ if had:
235
+ state_cls.selected_app_window = original
236
+ else:
237
+ del state_cls.selected_app_window
238
+ if now is not None:
239
+ now.__dict__.pop(store, None)
240
+ now.__dict__.pop(pid_store, None)
241
+ now.__dict__["selected_app_window"] = current
242
+
243
+ return restore
244
+
245
+
149
246
  def _control_props(control: Any) -> Dict[str, str]:
150
247
  info = getattr(control, "element_info", None)
151
248
  out: Dict[str, str] = {}
@@ -285,10 +382,12 @@ def run_ufo(
285
382
  trace = [] if trace is None else trace
286
383
  with _in_ufo(ufo_dir, ["ufo", "--task", task, "--request", goal, "--log-level", "WARNING"]):
287
384
  from ufo.automator.action_execution import ActionExecutor # type: ignore
385
+ from ufo.client.mcp.local_servers.ui_mcp_server import UIServerState # type: ignore
288
386
  from ufo.llm.base import BaseService # type: ignore
289
387
 
290
388
  restore_model = install(profile_name, profile, on_call=on_call, base_service=BaseService, model=model)
291
389
  restore_trace = install_trace(ActionExecutor, trace)
390
+ restore_window = follow_live_window(UIServerState, log=log)
292
391
  try:
293
392
  with _no_console_answers(log), _console_to_stderr():
294
393
  import asyncio
@@ -297,6 +396,7 @@ def run_ufo(
297
396
 
298
397
  asyncio.run(ufo_main.main())
299
398
  finally:
399
+ restore_window()
300
400
  restore_trace()
301
401
  restore_model()
302
402
  logs = ufo_dir / "logs" / task
@@ -142,7 +142,7 @@ def run_replay(req: Mapping[str, Any], events: Events, stop: threading.Event, dr
142
142
  if os.environ.get(n) is None:
143
143
  raise WorkflowError(f"secret {n} is not set: the workflow types it (set {n} in the environment or .env, or in the credential store)")
144
144
  driver = (driver_factory or (lambda: appium_driver(mobile)))()
145
- heal = make_heal(_model(req, events, model_factory), driver, log=events.log, images=takes_images(req.get("llm") or {})) if req.get("heal") else None
145
+ heal = make_heal(_model(req, events, model_factory), driver, log=events.log, images=takes_images(req.get("llm") or {}), steps=wf["steps"]) if req.get("heal") else None
146
146
  # A control that an earlier heal found is used again without the model (memory heals/<app>.json).
147
147
  heal = remembered_heal(AppMemory.from_request(req, "mobile"), wf["app"], driver, heal, log=events.log)
148
148
  shots = bool(mobile.get("screenshots", True))
@@ -169,6 +169,9 @@ def run_replay(req: Mapping[str, Any], events: Events, stop: threading.Event, dr
169
169
  should_stop=stop.is_set,
170
170
  compare_image=image_checker(workflow_file, out, update=bool(req.get("update_baselines"))),
171
171
  )
172
+ settle = getattr(heal, "settle", None)
173
+ if settle is not None:
174
+ settle(result.ok)
172
175
  steps = []
173
176
  for s in result.steps:
174
177
  shot = f"steps/{s.index:03d}.png"
@@ -38,7 +38,7 @@ def read(path: Path, test_attributes: Optional[List[str]] = None, skip_modules:
38
38
  if m is None:
39
39
  continue
40
40
  case = {**tc, "id": _case_id(tc["name"], used)}
41
- cases.append(ntir.build(m, case, idx.engines, tsu.route_of))
41
+ cases.append(ntir.build(m, case, idx.engines, tsu.route_of, idx.api, idx.controls))
42
42
  by_id = {c["source"]["test_case"]["surrogate"]: c["source"]["test_case"]["id"] for c in cases}
43
43
  suites = [{"name": s["name"], "folders": s["folders"], "cases": [by_id[x] for x in s["cases"] if x in by_id]} for s in idx.suites]
44
44
  return {"file": Path(path).name, "project": idx.project, "entities": idx.entity_count, "engines": idx.engines, "cases": cases, "suites": suites}
@@ -58,12 +58,22 @@ def summary(result: Dict[str, Any]) -> Dict[str, Any]:
58
58
  env.setdefault(e["name"], e)
59
59
  cases.append({
60
60
  "id": c["source"]["test_case"]["id"], "name": c["source"]["test_case"]["name"],
61
+ # Tosca's own unique id (the test case's surrogate): stays when it is renamed or moved.
62
+ "uid": c["source"]["test_case"].get("surrogate", ""),
61
63
  "folders": c["source"]["test_case"]["folders"], "area": c["source"]["test_case"].get("area", []),
62
64
  "suites": c["source"]["test_case"].get("suites", []), "route": c["route"], "routes": c["routes"],
63
65
  "steps": r["counts"]["steps"], "actions": r["counts"]["actions"], "asserts": r["counts"]["asserts"],
64
66
  "unsupported": r["counts"]["unsupported"], "warnings": len(r["warnings"]),
67
+ # Read-only database queries the target's database client runs (db.py).
68
+ "db": r["counts"].get("db", 0),
69
+ # Read-only file and Excel checks (files.py), which the test makes with the target's own code.
70
+ "files": r["counts"].get("files", 0),
71
+ # Runs of desktop or mobile steps in a web or API test, each a small workflow the test replays (ntir.py).
72
+ **({"parts": sorted({p["engine"] for p in c["parts"]})} if c.get("parts") else {}),
65
73
  "pages": [p["id"] for p in c["pages"]], "env": [e["name"] for e in c["config"]["env"]],
66
74
  "base_url": c["config"]["base_url"],
75
+ # A desktop or mobile case as a ForgeQE workflow (app.py): its engine, steps (launch and close aside), steps left out.
76
+ **({"workflow": {"engine": c["workflow"]["engine"], "steps": len(c["workflow"]["steps"]) - 2, "skipped": len(c["workflow"]["skipped"])}} if c.get("workflow") else {}),
67
77
  })
68
78
  pages: Dict[str, Dict[str, Any]] = {}
69
79
  for c in result["cases"]: