sim-cli-core 0.2.4__py3-none-any.whl

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.
@@ -0,0 +1,432 @@
1
+ """OpenFOAM driver for sim.
2
+
3
+ OpenFOAM runs on a remote Linux machine. This driver communicates with
4
+ it via sim-server (HTTP). No local OpenFOAM installation needed.
5
+
6
+ Two execution models:
7
+
8
+ Phase 1 — One-shot local:
9
+ run_file(script) executes a Python script locally via subprocess.
10
+ Only useful if OpenFOAM is installed on the same machine.
11
+
12
+ Phase 2 — Remote session via sim-server:
13
+ launch(host, port) → POST /connect {solver: "openfoam"}
14
+ run(code, label) → POST /exec {code, label}
15
+ query(name) → GET /inspect/<name>
16
+ disconnect() → POST /disconnect
17
+
18
+ The ``#!openfoam`` shebang in code sent to /exec triggers shell-mode
19
+ execution on the remote server — the code is run as a bash script
20
+ with the OpenFOAM environment sourced, not as Python.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import ast
25
+ import json
26
+ import re
27
+ import sys
28
+ import time
29
+ import uuid
30
+ from datetime import datetime, timezone
31
+ from pathlib import Path
32
+
33
+ import httpx
34
+
35
+ from sim.driver import ConnectionInfo, Diagnostic, LintResult, RunResult, SolverInstall
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Detection helpers (for local OpenFOAM, if present)
40
+ # ---------------------------------------------------------------------------
41
+
42
+ def _openfoam_version_from_path(install_dir: Path) -> str | None:
43
+ """Extract a normalized OpenFOAM version from an install dir name.
44
+
45
+ Examples:
46
+ /opt/openfoam-v2406 -> "v2406"
47
+ /opt/openfoam2312 -> "v2312"
48
+ /usr/lib/openfoam/openfoam-v2206 -> "v2206"
49
+ ~/OpenFOAM/OpenFOAM-11 -> "11"
50
+ """
51
+ name = install_dir.name.lower()
52
+ m = re.search(r"v?(\d{4})", name)
53
+ if m:
54
+ return f"v{m.group(1)}"
55
+ m = re.search(r"openfoam-(\d+)$", name)
56
+ if m:
57
+ return m.group(1)
58
+ return None
59
+
60
+
61
+ _OPENFOAM_PATTERNS = re.compile(
62
+ r"(#\s*openfoam|#!openfoam|blockMesh|simpleFoam|icoFoam|pisoFoam"
63
+ r"|snappyHexMesh|OpenFOAMCase|foam\.run_command|foam\.solve)",
64
+ re.IGNORECASE,
65
+ )
66
+
67
+
68
+ class OpenFOAMDriver:
69
+ """Sim driver for OpenFOAM (remote via sim-server).
70
+
71
+ DriverProtocol surface:
72
+ name, detect, lint, connect, parse_output, run_file
73
+
74
+ Extended remote-session API:
75
+ launch(host, port) → connect to remote sim-server
76
+ run(code, label) → execute on remote (shell or Python)
77
+ query(name) → inspect remote session state
78
+ disconnect() → tear down remote session
79
+ """
80
+
81
+ def __init__(self):
82
+ self._host: str | None = None
83
+ self._port: int | None = None
84
+ self._session_id: str | None = None
85
+ self._client: httpx.Client | None = None
86
+ self._timeout: float = 300.0 # solver can run minutes
87
+
88
+ @property
89
+ def name(self) -> str:
90
+ return "openfoam"
91
+
92
+ @property
93
+ def supports_session(self) -> bool:
94
+ return False
95
+
96
+ # -- DriverProtocol -------------------------------------------------------
97
+
98
+ def detect(self, script: Path) -> bool:
99
+ """Detect OpenFOAM scripts.
100
+
101
+ Accepts:
102
+ - .foam files (OpenFOAM case markers)
103
+ - .py files with OpenFOAM-related imports/comments
104
+ - Shell scripts with #!openfoam shebang
105
+ """
106
+ ext = script.suffix.lower()
107
+ if ext == ".foam":
108
+ return True
109
+ if ext in (".py", ".sh"):
110
+ try:
111
+ header = script.read_bytes()[:4096].decode("utf-8", errors="replace")
112
+ return bool(_OPENFOAM_PATTERNS.search(header))
113
+ except OSError:
114
+ return False
115
+ return False
116
+
117
+ def lint(self, script: Path) -> LintResult:
118
+ """Validate script syntax without executing."""
119
+ ext = script.suffix.lower()
120
+
121
+ if ext == ".foam":
122
+ return LintResult(ok=True, diagnostics=[
123
+ Diagnostic(level="info", message="OpenFOAM case marker file")
124
+ ])
125
+
126
+ if ext == ".sh":
127
+ # Shell scripts — just check file exists and is non-empty
128
+ try:
129
+ text = script.read_text(errors="replace")
130
+ if not text.strip():
131
+ return LintResult(ok=False, diagnostics=[
132
+ Diagnostic(level="error", message="Script is empty")
133
+ ])
134
+ return LintResult(ok=True, diagnostics=[])
135
+ except OSError as e:
136
+ return LintResult(ok=False, diagnostics=[
137
+ Diagnostic(level="error", message=f"Cannot read file: {e}")
138
+ ])
139
+
140
+ if ext == ".py":
141
+ try:
142
+ text = script.read_text(errors="replace")
143
+ ast.parse(text)
144
+ return LintResult(ok=True, diagnostics=[])
145
+ except SyntaxError as e:
146
+ return LintResult(ok=False, diagnostics=[
147
+ Diagnostic(level="error", message=f"Syntax error: {e}", line=e.lineno)
148
+ ])
149
+
150
+ return LintResult(ok=False, diagnostics=[
151
+ Diagnostic(level="error", message=f"Unsupported file type '{ext}'")
152
+ ])
153
+
154
+ def connect(self) -> ConnectionInfo:
155
+ """Check remote sim-server availability (if host/port set) or local OF."""
156
+ if self._host:
157
+ try:
158
+ r = httpx.get(
159
+ f"http://{self._host}:{self._port}/ps",
160
+ timeout=5.0,
161
+ )
162
+ data = r.json()
163
+ return ConnectionInfo(
164
+ solver="openfoam",
165
+ version=data.get("openfoam_version", "remote"),
166
+ status="ok",
167
+ message=f"sim-server at {self._host}:{self._port} reachable",
168
+ )
169
+ except Exception as e:
170
+ return ConnectionInfo(
171
+ solver="openfoam",
172
+ version=None,
173
+ status="unreachable",
174
+ message=f"Cannot reach sim-server at {self._host}:{self._port}: {e}",
175
+ )
176
+
177
+ # No remote host set — report as needing configuration
178
+ return ConnectionInfo(
179
+ solver="openfoam",
180
+ version=None,
181
+ status="not_configured",
182
+ message="OpenFOAM runs remotely. Call launch(host, port) to connect to sim-server.",
183
+ )
184
+
185
+ def detect_installed(self) -> list[SolverInstall]:
186
+ """Enumerate OpenFOAM installations on this host.
187
+
188
+ Strategy (deduplicated by install path; ordered with the highest
189
+ version first):
190
+ 1. WM_PROJECT_DIR / WM_PROJECT_VERSION env vars (the canonical
191
+ signal — set after the user has sourced etc/bashrc)
192
+ 2. /opt/openfoam-v* and /opt/openfoam* (ESI Ubuntu / RHEL packages)
193
+ 3. /usr/lib/openfoam/openfoam-v* (Foundation deb defaults)
194
+ 4. ~/OpenFOAM/OpenFOAM-v* (manual user installs)
195
+ 5. `which simpleFoam` PATH probe — last resort, used to surface a
196
+ usable install whose location doesn't match any default
197
+
198
+ Pure stdlib. Does NOT source bashrc — that happens later in the
199
+ runner's op_connect. Returns [] when nothing is found.
200
+ """
201
+ import os
202
+ import shutil
203
+
204
+ found: dict[str, SolverInstall] = {}
205
+
206
+ def _record(install_dir: Path, source: str, version_hint: str | None = None) -> None:
207
+ if not install_dir.is_dir():
208
+ return
209
+ version = version_hint or _openfoam_version_from_path(install_dir)
210
+ if version is None:
211
+ return
212
+ key = str(install_dir.resolve())
213
+ if key in found:
214
+ return
215
+ found[key] = SolverInstall(
216
+ name="openfoam",
217
+ version=version,
218
+ path=key,
219
+ source=source,
220
+ extra={"raw_version": version},
221
+ )
222
+
223
+ # 1) Inherited env vars
224
+ env_dir = os.environ.get("WM_PROJECT_DIR")
225
+ env_ver = os.environ.get("WM_PROJECT_VERSION")
226
+ if env_dir:
227
+ _record(Path(env_dir), source="env:WM_PROJECT_DIR", version_hint=env_ver)
228
+
229
+ # 2,3,4) Default install dirs
230
+ scan_roots = [
231
+ Path("/opt"),
232
+ Path("/usr/lib"),
233
+ Path("/usr/lib/openfoam"),
234
+ Path.home() / "OpenFOAM",
235
+ ]
236
+ for root in scan_roots:
237
+ if not root.is_dir():
238
+ continue
239
+ for child in sorted(root.iterdir()):
240
+ n = child.name.lower()
241
+ if "openfoam" not in n:
242
+ continue
243
+ # ESI sometimes nests as openfoam-v2406/ → has etc/bashrc directly,
244
+ # sometimes as openfoam/openfoam-v2406/ — handle both layers.
245
+ if (child / "etc" / "bashrc").is_file():
246
+ _record(child, source=f"default-path:{root}")
247
+ else:
248
+ for sub in child.iterdir() if child.is_dir() else []:
249
+ if (sub / "etc" / "bashrc").is_file():
250
+ _record(sub, source=f"default-path:{root}")
251
+
252
+ # 5) PATH probe
253
+ sfoam = shutil.which("simpleFoam")
254
+ if sfoam:
255
+ # simpleFoam typically lives at <install>/platforms/linux64GccDPInt32Opt/bin/
256
+ # walk up to find the install root (the dir that contains etc/bashrc)
257
+ p = Path(sfoam).resolve()
258
+ for parent in p.parents:
259
+ if (parent / "etc" / "bashrc").is_file():
260
+ _record(parent, source="which:simpleFoam")
261
+ break
262
+
263
+ # Highest version first (string sort works for "v2406" > "v2312" > "v2206")
264
+ return sorted(found.values(), key=lambda i: i.version, reverse=True)
265
+
266
+ def parse_output(self, stdout: str) -> dict:
267
+ """Extract last JSON object from stdout."""
268
+ for line in reversed(stdout.strip().splitlines()):
269
+ line = line.strip()
270
+ if line.startswith("{"):
271
+ try:
272
+ return json.loads(line)
273
+ except json.JSONDecodeError:
274
+ continue
275
+ return {}
276
+
277
+ def run_file(self, script: Path) -> RunResult:
278
+ """Execute a local script with the OpenFOAM environment sourced.
279
+
280
+ ``--solver openfoam`` is supposed to mean "run this in an OpenFOAM
281
+ environment". Without sourcing ``etc/bashrc`` the agent's script
282
+ sees an empty PATH/WM_PROJECT_DIR and gets a confusing
283
+ ``blockMesh: not found`` from the wrong layer. We source bashrc
284
+ once and then exec the script so the OF tooling is reachable.
285
+
286
+ Falls back to bare ``python3 SCRIPT`` only if no OF install is
287
+ detected (caller will fail downstream anyway).
288
+ """
289
+ from sim.runner import run_subprocess
290
+
291
+ installs = self.detect_installed()
292
+ bashrc = None
293
+ for inst in installs:
294
+ candidate = Path(inst.path) / "etc" / "bashrc"
295
+ if candidate.is_file():
296
+ bashrc = candidate
297
+ break
298
+
299
+ if bashrc is None:
300
+ return run_subprocess(
301
+ [sys.executable, str(script)],
302
+ script=script,
303
+ solver=self.name,
304
+ )
305
+
306
+ # Wrap so the OF env is in place before the script runs. exec
307
+ # replaces the bash shell so the PID seen by the runner is the
308
+ # script's, not bash's.
309
+ import shlex
310
+ runner = "python3" if script.suffix == ".py" else "bash"
311
+ cmd = [
312
+ "bash", "-c",
313
+ f"source {shlex.quote(str(bashrc))} && "
314
+ f"exec {runner} {shlex.quote(str(script))}",
315
+ ]
316
+ return run_subprocess(cmd, script=script, solver=self.name)
317
+
318
+ # -- Phase 2: Remote session via sim-server --------------------------------
319
+
320
+ def launch(
321
+ self,
322
+ host: str = "localhost",
323
+ port: int = 7600,
324
+ timeout: float = 300.0,
325
+ ) -> dict:
326
+ """Connect to a remote sim-server running OpenFOAM.
327
+
328
+ Args:
329
+ host: sim-server hostname or IP.
330
+ port: sim-server port (default 7600).
331
+ timeout: HTTP timeout for long-running solver commands.
332
+ """
333
+ if self._session_id is not None:
334
+ raise RuntimeError("Session already active. Call disconnect() first.")
335
+
336
+ self._host = host
337
+ self._port = port
338
+ self._timeout = timeout
339
+ self._client = httpx.Client(timeout=timeout)
340
+
341
+ try:
342
+ r = self._client.post(
343
+ f"http://{host}:{port}/connect",
344
+ json={"solver": "openfoam"},
345
+ )
346
+ except httpx.ConnectError as e:
347
+ self._client.close()
348
+ self._client = None
349
+ raise RuntimeError(f"Cannot reach sim-server at {host}:{port}: {e}")
350
+
351
+ if r.status_code != 200:
352
+ detail = r.json().get("detail", r.text)
353
+ raise RuntimeError(f"sim-server /connect failed: {detail}")
354
+
355
+ data = r.json()
356
+ self._session_id = data.get("data", {}).get("session_id")
357
+ return data
358
+
359
+ def run(self, code: str, label: str = "openfoam-snippet") -> dict:
360
+ """Execute code on the remote OpenFOAM session.
361
+
362
+ If code starts with ``#!openfoam``, the server runs it as a
363
+ shell script with the OpenFOAM environment sourced.
364
+ Otherwise, it runs as Python code.
365
+
366
+ Args:
367
+ code: Shell commands (with #!openfoam prefix) or Python code.
368
+ label: Human-readable label for this execution step.
369
+ """
370
+ if self._client is None:
371
+ raise RuntimeError("Not connected. Call launch() first.")
372
+
373
+ r = self._client.post(
374
+ f"http://{self._host}:{self._port}/exec",
375
+ json={"code": code, "label": label},
376
+ )
377
+
378
+ if r.status_code != 200:
379
+ detail = r.json().get("detail", r.text)
380
+ return {"ok": False, "label": label, "error": detail}
381
+
382
+ data = r.json()
383
+ return data.get("data", data)
384
+
385
+ def query(self, name: str = "session.summary") -> dict:
386
+ """Query remote session state.
387
+
388
+ Supported: "session.summary", "last.result"
389
+ """
390
+ if self._client is None:
391
+ raise RuntimeError("Not connected. Call launch() first.")
392
+
393
+ r = self._client.get(
394
+ f"http://{self._host}:{self._port}/inspect/{name}",
395
+ )
396
+ data = r.json()
397
+ return data.get("data", data)
398
+
399
+ def disconnect(self) -> dict:
400
+ """Disconnect from the remote sim-server session."""
401
+ result = {"ok": False, "reason": "no active session"}
402
+
403
+ if self._client is not None:
404
+ try:
405
+ r = self._client.post(
406
+ f"http://{self._host}:{self._port}/disconnect",
407
+ )
408
+ result = r.json()
409
+ except Exception:
410
+ pass
411
+ try:
412
+ self._client.close()
413
+ except Exception:
414
+ pass
415
+
416
+ self._client = None
417
+ self._session_id = None
418
+ return result
419
+
420
+ @property
421
+ def is_connected(self) -> bool:
422
+ return self._client is not None and self._session_id is not None
423
+
424
+ def ps(self) -> dict:
425
+ """Check remote session status."""
426
+ if self._client is None:
427
+ return {"connected": False}
428
+ try:
429
+ r = self._client.get(f"http://{self._host}:{self._port}/ps")
430
+ return r.json()
431
+ except Exception:
432
+ return {"connected": False, "error": "request failed"}
@@ -0,0 +1,24 @@
1
+ # Third-party attribution for `sim.gui`
2
+
3
+ `sim.gui` runs on the upstream **pywinauto** library (BSD-3), installed
4
+ as a dependency of sim-cli on Windows hosts. No pywinauto code is
5
+ vendored — we call the public API directly.
6
+
7
+ Design of the tool catalogue in `_pywinauto_tools.py` (find / click /
8
+ type / close / screenshot / snapshot) was informed by:
9
+
10
+ - [`sandraschi/pywinauto-mcp`](https://github.com/sandraschi/pywinauto-mcp)
11
+ — MIT licensed. Their MCP-decorated wrappers showed which action set
12
+ was worth exposing to LLM agents. We do not import or vendor their
13
+ code; we re-implement directly over pywinauto because the MCP
14
+ decoration layer is not useful outside an MCP server.
15
+
16
+ The subprocess-isolation pattern for UIA calls (one-shot
17
+ `python -c '...'` per action to keep the calling process's COM
18
+ apartment clean) was developed in this project's GUI-driving work for
19
+ solvers that don't expose a batch API.
20
+
21
+ The Win32 ctypes file-dialog primitives in `_win32_dialog.py`
22
+ (`WM_SETTEXT` + `BM_CLICK` against control ids 1148 / 1) are part of
23
+ that same shared backend so every driver can share the implementation
24
+ instead of copy-pasting it.
sim/gui/__init__.py ADDED
@@ -0,0 +1,230 @@
1
+ """``sim.gui`` — cross-driver GUI actuation.
2
+
3
+ ``GuiController`` is the object that each session-capable driver
4
+ injects into your ``sim exec`` namespace as ``gui``. It is an
5
+ **actuation** layer — meaning the probes (``sim.inspect``) only
6
+ observe and this module only acts. The decision of whether to act
7
+ and how lives one layer higher, in the LLM agent that issues
8
+ ``sim exec`` commands.
9
+
10
+ Usage from an agent::
11
+
12
+ # Find a blocking dialog and click OK
13
+ dlg = gui.find(title_contains='Login', timeout_s=5)
14
+ if dlg:
15
+ dlg.click('OK')
16
+
17
+ # Fill a text field, then click OK
18
+ dlg = gui.find(title_contains='File Save')
19
+ dlg.send_text('/tmp/out.cas.h5', into='File name')
20
+ dlg.click('OK')
21
+
22
+ # Full UIA tree of everything the solver currently has on screen
23
+ state = gui.snapshot()
24
+
25
+ Remote use is identical — the same object lives in the namespace of a
26
+ ``sim serve`` running on the remote Windows host; the agent just talks
27
+ to it over ``sim exec --host <remote>``.
28
+
29
+ All calls return JSON-serialisable dicts. Errors are surfaced via
30
+ ``ok=False`` + ``error`` (from ``_pywinauto_tools``) — methods do not
31
+ raise unless the caller passes invalid Python types. The agent's
32
+ subsequent inspect round (channel #3 traceback / #8 window_observed)
33
+ will reflect the outcome.
34
+
35
+ See ``sim-skills/sim-cli/gui/SKILL.md`` for the full agent-facing
36
+ reference and solver-specific dialog recipes.
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import os
41
+ from dataclasses import dataclass
42
+
43
+ from sim.gui import _pywinauto_tools as _tools
44
+
45
+
46
+ @dataclass
47
+ class _WindowHandle:
48
+ """Lightweight handle describing a window found by :class:`GuiController`."""
49
+ hwnd: int
50
+ pid: int
51
+ proc: str
52
+ title: str
53
+ rect: list[int] | None
54
+
55
+
56
+ class SimWindow:
57
+ """A found window. All methods proxy to pywinauto subprocess helpers.
58
+
59
+ Instances are produced by :meth:`GuiController.find` — do not
60
+ construct directly unless you already know the hwnd.
61
+
62
+ Every method returns a dict with at least ``ok: bool``. On failure
63
+ ``error`` is populated. Agents should read ``ok`` before chaining.
64
+ """
65
+
66
+ def __init__(self, handle: _WindowHandle, workdir: str | os.PathLike | None = None):
67
+ self._h = handle
68
+ self._workdir = workdir or os.getcwd()
69
+
70
+ # ── accessors ────────────────────────────────────────────────────────
71
+ @property
72
+ def hwnd(self) -> int:
73
+ return self._h.hwnd
74
+
75
+ @property
76
+ def title(self) -> str:
77
+ return self._h.title
78
+
79
+ @property
80
+ def pid(self) -> int:
81
+ return self._h.pid
82
+
83
+ @property
84
+ def proc(self) -> str:
85
+ return self._h.proc
86
+
87
+ def as_dict(self) -> dict:
88
+ return {
89
+ "hwnd": self._h.hwnd, "pid": self._h.pid, "proc": self._h.proc,
90
+ "title": self._h.title, "rect": self._h.rect,
91
+ }
92
+
93
+ # ── actions ──────────────────────────────────────────────────────────
94
+ def click(self, button_label: str, timeout_s: float = 5.0) -> dict:
95
+ """Click the control whose accessible name equals ``button_label``.
96
+
97
+ Tries a Button control first, falls back to any control with that
98
+ title. Returns ``{ok, clicked, strategy}`` on success or
99
+ ``{ok: false, error}`` if the control was not found.
100
+ """
101
+ return _tools.click_by_name(self._h.hwnd, button_label, timeout_s=timeout_s)
102
+
103
+ def send_text(self, text: str, into: str = "", timeout_s: float = 5.0) -> dict:
104
+ """Type ``text`` into an Edit control. ``into`` is the field's
105
+ accessible name; if empty, types into the first Edit in tab order.
106
+ """
107
+ return _tools.send_text(self._h.hwnd, text, field=into, timeout_s=timeout_s)
108
+
109
+ def close(self) -> dict:
110
+ """Close this window (WM_CLOSE / Alt+F4 equivalent)."""
111
+ return _tools.close_window(self._h.hwnd)
112
+
113
+ def activate(self) -> dict:
114
+ """Bring this window to the foreground."""
115
+ return _tools.activate_window(self._h.hwnd)
116
+
117
+ def screenshot(self, label: str = "window") -> dict:
118
+ """Save a PNG of this window (window-only, not the whole desktop).
119
+
120
+ The file lands under ``<workdir>/screenshots/<label>_*.png``; the
121
+ returned dict carries ``path`` so the agent can fetch / reference it.
122
+ """
123
+ out = _tools.workdir_screenshot_path(self._workdir, label)
124
+ return _tools.screenshot_window(self._h.hwnd, out)
125
+
126
+ def __repr__(self) -> str:
127
+ return f"<SimWindow hwnd={self._h.hwnd} pid={self._h.pid} title={self._h.title!r}>"
128
+
129
+
130
+ class GuiController:
131
+ """Per-driver GUI actuation facade.
132
+
133
+ Construct with the process-name substrings that identify the driver's
134
+ windows (e.g. ``('fluent', 'cx', 'cortex')``). Every ``find`` / ``list``
135
+ call filters to those processes so accidental hits on the user's
136
+ unrelated applications are avoided.
137
+
138
+ ``available`` is ``False`` on non-Windows hosts or when pywinauto is
139
+ not importable — agents should check this before driving GUI flows.
140
+ Calling methods on an unavailable controller will return
141
+ ``{ok: false, error: ...}`` rather than raise.
142
+ """
143
+
144
+ def __init__(
145
+ self,
146
+ process_name_substrings: tuple[str, ...] = (),
147
+ workdir: str | os.PathLike | None = None,
148
+ ):
149
+ self._procs = tuple(process_name_substrings)
150
+ self._workdir = workdir or os.getcwd()
151
+
152
+ @property
153
+ def available(self) -> bool:
154
+ """True iff pywinauto is usable in this environment."""
155
+ return _tools.pywinauto_available()
156
+
157
+ @property
158
+ def process_filter(self) -> tuple[str, ...]:
159
+ return self._procs
160
+
161
+ def list_windows(self) -> dict:
162
+ """Return every visible top-level window owned by a matching process.
163
+
164
+ Shape: ``{ok, windows: [{hwnd, pid, proc, title, rect}, ...]}``
165
+ """
166
+ return _tools.list_windows(self._procs)
167
+
168
+ def find(self, title_contains: str = "", timeout_s: float = 5.0) -> "SimWindow | None":
169
+ """Poll until a matching window appears, or return ``None`` on timeout.
170
+
171
+ ``title_contains`` is a plain substring match (case-sensitive). Combine
172
+ with this controller's process filter so you get exactly one intended
173
+ window even if the user happens to have another app with the same title.
174
+ """
175
+ r = _tools.find_window(
176
+ title_contains=title_contains,
177
+ process_name_substrings=self._procs,
178
+ timeout_s=timeout_s,
179
+ )
180
+ if not r.get("ok") or not r.get("window"):
181
+ return None
182
+ w = r["window"]
183
+ return SimWindow(
184
+ _WindowHandle(
185
+ hwnd=int(w["hwnd"]), pid=int(w["pid"]),
186
+ proc=str(w["proc"]), title=str(w["title"]),
187
+ rect=w.get("rect"),
188
+ ),
189
+ workdir=self._workdir,
190
+ )
191
+
192
+ def wait_until_window_gone(
193
+ self,
194
+ title_contains: str,
195
+ timeout_s: float = 30.0,
196
+ poll_s: float = 0.5,
197
+ ) -> bool:
198
+ """Poll until no window with ``title_contains`` is visible, or timeout.
199
+
200
+ Returns ``True`` if the window is gone before ``timeout_s``, ``False``
201
+ if the timeout elapsed first. Use this instead of ``time.sleep(N)``
202
+ after dismissing a dialog — it returns as soon as the window closes
203
+ rather than waiting a fixed duration.
204
+
205
+ Example::
206
+
207
+ dlg.click('OK')
208
+ gui.wait_until_window_gone('Login', timeout_s=15)
209
+ """
210
+ import time as _t
211
+ deadline = _t.monotonic() + timeout_s
212
+ while _t.monotonic() < deadline:
213
+ r = self.list_windows()
214
+ titles = [w.get("title", "") for w in (r.get("windows") or [])]
215
+ if not any(title_contains in t for t in titles):
216
+ return True
217
+ _t.sleep(poll_s)
218
+ return False
219
+
220
+ def snapshot(self, max_depth: int = 3) -> dict:
221
+ """Full UIA tree dump of every matching window.
222
+
223
+ Expensive; use for debugging or for agents that need to reason
224
+ about the complete control tree. For targeted actions prefer
225
+ :meth:`find` + :meth:`SimWindow.click`.
226
+ """
227
+ return _tools.snapshot_uia_tree(self._procs, max_depth=max_depth)
228
+
229
+
230
+ __all__ = ["GuiController", "SimWindow"]