dsh-windows-parallel-mcp 0.8.2 → 0.9.0-rc.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 (53) hide show
  1. package/CHANGELOG.de.md +444 -419
  2. package/CHANGELOG.es.md +444 -419
  3. package/CHANGELOG.fr.md +444 -419
  4. package/CHANGELOG.it.md +444 -419
  5. package/CHANGELOG.ja.md +444 -419
  6. package/CHANGELOG.ko.md +444 -419
  7. package/CHANGELOG.md +965 -940
  8. package/CHANGELOG.pt.md +444 -419
  9. package/CHANGELOG.ru.md +444 -419
  10. package/CHANGELOG.zh.md +444 -419
  11. package/INSTALL.de.md +126 -126
  12. package/INSTALL.es.md +126 -126
  13. package/INSTALL.fr.md +126 -126
  14. package/INSTALL.it.md +126 -126
  15. package/INSTALL.ja.md +126 -126
  16. package/INSTALL.ko.md +126 -126
  17. package/INSTALL.md +122 -122
  18. package/INSTALL.pt.md +126 -126
  19. package/INSTALL.ru.md +126 -126
  20. package/INSTALL.zh.md +126 -126
  21. package/README.de.md +684 -684
  22. package/README.es.md +684 -684
  23. package/README.fr.md +684 -684
  24. package/README.it.md +684 -684
  25. package/README.ja.md +684 -684
  26. package/README.ko.md +684 -684
  27. package/README.md +680 -680
  28. package/README.pt.md +684 -684
  29. package/README.ru.md +684 -684
  30. package/README.zh.md +684 -684
  31. package/cordis.patch.yml +15 -15
  32. package/docs/refusals.md +90 -90
  33. package/docs/takeover.md +128 -128
  34. package/dsh.plugin.json +18 -18
  35. package/lib/config.js +275 -275
  36. package/lib/engine.js +252 -252
  37. package/lib/host-tools.js +365 -338
  38. package/lib/index.js +1275 -1249
  39. package/lib/peers-schemastery.js +23 -23
  40. package/lib/peers-tools.js +15 -15
  41. package/lib/proof-window.mjs +427 -427
  42. package/package.json +122 -122
  43. package/server.json +110 -110
  44. package/src/engine/decide.ps1 +356 -356
  45. package/src/engine/engine.ps1 +1208 -1208
  46. package/src/engine/hud.ps1 +411 -411
  47. package/src/engine/input-inject.ps1 +176 -176
  48. package/src/engine/overlay.ps1 +389 -389
  49. package/src/engine/takeover.ps1 +144 -144
  50. package/src/engine/win.ps1 +1881 -1881
  51. package/src/engine/worker.ps1 +310 -310
  52. package/src/schema/tools.json +533 -533
  53. package/types/index.d.ts +190 -187
@@ -1,1881 +1,1881 @@
1
- # win.ps1 -- the IO half of the R2' engine: probe a target's doors, act through the cheapest
2
- # door it has, and put the owner's focus back when the action cost them a flash.
3
- #
4
- # Layering is deliberate. decide.ps1 owns every judgement (pure, unit-tested). This file owns
5
- # every syscall and no judgement: it reports facts, and it executes what it is told. When a
6
- # behaviour is wrong, the question is then 'was the fact wrong or the table wrong', and those
7
- # live in different files with different tests.
8
- #
9
- # WHAT THIS FILE REFUSES TO DO, because the stance predates the code:
10
- # * no SendInput / keybd_event / mouse_event -- no physical injection, not even as a fallback
11
- # * no forged Alt key to defeat the foreground lock (it works; it also drops the owner's next
12
- # keystroke into whichever window the trick raised)
13
- # * no acting on a window this process did not create, UNLESS it was named as the target by
14
- # hwnd -- and the restore path only ever reverses an activation this process caused
15
- #
16
- # All coordinates crossing this boundary are SCREEN pixels. Client-space conversion happens only
17
- # at the moment a message is posted to a child window, because lParam for WM_LBUTTONDOWN is
18
- # child-relative and getting that wrong clicks the title bar instead of the control.
19
-
20
- Set-StrictMode -Version 2.0
21
-
22
- Add-Type -AssemblyName WindowsBase
23
- Add-Type -AssemblyName UIAutomationClient
24
- Add-Type -AssemblyName UIAutomationTypes
25
-
26
- if (-not ('WpmWin' -as [type])) {
27
- Add-Type -TypeDefinition @'
28
- using System;
29
- using System.Collections.Generic;
30
- using System.Runtime.InteropServices;
31
- using System.Text;
32
- using System.Threading;
33
-
34
- public static class WpmWin
35
- {
36
- [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; }
37
- [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
38
- [StructLayout(LayoutKind.Sequential)] public struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
39
- [StructLayout(LayoutKind.Sequential)] public struct GUITHREADINFO
40
- {
41
- public uint cbSize; public uint flags; public IntPtr hwndActive; public IntPtr hwndFocus;
42
- public IntPtr hwndCapture; public IntPtr hwndMenuOwner; public IntPtr hwndMoveSize;
43
- public IntPtr hwndCaret; public RECT rcCaret;
44
- }
45
-
46
- public delegate bool EnumProc(IntPtr h, IntPtr l);
47
-
48
- [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr l);
49
- [DllImport("user32.dll")] public static extern bool EnumChildWindows(IntPtr parent, EnumProc cb, IntPtr l);
50
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassNameW(IntPtr h, StringBuilder s, int n);
51
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n);
52
- [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
53
- [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
54
- [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
55
- [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
56
- [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
57
-
58
- [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
59
- [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
60
- [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
61
- [DllImport("user32.dll")] static extern bool AttachThreadInput(uint attach, uint to, bool join);
62
- [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
63
- [DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint tid, ref GUITHREADINFO gti);
64
-
65
- [DllImport("user32.dll")] public static extern IntPtr SendMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
66
- [DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
67
-
68
- [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
69
- [DllImport("user32.dll")] public static extern IntPtr ChildWindowFromPointEx(IntPtr h, POINT p, uint flags);
70
- [DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr h, ref POINT p);
71
- [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
72
- [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h, uint flags);
73
-
74
- [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO l);
75
- [DllImport("kernel32.dll")] static extern ulong GetTickCount64();
76
-
77
- // ---- integrity level: the REAL elevated_target check -------------------------------------
78
- // The old comment in Get-WpmFacts said this was deliberately unwired because "a wrong check is
79
- // worse than none". That is still true, which is why the check below is the documented,
80
- // side-effect-free one: OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION) -> GetTokenInformation
81
- // (TokenIntegrityLevel) -> the RID's last sub-authority. No writes, no SeDebug privilege, and
82
- // it degrades to -1 (unknown) on any failure -- unknown is NOT treated as elevated, because
83
- // that would refuse every window the moment a handle read failed, which is the opposite wrong
84
- // check. Unknown instead falls through to the door probe, and a genuinely elevated target then
85
- // simply produces no effect, which the app-side verification reports as unverified.
86
- [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
87
- [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
88
- [DllImport("advapi32.dll")] static extern bool OpenProcessToken(IntPtr p, uint access, out IntPtr tok);
89
- [DllImport("advapi32.dll", SetLastError = true)]
90
- static extern bool GetTokenInformation(IntPtr tok, int cls, IntPtr info, uint len, out uint need);
91
- [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr h);
92
-
93
- const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
94
- const uint TOKEN_QUERY = 0x0008;
95
- const int TokenIntegrityLevel = 25;
96
-
97
- /// <summary>Integrity RID of a pid: 0x1000 low, 0x2000 medium, 0x3000 high, 0x4000 system. -1 = unknown.</summary>
98
- public static long IntegrityOf(uint pid)
99
- {
100
- IntPtr proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
101
- if (proc == IntPtr.Zero) return -1;
102
- try
103
- {
104
- IntPtr tok;
105
- if (!OpenProcessToken(proc, TOKEN_QUERY, out tok)) return -1;
106
- try
107
- {
108
- uint need;
109
- // Two-pass: the SIZE-PROBE call is DOCUMENTED to fail -- it returns FALSE with
110
- // ERROR_INSUFFICIENT_BUFFER and fills `needed`. Treating that false as a dead end
111
- // made every read come back unknown on the first run of test/integrity-probe.ps1,
112
- // which is exactly how a 'wrong check is worse than none' failure looks in the wild:
113
- // the flag stayed false everywhere, so nothing was refused and nothing was claimed.
114
- // The real condition is `needed > 0`, not the return value.
115
- GetTokenInformation(tok, TokenIntegrityLevel, IntPtr.Zero, 0, out need);
116
- if (need == 0) return -1;
117
- IntPtr buf = Marshal.AllocHGlobal((int)need);
118
- try
119
- {
120
- if (!GetTokenInformation(tok, TokenIntegrityLevel, buf, need, out need)) return -1;
121
- // TOKEN_MANDATORY_LABEL { SID_AND_ATTRIBUTES Label }; Label.Sid is at offset 0.
122
- IntPtr sid = Marshal.ReadIntPtr(buf);
123
- if (sid == IntPtr.Zero) return -1;
124
- // SID layout: Revision(1) | SubAuthorityCount(1) | IdentifierAuthority(6) |
125
- // SubAuthority(4*n). The integrity RID is the LAST sub-authority.
126
- //
127
- // GetLengthSid was the first attempt and is NOT used: on this host it returns
128
- // TRUE with length 0 for a SID whose bytes read back correctly (revision 1,
129
- // count 1, authority 0x10, RID 0x2000 = medium) -- a silent contradiction that
130
- // made every read come back unknown. The length is therefore computed from the
131
- // SID's own header, which is the authoritative source anyway. Two wrong
132
- // behaviours this replaced, both discovered only by measuring: trusting the
133
- // size-probe's return value, and trusting GetLengthSid's output.
134
- int rev = Marshal.ReadByte(sid, 0);
135
- int count = Marshal.ReadByte(sid, 1);
136
- if (rev != 1 || count < 1 || count > 15) return -1;
137
- int needed = 8 + 4 * count;
138
- if (needed > (int)need) return -1; // header claims more than the buffer holds
139
- // The integrity RID is the LAST sub-authority.
140
- return (long)BitConverter.ToUInt32(
141
- new byte[] { Marshal.ReadByte(sid, 8 + 4 * (count - 1)),
142
- Marshal.ReadByte(sid, 9 + 4 * (count - 1)),
143
- Marshal.ReadByte(sid, 10 + 4 * (count - 1)),
144
- Marshal.ReadByte(sid, 11 + 4 * (count - 1)) }, 0);
145
- }
146
- finally { Marshal.FreeHGlobal(buf); }
147
- }
148
- finally { CloseHandle(tok); }
149
- }
150
- finally { CloseHandle(proc); }
151
- }
152
-
153
- /// <summary>Whether the target outruns us. Equal integrity is NOT elevated for our purposes.</summary>
154
- public static bool IsElevatedTarget(uint pid)
155
- {
156
- long mine = IntegrityOf((uint)System.Diagnostics.Process.GetCurrentProcess().Id);
157
- long theirs = IntegrityOf(pid);
158
- if (mine < 0 || theirs < 0) return false; // unknown never claims elevated
159
- return theirs > mine;
160
- }
161
-
162
- // ---- overlay support: ex-styles, hotkey, and the cross-thread control board --------------
163
- // WpmCtl is the ONE shared state between the worker's main thread (stdin/protocol/actions)
164
- // and the overlay thread (WPF dispatcher, global hotkey). A PowerShell script variable is
165
- // not visible across runspaces, so a static holder is the honest shape; the bools are
166
- // volatile because the hotkey handler writes them from another thread while actions read
167
- // them mid-flight.
168
- [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr h, int i);
169
- [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr h, int i, int v);
170
- [DllImport("user32.dll")] public static extern bool RegisterHotKey(IntPtr h, int id, uint mods, uint vk);
171
- [DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr h, int id);
172
-
173
- public const int GWL_EXSTYLE = -20;
174
- public const int WS_EX_TOPMOST = 0x00000008;
175
- public const int WS_EX_TRANSPARENT = 0x00000020;
176
- public const int WS_EX_LAYERED = 0x00080000;
177
- public const int WS_EX_NOACTIVATE = 0x08000000;
178
- public const int WM_HOTKEY = 0x0312;
179
- public const int WM_CLOSE = 0x0010;
180
- public const uint MOD_CONTROL = 0x0002;
181
- public const uint MOD_ALT = 0x0001;
182
-
183
- [DllImport("user32.dll", SetLastError=true)] static extern bool SetProcessDPIAware();
184
- [DllImport("user32.dll", SetLastError=true)] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr ctx);
185
-
186
- /// <summary>
187
- /// Declare this process DPI aware, BEFORE any window exists.
188
- /// Why this is not cosmetic: PowerShell starts DPI UNAWARE, so Windows virtualises every
189
- /// coordinate it passes to user32. The engine receives PHYSICAL screen pixels (that is what a
190
- /// click point is), the marker is placed through the same user32 -- and with an unaware process
191
- /// a target of (470,410) rendered the marker at (303,263), exactly /1.5 on this 150% display.
192
- /// Two components, one coordinate space, or the AI cursor points at the wrong place while every
193
- /// style assertion still passes. Must run before any window is created (per-process setting);
194
- /// returns false when the manifest already set it, which is success, not failure.
195
- /// </summary>
196
- public static bool EnsureDpiAware() {
197
- try { SetThreadDpiAwarenessContext(new IntPtr(-4)); } catch { } // PER_MONITOR_AWARE_V2
198
- try { return SetProcessDPIAware(); } catch { return false; }
199
- }
200
-
201
- [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
202
- public const uint SWP_NOZORDER = 0x0004;
203
- public const uint SWP_NOACTIVATE = 0x0010;
204
-
205
- /// <summary>
206
- /// Move a window in PHYSICAL pixels without activating it or changing its z-order.
207
- /// This exists instead of WPF's Window.Left/Top because WPF's units are device independent while
208
- /// every coordinate this product receives from Win32 is physical. Measured on this machine
209
- /// (150% display): setting Left/Top put the marker at (303,263) for a target of (470,410) -- the
210
- /// DIP conversion and the window's actual rendering disagreed by the scale factor, and no amount
211
- /// of matrix arithmetic inside the process fixes a process-wide DPI-awareness mismatch.
212
- /// SetWindowPos takes the same units the caller has, so there is nothing left to guess.
213
- /// </summary>
214
- public static bool MoveNoActivate(IntPtr h, int x, int y, int cx, int cy) {
215
- return SetWindowPos(h, IntPtr.Zero, x, y, cx, cy, SWP_NOZORDER | SWP_NOACTIVATE);
216
- }
217
-
218
- /// <summary>
219
- /// Put THIS window at the top of the topmost band without activating it. Exists for the desktop
220
- /// test arms, which assert facts about a screen point ("WindowFromPoint at the marker returns my
221
- /// base"; "the click lands on my target's button"). A third-party full-screen window -- a video
222
- /// player that went fullscreen while these lines were written (measured live: PotPlayer owned every
223
- /// test point) -- makes WindowFromPoint return the OCCLUDER. When that happens the ENGINE IS RIGHT
224
- /// to refuse: it must never act under a window the caller did not name. What broke is the arm's
225
- /// PREMISE, not the product. Raising the test's OWN window into the topmost band uses the same
226
- /// mechanism the overlay relies on (HWND_TOPMOST + SWP_NOACTIVATE): z-order changes,
227
- /// GetForegroundWindow does not. This is a test-support primitive, NOT a product surface -- there is
228
- /// no reason to let a model topmost-raise arbitrary windows, so no such action exists in
229
- /// tools.json; scripts/raise-topmost.ps1 is the only product-adjacent caller and it is a test
230
- /// helper under scripts/, not exposed through wpm.
231
- /// </summary>
232
- public static bool MakeTopmostNoActivate(IntPtr h) {
233
- // SWP_NOMOVE(0x2) | SWP_NOSIZE(0x1) | SWP_NOACTIVATE(0x10), insert after HWND_TOPMOST(-1).
234
- return SetWindowPos(h, new IntPtr(-1), 0, 0, 0, 0, 0x2u | 0x1u | 0x10u);
235
- }
236
-
237
- /// <summary>Add ex-style bits and return the new value (the trio lives here, once).</summary>
238
- public static int AddExStyles(IntPtr h, int bits) {
239
- int v = GetWindowLong(h, GWL_EXSTYLE);
240
- SetWindowLong(h, GWL_EXSTYLE, v | bits);
241
- return v | bits;
242
- }
243
-
244
- public const int SW_MINIMIZE = 6;
245
- public const int SW_SHOWNA = 8;
246
- public const int SW_RESTORE = 9;
247
-
248
- public static string Cls(IntPtr h) { var s = new StringBuilder(512); GetClassNameW(h, s, s.Capacity); return s.ToString(); }
249
- public static string Txt(IntPtr h) { var s = new StringBuilder(1024); GetWindowTextW(h, s, s.Capacity); return s.ToString(); }
250
- public static string Fg() { return GetForegroundWindow().ToInt64().ToString(); }
251
- public static IntPtr FgHandle() { return GetForegroundWindow(); }
252
- public static string Cursor() { POINT p; GetCursorPos(out p); return p.X + "," + p.Y; }
253
- public static uint PidOf(IntPtr h) { uint p; GetWindowThreadProcessId(h, out p); return p; }
254
-
255
- // One proof sample: cursor x/y, foreground HWND, focused-control HWND, and the age of the last
256
- // PHYSICAL input. Every read is a non-disturbing query (GetCursorPos, GetForegroundWindow,
257
- // GetGUIThreadInfo, GetLastInputInfo change nothing), which is the property that makes it safe to
258
- // call in a tight loop DURING an action -- unlike spawning a fresh PowerShell per poll, which can
259
- // itself steal the foreground and contaminate the measured quantity (src/lib/sampler.mjs).
260
- public static string[] Sample()
261
- {
262
- POINT cp; GetCursorPos(out cp);
263
- IntPtr fg = GetForegroundWindow();
264
- GUITHREADINFO g = new GUITHREADINFO();
265
- g.cbSize = (uint)Marshal.SizeOf(typeof(GUITHREADINFO));
266
- uint pid; uint tid = GetWindowThreadProcessId(fg, out pid);
267
- long focusHwnd = 0;
268
- if (GetGUIThreadInfo(tid, ref g)) focusHwnd = g.hwndFocus.ToInt64();
269
- long age = LastInputAgeMs(); // the one tick-difference calculation; -1 when unreadable
270
- return new string[] {
271
- cp.X.ToString(), cp.Y.ToString(),
272
- fg.ToInt64().ToString(), focusHwnd.ToString(), age.ToString()
273
- };
274
- }
275
- public static IntPtr Root(IntPtr h) { IntPtr r = GetAncestor(h, 2); return r == IntPtr.Zero ? h : r; }
276
-
277
- public static List<long> Children(IntPtr parent)
278
- {
279
- var acc = new List<long>();
280
- EnumChildWindows(parent, delegate (IntPtr h, IntPtr l) { if (IsWindowVisible(h)) acc.Add(h.ToInt64()); return true; }, IntPtr.Zero);
281
- return acc;
282
- }
283
-
284
- // Age of the last physical input, in ms; -1 when the call fails. Callers must treat -1 as
285
- // UNKNOWN rather than as 'idle' -- counting unknown as idle is how a software-caused change
286
- // gets laundered into 'the owner was away'.
287
- public static long LastInputAgeMs()
288
- {
289
- LASTINPUTINFO i = new LASTINPUTINFO();
290
- i.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
291
- if (!GetLastInputInfo(ref i)) return -1;
292
- uint now = (uint)(GetTickCount64() & 0xFFFFFFFF);
293
- return (long)((now - i.dwTime) & 0xFFFFFFFF);
294
- }
295
-
296
- // hwndActive / hwndFocus for the foreground thread. hwndFocus is the CONTROL inside the
297
- // window; that distinction is what makes 'the window came back' testable separately from
298
- // 'the caret came back'.
299
- public static long[] GuiFocusOfForeground()
300
- {
301
- GUITHREADINFO g = new GUITHREADINFO();
302
- g.cbSize = (uint)Marshal.SizeOf(typeof(GUITHREADINFO));
303
- IntPtr fg = GetForegroundWindow();
304
- uint pid; uint tid = GetWindowThreadProcessId(fg, out pid);
305
- if (!GetGUIThreadInfo(tid, ref g)) return new long[] { 0, 0, 0 };
306
- return new long[] { g.hwndActive.ToInt64(), g.hwndFocus.ToInt64(), (long)tid };
307
- }
308
-
309
- // Restore the foreground to a window we previously took it from. Joins the input queue of the
310
- // thread that OWNS THE CURRENT foreground (the documented unlock) rather than of the window
311
- // being restored to -- the earlier failure in this repo was joining the wrong one and
312
- // concluding the door was locked.
313
- public static string RestoreForeground(IntPtr want)
314
- {
315
- IntPtr cur = GetForegroundWindow();
316
- uint pid; uint tid = GetWindowThreadProcessId(cur, out pid);
317
- bool joined = AttachThreadInput(GetCurrentThreadId(), tid, true);
318
- bool ok = false;
319
- try { ok = SetForegroundWindow(want); }
320
- finally { if (joined) AttachThreadInput(GetCurrentThreadId(), tid, false); }
321
- Thread.Sleep(40);
322
- return (ok ? "true" : "false") + "|" + (joined ? "true" : "false") + "|" + GetForegroundWindow().ToInt64();
323
- }
324
-
325
- // Click a child control by POSTING mouse messages inside it. lParam is child-relative, which
326
- // is why the conversion happens here and not at the call site.
327
- public static string MessageClick(IntPtr child, int screenX, int screenY)
328
- {
329
- POINT p = new POINT(); p.X = screenX; p.Y = screenY;
330
- if (!ScreenToClient(child, ref p)) return "convert-failed";
331
- IntPtr lp = (IntPtr)((p.Y * 0x10000) + (p.X & 0xFFFF));
332
- SendMessageW(child, 0x0201, (IntPtr)1, lp);
333
- Thread.Sleep(30);
334
- SendMessageW(child, 0x0202, IntPtr.Zero, lp);
335
- return "ok|" + p.X + "," + p.Y;
336
- }
337
-
338
- public static string MessageText(IntPtr child, string text, bool replace)
339
- {
340
- if (!replace)
341
- {
342
- for (int i = 0; i < text.Length; i++) SendMessageW(child, 0x0102, (IntPtr)text[i], IntPtr.Zero);
343
- return "char|" + text.Length;
344
- }
345
- SendMessageString(child, 0x000C, IntPtr.Zero, text);
346
- return "settext|" + text.Length;
347
- }
348
-
349
- // ---- 0.6.0: reading the value back, and putting the caret somewhere on purpose -------------
350
- // WHY THESE PRIMITIVES DID NOT EXIST BEFORE. The message door only ever SENT; every claim about
351
- // "the field now contains this" was a report of what SendMessage returned, which is a statement
352
- // about delivery, not about the application's state. Measured on 2026-11-23 (findings 8.2) with an
353
- // in-process oracle: on a plain Win32 EDIT that has never held focus, WM_CHAR is INERT -- every
354
- // character is accepted and nothing changes -- while the shipped answer was `reported-by-send`.
355
- // The read is what turns that from a false success into a visible one.
356
- //
357
- // ONE MORE THING THIS FIXED, found by running the syscall instead of trusting the import: the
358
- // previous WM_SETTEXT binding was declared as `SendMessageStrW`, which user32.dll does not export
359
- // (.tmp/_t-sendmessagestrw.ps1: EntryPointNotFoundException, first call, every call). So
360
- // `type` with replace:true threw and surfaced as `action_failed` on EVERY target, and no test in
361
- // the repo exercised it. The entry point is now pinned explicitly, because a marshaller resolves
362
- // the name it is given and an alias that exists in nobody's header is not a name.
363
- [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageW")]
364
- public static extern IntPtr SendMessageString(IntPtr h, uint m, IntPtr w, string l);
365
-
366
- [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageW")]
367
- public static extern IntPtr SendMessageBuffer(IntPtr h, uint m, IntPtr w, [Out()] StringBuilder l);
368
-
369
- // The hang-proof read. A plain SendMessageW(WM_GETTEXT) to a window whose thread is busy blocks
370
- // this worker indefinitely, and a read is never worth wedging the sidecar for: with a budget the
371
- // answer degrades to `unavailable`, which the engine reports instead of inventing.
372
- [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageTimeoutW")]
373
- public static extern IntPtr SendMessageTimeoutBuffer(IntPtr h, uint m, IntPtr w, [Out()] StringBuilder l,
374
- uint flags, uint ms, out IntPtr res);
375
-
376
- [DllImport("user32.dll")] public static extern bool IsWindowEnabled(IntPtr h);
377
-
378
- public const uint WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E;
379
- public const uint WM_CHAR = 0x0102, EM_SETSEL = 0x00B1, EM_GETSEL = 0x00B0;
380
- public const uint SMTO_ABORTIFHUNG = 0x0002;
381
-
382
- /// <summary>WM_GETTEXTLENGTH. A length the CONTROL reports, not a length we computed.</summary>
383
- public static int TextLength(IntPtr h) { return (int)(long)SendMessageW(h, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero); }
384
-
385
- /// <summary>{ok, chars, text} from WM_GETTEXT, sized from the control's own WM_GETTEXTLENGTH.
386
- /// The buffer is deliberately one char LONGER than the reported length: the control writes a
387
- /// terminating NUL into the buffer it is handed, and a measured truncation (a 1000-char buffer
388
- /// against a 5000-char value came back as 999) has to stay visible rather than become the answer.</summary>
389
- public static object[] ReadText(IntPtr h, uint ms)
390
- {
391
- int len = TextLength(h);
392
- if (len < 0) len = 0;
393
- if (len > 65536) len = 65536; // a capped read, reported as truncated downstream
394
- var sb = new StringBuilder(len + 2);
395
- IntPtr res;
396
- IntPtr r = SendMessageTimeoutBuffer(h, WM_GETTEXT, (IntPtr)(len + 1), sb, SMTO_ABORTIFHUNG, ms, out res);
397
- if (r == IntPtr.Zero) return new object[] { false, -1, "" };
398
- int n = (int)(long)res;
399
- string s = sb.ToString();
400
- if (n >= 0 && n <= s.Length) s = s.Substring(0, n);
401
- return new object[] { true, n, s };
402
- }
403
-
404
- /// <summary>{start, end} from EM_GETSEL -- the control's own answer about where a typed
405
- /// character will land, which is what makes an expected-value model computable (findings 8.2).</summary>
406
- public static int[] GetSel(IntPtr h)
407
- {
408
- long r = (long)SendMessageW(h, EM_GETSEL, IntPtr.Zero, IntPtr.Zero);
409
- return new int[] { (int)(r & 0xFFFF), (int)((r >> 16) & 0xFFFF) };
410
- }
411
-
412
- /// <summary>EM_SETSEL. NOTE: -1 is NOT used for `end` -- measured on WinForms EDIT it leaves the
413
- /// selection at 0,0 and the typed character goes to the FRONT (findings 8.2). The caller passes
414
- /// the length it read from the control.</summary>
415
- public static void SetSel(IntPtr h, int a, int b) { SendMessageW(h, EM_SETSEL, (IntPtr)a, (IntPtr)b); }
416
-
417
- /// <summary>
418
- /// Write text through the message door with an explicit caret intention, and report BOTH what was
419
- /// asked for and what the control says its selection now is. The selection is read back rather than
420
- /// echoed because the whole point is that the control, not the caller, decides where text goes:
421
- /// EM_SETSEL(6,6) on a buffer whose WM_GETTEXTLENGTH is 6 came back as 4,4 on a value containing a
422
- /// newline, and an engine that reported the requested pair would have been describing a wish.
423
- /// mode: 'settext' (whole-value replace) | 'char' (per-character, inserted at the reported sel).
424
- /// </summary>
425
- public static object[] MessageTextAt(IntPtr child, string text, bool replace, string caret)
426
- {
427
- if (replace)
428
- {
429
- SendMessageString(child, WM_SETTEXT, IntPtr.Zero, text);
430
- if (caret == "start") SetSel(child, 0, 0);
431
- else if (caret == "end") { int l = TextLength(child); SetSel(child, l, l); }
432
- int[] rs = GetSel(child);
433
- return new object[] { "settext", text.Length, rs[0], rs[1] };
434
- }
435
- int askedStart = -1, askedEnd = -1;
436
- if (caret == "start") { SetSel(child, 0, 0); askedStart = 0; askedEnd = 0; }
437
- else if (caret == "end") { int l = TextLength(child); SetSel(child, l, l); askedStart = l; askedEnd = l; }
438
- int[] sel = GetSel(child);
439
- for (int i = 0; i < text.Length; i++) SendMessageW(child, WM_CHAR, (IntPtr)text[i], IntPtr.Zero);
440
- return new object[] { "char", text.Length, sel[0], sel[1], askedStart, askedEnd };
441
- }
442
-
443
- // ---- 0.5.0: the frame, the virtual screen, and the capture footprint ---------------------
444
- // THE FRAME COMES FROM DWM, NOT FROM GetWindowRect. Measured on this desktop (2026-11-23):
445
- // GetWindowRect returns -8,-8,1928,1040 while DwmGetWindowAttribute(EXTENDED_FRAME_BOUNDS)
446
- // returns 0,0,1920,1032 -- four 8px differences that are the invisible resize shadow. The UIA
447
- // tree MIXES the two spaces (the ROOT element reports the shadow-inclusive rect, its children the
448
- // real one), so any arithmetic that mixes them is 8px wrong and looks right. `screenRect` is
449
- // therefore DWM-only, and the fallback is REPORTED as frame='win32' rather than hidden: an 8px
450
- // offset with no field to explain it is the failure mode this whole change is written against.
451
- [DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int attr, out RECT r, int size);
452
- [DllImport("user32.dll")] static extern int GetSystemMetrics(int i);
453
-
454
- /// <summary>{hr, left, top, right, bottom}. hr==0 means the DWM answer is usable.</summary>
455
- public static long[] DwmFrame(IntPtr h)
456
- {
457
- RECT r;
458
- int hr = DwmGetWindowAttribute(h, 9 /* DWMWA_EXTENDED_FRAME_BOUNDS */, out r, Marshal.SizeOf(typeof(RECT)));
459
- if (hr != 0) return new long[] { hr, 0, 0, 0, 0 };
460
- return new long[] { 0, r.Left, r.Top, r.Right, r.Bottom };
461
- }
462
-
463
- /// <summary>{ok, left, top, right, bottom} from GetWindowRect -- the documented FALLBACK only.</summary>
464
- public static long[] WinRect(IntPtr h)
465
- {
466
- RECT r;
467
- if (!GetWindowRect(h, out r)) return new long[] { 0, 0, 0, 0, 0 };
468
- return new long[] { 1, r.Left, r.Top, r.Right, r.Bottom };
469
- }
470
-
471
- /// <summary>{x, y, width, height} of the virtual screen (all monitors, physical pixels).</summary>
472
- public static int[] VirtualScreen()
473
- {
474
- const int SM_XVIRTUALSCREEN = 76, SM_YVIRTUALSCREEN = 77;
475
- const int SM_CXVIRTUALSCREEN = 78, SM_CYVIRTUALSCREEN = 79;
476
- return new int[] { GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN),
477
- GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN) };
478
- }
479
-
480
- // ---- 0.6.0-B: the cheaper capture, with the SAME semantics as the one it replaces -----------
481
- // WHY. Measured on this host (findings 8.4): the capture is not the bottleneck -- PNG encoding is
482
- // (37-39ms of a ~70ms screenshot). But the capture half still costs 22-33ms through
483
- // Graphics.CopyFromScreen and 16-21ms through a direct BitBlt, so the cheap primitive is taken and
484
- // the encoder is left alone. JPEG (10ms, but it smears text), WIC (158ms, slower), and 24bpp
485
- // (7% smaller) were all measured and all rejected.
486
- //
487
- // WHY THE SOURCE DC IS THE SCREEN AND NOT THE WINDOW. Get-WpmScreenshot has always captured the
488
- // frame RECTANGLE OUT OF THE SCREEN, which is what makes its coordinates the same system a click
489
- // uses and what makes an occluding window appear in the picture (honestly: the picture shows what a
490
- // user would see). Capturing with GetWindowDC/PrintWindow would be a DIFFERENT product -- unoccluded,
491
- // and no longer the screen the coordinates refer to. Equivalence was measured, not assumed: on a
492
- // static scene the two paths give identical size, identical content, 0 max per-channel difference
493
- // over 17388 sampled points, and byte-identical PNGs (findings 8.3). The one difference is reported:
494
- // FromHbitmap yields Format32bppRgb where CopyFromScreen yields Format32bppArgb.
495
- [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleDC(IntPtr dc);
496
- [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr h);
497
- [DllImport("user32.dll")] static extern int ReleaseDC(IntPtr h, IntPtr dc);
498
- [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleBitmap(IntPtr dc, int w, int h);
499
- [DllImport("gdi32.dll")] static extern IntPtr SelectObject(IntPtr dc, IntPtr obj);
500
- [DllImport("gdi32.dll")] static extern bool BitBlt(IntPtr dc, int x, int y, int w, int h,
501
- IntPtr srcDc, int srcX, int srcY, uint rop);
502
- [DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr obj);
503
- [DllImport("gdi32.dll")] static extern bool DeleteDC(IntPtr dc);
504
- const uint SRCCOPY = 0x00CC0020;
505
-
506
- /// <summary>
507
- /// Capture a SCREEN rectangle into a new HBITMAP through BitBlt. Returns IntPtr.Zero with a named
508
- /// reason on ANY failure -- the caller falls back to CopyFromScreen and reports which path it used.
509
- /// Every GDI object created here is released on every path, including the partial ones: a leaked DC
510
- /// in a long-lived worker is the kind of bug that shows up as "the app stopped painting" an hour in.
511
- /// The returned handle is owned by the caller and must be passed to FreeHbitmap.
512
- /// </summary>
513
- public static IntPtr CaptureBitBlt(int x, int y, int w, int h, out string reason)
514
- {
515
- reason = "";
516
- if (w <= 0 || h <= 0) { reason = "empty rectangle " + w + "x" + h; return IntPtr.Zero; }
517
- IntPtr screen = GetDC(IntPtr.Zero);
518
- if (screen == IntPtr.Zero) { reason = "GetDC(NULL) returned no screen DC"; return IntPtr.Zero; }
519
- IntPtr mem = IntPtr.Zero, bmp = IntPtr.Zero, old = IntPtr.Zero;
520
- try
521
- {
522
- mem = CreateCompatibleDC(screen);
523
- if (mem == IntPtr.Zero) { reason = "CreateCompatibleDC failed"; return IntPtr.Zero; }
524
- bmp = CreateCompatibleBitmap(screen, w, h);
525
- if (bmp == IntPtr.Zero) { reason = "CreateCompatibleBitmap failed"; return IntPtr.Zero; }
526
- old = SelectObject(mem, bmp);
527
- if (!BitBlt(mem, 0, 0, w, h, screen, x, y, SRCCOPY)) { reason = "BitBlt refused"; DeleteObject(bmp); return IntPtr.Zero; }
528
- return bmp;
529
- }
530
- finally
531
- {
532
- // `old` is restored before the memory DC goes away, and the screen DC is always released.
533
- if (mem != IntPtr.Zero && old != IntPtr.Zero) SelectObject(mem, old);
534
- if (mem != IntPtr.Zero) DeleteDC(mem);
535
- ReleaseDC(IntPtr.Zero, screen);
536
- }
537
- }
538
-
539
- /// <summary>Release an HBITMAP from CaptureBitBlt. Safe to call after FromHbitmap: that call copies
540
- /// the bits into managed memory, so the native handle has nothing left to alias.</summary>
541
- public static bool FreeHbitmap(IntPtr h) { return h != IntPtr.Zero && DeleteObject(h); }
542
- }
543
- '@
544
- }
545
-
546
- if (-not ('WpmCtl' -as [type])) {
547
- Add-Type -TypeDefinition @'
548
- using System;
549
- public static class WpmCtl {
550
- public static volatile bool Paused = false;
551
- public static volatile bool OverlayOn = false;
552
- public static volatile bool HotkeyOk = false;
553
- // The chord that ACTUALLY registered, not the one the docs promise: on this machine Ctrl+Alt+Q
554
- // is already owned by another app (RegisterHotKey -> 1409, measured in
555
- // scripts/hotkey-availability.ps1, 7/8 other candidates free). A silent fallback would make the
556
- // README's "Ctrl+Alt+Q" untrue with nothing to notice; the real chord is reported instead.
557
- public static string HotkeyLabel = "";
558
- // Marker placement travels through these fields INSTEAD of a cross-thread Dispatcher.Invoke.
559
- // Measured (.tmp/ov-seg.log): Invoke(priority, Action) from the worker's thread cost 1818ms and
560
- // sometimes never returned -- the delegate is a PowerShell scriptblock and the overlay thread is
561
- // already inside Dispatcher.Run(), so the engine has to reach a runspace that is busy. Writing
562
- // three fields costs nothing, and the overlay's own pump applies them from its own thread.
563
- public static volatile int MarkerX = -1;
564
- public static volatile int MarkerY = -1;
565
- public static volatile bool MarkerHide = false;
566
- public static volatile int MarkerSeq = 0; // incremented per request; the pump compares it
567
- // volatile is illegal on long in C# (the compiler rejects it, which is the point: a 64-bit
568
- // read is not guaranteed atomic). The hwnd is written once before any reader exists and read
569
- // as a value, so plain static is honest here; Interlocked would be the answer if it changed.
570
- public static long OverlayHwnd = 0;
571
- public static string Reason = "";
572
- public static object Dispatcher = null; // overlay thread's WPF dispatcher (set by that thread)
573
- public static object Window = null; // the marker window (touched ONLY on its own thread)
574
- public static object Timer = null; // auto-hide timer (same rule)
575
-
576
- // ---- R3 takeover surface (spec.md §2) ------------------------------------------------------
577
- // Same rule as the marker fields: the HUD thread owns the window and reads these; the engine writes
578
- // the request fields. No scriptblock is ever marshalled across the threads.
579
- public static volatile bool HudOn = false;
580
- public static volatile bool TakeoverAbort = false; // HUD button / abort chord / worker abort
581
- public static volatile bool AbortChordOk = false;
582
- // volatile is ILLEGAL on string in C# (like long below): a reference write is atomic, so a plain
583
- // static is the honest declaration and not a weaker one.
584
- public static string HudPhase = "";
585
- public static string HudAction = "";
586
- public static string AbortChordLabel = "";
587
- public static volatile int HudElapsedMs = 0;
588
- public static volatile int HudMaxMs = 0;
589
- public static volatile int HudSeq = 0;
590
- public static volatile int InjectedChars = 0;
591
- public static long HudHwnd = 0;
592
- }
593
- '@
594
- }
595
-
596
- # Before anything can create a window. See EnsureDpiAware: an unaware process virtualises the same
597
- # coordinates the engine uses for clicks, which is how the marker ended up off by the display scale.
598
- $script:WpmDpiAware = [WpmWin]::EnsureDpiAware()
599
-
600
- $script:WpmUia = $null
601
- # ---- 0.5.0 state. Deliberately IN-PROCESS and BOUNDED: a label is only meaningful in the frame that
602
- # printed it, so this holds at most two snapshots (the newest for label references, the previous as a
603
- # sinceSnapId diff base) and at most shotsKeep screenshots. A worker restart empties both, which is
604
- # exactly what makes a stale id a real, reportable condition instead of an unbounded cache.
605
- $script:WpmSnapshots = @()
606
- $script:WpmShots = @{}
607
- $script:WpmSnapSeq = 0
608
- $script:WpmShotSeq = 0
609
- function Get-WpmUiaCached {
610
- # Each pattern type is resolved independently and a missing one is simply absent from the table.
611
- # The first version built the table in one literal, and on this runtime
612
- # [System.Windows.Automation.LegacyIAccessiblePattern] does not exist -- so the constructor threw,
613
- # the table came back empty, every target reported 'no pattern', and the engine refused windows
614
- # that demonstrably had patterns. One optional identifier took the whole engine down because the
615
- # lookup was all-or-nothing. Now a missing type costs only that type.
616
- if (-not $script:WpmUia) {
617
- $t = @{}
618
- $map = @{
619
- invoke = 'System.Windows.Automation.InvokePattern'
620
- value = 'System.Windows.Automation.ValuePattern'
621
- toggle = 'System.Windows.Automation.TogglePattern'
622
- select = 'System.Windows.Automation.SelectionItemPattern'
623
- legacy = 'System.Windows.Automation.LegacyIAccessiblePattern'
624
- range = 'System.Windows.Automation.RangeValuePattern'
625
- }
626
- foreach ($k in $map.Keys) {
627
- try {
628
- # Resolve against the assemblies already loaded by Add-Type -AssemblyName above. Probing
629
- # by assembly-qualified name failed here because the assembly's simple name is not what
630
- # GetType expects, and guessing names is how a resolver turns into a silent 'type not
631
- # found'. Asking the loaded assemblies what they actually contain cannot guess wrong.
632
- $ty = $null
633
- foreach ($asm in [AppDomain]::CurrentDomain.GetAssemblies()) {
634
- try { $ty = $asm.GetType($map[$k]); } catch { $ty = $null }
635
- if ($ty) { break }
636
- }
637
- if ($ty) {
638
- # Pattern is a public static FIELD on these classes, not a property. Asking only for a
639
- # property returned $null for every pattern and produced 'no identifiers resolved' -- the
640
- # same shape of mistake as reading an empty field as evidence.
641
- $v = $null
642
- $pr = $ty.GetProperty('Pattern')
643
- if ($pr) { $v = $pr.GetValue($null) }
644
- if (-not $v) {
645
- $fl = $ty.GetField('Pattern')
646
- if ($fl) { $v = $fl.GetValue($null) }
647
- }
648
- if ($v) { $t[$k] = $v }
649
- }
650
- } catch { }
651
- }
652
- if ($t.Count -eq 0) { throw 'no UIA pattern identifiers resolved; the automation client is unusable' }
653
- $script:WpmUia = $t
654
- }
655
- return $script:WpmUia
656
- }
657
-
658
- function Test-WpmUiaTreeHasContent([IntPtr]$Hwnd, [int]$MaxElements = 200) {
659
- <#
660
- Does this target's accessibility tree contain ANY content element, or is it shell only?
661
- Returns $true when at least one element carries a content control type, $false when the
662
- walked tree is only structural chrome, and $false when the walk itself cannot run (a walk
663
- that failed must not be reported as "measured empty" -- the caller distinguishes that world
664
- through the probe error, not through this answer).
665
-
666
- WHY CONTENT, NOT COUNT. "The tree is empty" cannot mean Count == 0: a Chromium window with
667
- renderer accessibility off still exposes ONE shell element -- the Chrome_RenderWidgetHostHWND
668
- pane ("Chrome Legacy Window") -- so uTools measures raw=1 while carrying zero drivable
669
- content, and the same window measured raw=0 earlier the same day depending on its own state.
670
- What never changed across every re-read was the CONTENT count: 0 for the a11y-off window,
671
- hundreds for the a11y-on ones (DSH 514 at census time, 1019 later; ZCode 497). The stable
672
- boundary is structural, not numeric: shell types (Pane/Group/Image/Text/Thumb/Separator/
673
- TitleBar) are the window's own chrome; anything else -- Button, Edit, Document, Custom --
674
- is something an application chose to expose. Custom counts as content deliberately: it may
675
- be undrivable, but calling it "empty" would claim the app has a11y off, and a wrong
676
- uia_tree_empty is a worse lie than an honest unreachable.
677
-
678
- Measured on 2026-11-21 (see scripts/uia-tree-content.ps1, which reads the same two counters
679
- with the same shell list). This is also why NO retry/polling exists for a tree that answers
680
- empty: three in-place reads over 2.2s produced zero content elements every time -- there is
681
- nothing to wait for. The switch is launch-time: --force-renderer-accessibility.
682
- #>
683
- try {
684
- $rootEl = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
685
- $all = $rootEl.FindAll([System.Windows.Automation.TreeScope]::Descendants,
686
- [System.Windows.Automation.Condition]::TrueCondition)
687
- $n = [Math]::Min($all.Count, $MaxElements)
688
- for ($i = 0; $i -lt $n; $i++) {
689
- $t = ''
690
- try { $t = $all[$i].Current.ControlType.ProgrammaticName -replace 'ControlType\.', '' } catch { continue }
691
- if (@('Pane', 'Group', 'Image', 'Text', 'Thumb', 'Separator', 'TitleBar') -notcontains $t) { return $true }
692
- }
693
- return $false
694
- } catch {
695
- return $false
696
- }
697
- }
698
-
699
- function Get-WpmFamily([IntPtr]$Hwnd, [string]$Cls) {
700
- # Family decides which door is even possible, so it is measured from the class name rather than
701
- # guessed from the title: a title is the user's text, a class is the toolkit's identity.
702
- if ($Cls -like 'CASCADIA_HOSTING_WINDOW_CLASS*') { return 'terminal' }
703
- if ($Cls -like 'WindowsForms10*') { return 'winforms' }
704
- if ($Cls -like 'HwndWrapper*') { return 'wpf' }
705
- if ($Cls -eq 'ApplicationFrameWindow' -or $Cls -eq 'Windows.UI.Core.CoreWindow') { return 'uwp' }
706
- if ($Cls -like 'Chrome_WidgetWin*') { return 'chromium' }
707
- if ($Cls -like 'Edit' -or $Cls -like 'RichEdit*' -or $Cls -eq '#32770') { return 'win32-classic' }
708
- return 'unknown'
709
- }
710
-
711
- function Resolve-WpmUiaElementAtPoint {
712
- <#
713
- WHICH UIA ELEMENT SITS UNDER A SCREEN POINT -- the UIA twin of Resolve-WpmChildAtPoint.
714
-
715
- WHY THIS EXISTS. The UIA tier used to take the FIRST descendant carrying any usable pattern and
716
- invoke that, while the contract (src/schema/tools.json) says x/y are REQUIRED and that a point
717
- which does not resolve inside the target is refused "instead of being sent somewhere else". On a
718
- target with no message door -- WPF, UWP, WinUI3, i.e. most modern apps -- 'click 500,300' would
719
- therefore Invoke whichever control happened to come first in tree order and return ok:true. That
720
- is not a refusal, it is a wrong action reported as a right one, and it also breaks the marker's
721
- promise (the marker is drawn at the requested point, which was then not the point acted on).
722
-
723
- THE WALK-UP. AutomationElement.FromPoint returns the DEEPEST element at the point, which for a
724
- button is usually its text child; the Invoke pattern lives on the ancestor. So the search climbs
725
- from the hit element towards the target root and takes the nearest ancestor that has a usable
726
- pattern. Climbing stops at the target's own root element: beyond it lies the caller's other
727
- windows, and acting there would be acting on a window nobody named.
728
-
729
- ANCESTRY IS PROVEN, NOT ASSUMED. If the climb reaches a null parent without meeting the target
730
- root, the point belongs to a different window and the answer is a refusal -- the same rule the
731
- message tier enforces with Root(hit) -ne Hwnd.
732
- #>
733
- param([IntPtr]$Hwnd, [int]$X, [int]$Y)
734
-
735
- $out = @{ element = $null; patternKind = 'none'; err = ''; atPoint = $false; reason = '' }
736
- try {
737
- $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
738
- if (-not $root) { $out.err = 'target window has no UIA element'; $out.reason = 'target element unavailable'; return $out }
739
-
740
- $pt = New-Object System.Windows.Point([double]$X, [double]$Y)
741
- $hitEl = [System.Windows.Automation.AutomationElement]::FromPoint($pt)
742
- if (-not $hitEl) { $out.reason = 'nothing at that point is exposed to UI Automation'; return $out }
743
- $out.atPoint = $true
744
-
745
- # ANCESTRY FIRST, PATTERN SECOND. The first version of this function searched for a pattern
746
- # while climbing and returned the moment it found one -- which re-created the very bug it was
747
- # written to kill, one level down: a click at a point OUTSIDE the target climbed into the
748
- # taskbar, found a patterned button there, invoked it, and reported ok:true. Caught by the
749
- # 'point outside the target' arm of test/uia-click-truth.mjs. The order is the invariant:
750
- # prove the point belongs to THIS window, and only then ask what at the point can be driven.
751
- $walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker
752
- $path = @()
753
- $el = $hitEl
754
- $sawRoot = $false
755
- $hop = 0
756
- while ($el -and $hop -lt 24) {
757
- if ($el -eq $root) { $sawRoot = $true; break }
758
- $path += $el
759
- try { $el = $walker.GetParent($el) } catch { $el = $null }
760
- $hop++
761
- }
762
- if ($el -eq $root) { $sawRoot = $true }
763
-
764
- if (-not $sawRoot) {
765
- # The climb ended without meeting the target root: the point is in another window, and
766
- # acting there would be acting on a window nobody named.
767
- $out.element = $null
768
- $out.patternKind = 'none'
769
- $out.reason = 'the element under that point does not belong to the target window'
770
- return $out
771
- }
772
-
773
- $pats = Get-WpmUiaCached
774
- foreach ($node in $path) {
775
- foreach ($k in @('invoke', 'value', 'toggle', 'select', 'legacy')) {
776
- if (-not $pats.ContainsKey($k)) { continue }
777
- $obj = $null
778
- $has = $false
779
- try { $has = $node.TryGetCurrentPattern($pats[$k], [ref]$obj) } catch { $has = $false; $obj = $null }
780
- if ($has -and $obj) { $out.element = $node; $out.patternKind = $k; return $out }
781
- }
782
- }
783
- $out.reason = 'the element under that point exposes no usable UIA pattern'
784
- return $out
785
- } catch {
786
- $out.err = $_.Exception.Message
787
- $out.reason = 'the point probe threw'
788
- return $out
789
- }
790
- }
791
-
792
- function Get-WpmFacts {
793
- <#
794
- Measure a target's doors. Returns the hashtable decide.ps1 consumes, plus the raw handles the
795
- executor needs. Cached per hwnd because UIA enumeration costs hundreds of ms and a batch of 50
796
- clicks must not pay it 50 times -- but the cache is keyed on hwnd AND invalidated by the caller
797
- when the window set changes, never assumed fresh.
798
- #>
799
- param([IntPtr]$Hwnd, [string]$Action = 'click', [string]$ElementName = '', [int]$X = -1, [int]$Y = -1, [switch]$NoCache)
800
-
801
- $cls = [WpmWin]::Cls($Hwnd)
802
- $fam = Get-WpmFamily $Hwnd $cls
803
- $kids = @([WpmWin]::Children($Hwnd))
804
- $childHandles = @()
805
- $doorKinds = @()
806
- $doorHandles = @()
807
- foreach ($k in $kids) {
808
- $kh = [IntPtr]$k
809
- $kc = [WpmWin]::Cls($kh)
810
- # WinForms child classes are NOT 'Edit'/'Button': they are
811
- # WindowsForms10.EDIT.app.0.<hash>_rN_adN / .BUTTON. / .RichEdit20W.
812
- # and the old exact-ish match ('Edit', 'Button') never hit one of those -- the message door
813
- # silently did not exist on the one toolkit where it demonstrably works, and the engine
814
- # reported WinForms as `unreachable`. Found end-to-end by test/llm-action-battery.mjs; the
815
- # census scripts had their own matching and never exercised this path. The base class is the
816
- # segment after the `WindowsForms10.` prefix, taken before the next dot.
817
- $base = $kc
818
- if ($kc -like 'WindowsForms10.*') { $base = (($kc -split '\.')[1]) }
819
- $kind = ''
820
- if ($base -like 'Edit*' -or $base -like 'RichEdit*' -or $kc -like '*TextBox*') { $kind = 'text' }
821
- elseif ($base -like 'BUTTON*' -or $base -like 'Button*' -or $kc -eq 'ComboBox') { $kind = 'click' }
822
- if ($kind) {
823
- $doorKinds += $kind
824
- $childHandles += $kh
825
- $doorHandles += @{ kind = $kind; hwnd = $kh }
826
- }
827
- }
828
-
829
- # An element named by the caller always gets a UIA probe, even when a message door exists: the
830
- # door tiers address a whole window, so 'click the Save button' cannot be expressed in them
831
- # without coordinates. Naming an element is how a caller asks for a specific control instead of
832
- # whichever one happens to be found first -- and 'first found' is not a contract, it is an
833
- # accident of tree order that changes between app versions.
834
- $hasPattern = $false
835
- $patKind = 'none'
836
- $uiaElement = $null
837
- $uiaErr = ''
838
- $uiaReason = ''
839
- $scanProbed = $false
840
-
841
- # A CLICK WITH COORDINATES IS RESOLVED AT THE POINT, never by tree order. See
842
- # Resolve-WpmUiaElementAtPoint for what went wrong before this: the first descendant carrying a
843
- # pattern was invoked regardless of x/y, so an unnamed click on a WPF/UWP/WinUI target acted on a
844
- # control the caller never pointed at -- and answered ok:true. Naming an element (ElementName) is
845
- # a different contract: there the caller asked for that control, so tree scan is correct.
846
- $pointResolved = $false
847
- if ($doorKinds.Count -eq 0 -and -not $ElementName -and $Action -eq 'click' -and $X -ge 0 -and $Y -ge 0) {
848
- $pr = Resolve-WpmUiaElementAtPoint -Hwnd $Hwnd -X $X -Y $Y
849
- $uiaErr = $pr.err
850
- $uiaReason = $pr.reason
851
- $pointResolved = $true
852
- if ($pr.element) {
853
- $hasPattern = $true
854
- $patKind = $pr.patternKind
855
- $uiaElement = $pr.element
856
- }
857
- } elseif ($doorKinds.Count -eq 0 -or $ElementName) {
858
- $scanProbed = $true
859
- try {
860
- $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
861
- $cond = New-Object System.Windows.Automation.PropertyCondition(
862
- [System.Windows.Automation.AutomationElement]::IsEnabledProperty, $true)
863
- $found = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants, $cond)
864
- $pats = Get-WpmUiaCached
865
- $limit = [Math]::Min($found.Count, 200)
866
- for ($i = 0; $i -lt $limit; $i++) {
867
- $el = $found[$i]
868
- if ($ElementName) {
869
- # Match on Name or AutomationId. The two are different fields: Name is the visible label
870
- # (localised, may change), AutomationId is the developer's id (stable). Accepting either
871
- # keeps the caller from having to know which one a given app populates.
872
- $nm = ''; $aid = ''
873
- try { $nm = [string]$el.Current.Name } catch { }
874
- try { $aid = [string]$el.Current.AutomationId } catch { }
875
- if ($nm -ne $ElementName -and $aid -ne $ElementName) { continue }
876
- }
877
- foreach ($k in @('invoke', 'value', 'toggle', 'select', 'legacy')) {
878
- if (-not $pats.ContainsKey($k)) { continue }
879
- $obj = $null
880
- try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
881
- if ($obj) { $hasPattern = $true; $patKind = $k; $uiaElement = $el; break }
882
- }
883
- if ($hasPattern) { break }
884
- }
885
- } catch {
886
- # NOT swallowed. A silent catch here made the probe report 'no pattern' on a target that
887
- # demonstrably had one, and the engine then refused a perfectly reachable window -- with no
888
- # diagnostic anywhere. The error travels out with the facts so a refusal can say why.
889
- $uiaErr = $_.Exception.Message
890
- }
891
- }
892
-
893
- # EMPTY TREE vs PATTERN-LESS CONTENT, measured rather than folded into one word. When the UIA
894
- # probe ran and found nothing usable, two different worlds produce the same hasPattern=false:
895
- # a tree that was never populated (the app has a11y off -- uTools walks to one shell Pane and
896
- # zero content elements, and no amount of re-querying changes that), and a tree that is alive
897
- # but offers nothing at the named point or element (ZCode/DSH walk to hundreds of elements).
898
- # They get different refusal codes (decide.ps1), so this measurement runs only when the probe
899
- # actually ran -- never to decorate a target whose message door already decided the route.
900
- $uiaTreeEmpty = $false
901
- # THE DIAGNOSIS ONLY APPLIES TO A WINDOW THAT HAS NO OTHER DOOR. This condition used to be just
902
- # "the probe ran and found no pattern", which mislabels a whole class of target: name an element on a
903
- # WinForms window and `engine.ps1` suppresses its message door (a window message cannot address "the
904
- # control called X"), the UIA scan then finds nothing drivable, and the engine reported
905
- # `uia_tree_empty` -- "the application has accessibility switched off, relaunch it with
906
- # --force-renderer-accessibility". That advice is not merely useless for WinForms, it is WRONG about
907
- # the cause: the window demonstrably has a real door, we shut it ourselves. Measured 2026-11-23: the
908
- # WinForms positive control walks to three Panes carrying the controls' own names and automation ids
909
- # through the MSAA bridge (content=0, so `Test-WpmUiaTreeHasContent` says "no content"), while the
910
- # genuine a11y-off sample (uTools) and a bare desktop shell have the same shape -- so the tree alone
911
- # cannot separate them. The door CAN: a target we measured a door on must not be diagnosed as
912
- # accessibilty-off, whatever its tree looks like. Doors present => the honest code is `unreachable`
913
- # ("nothing addressable at that name"), which points at a next step that exists.
914
- if (-not $hasPattern -and ($pointResolved -or $scanProbed) -and ($doorKinds.Count -eq 0)) {
915
- $uiaTreeEmpty = -not (Test-WpmUiaTreeHasContent $Hwnd)
916
- }
917
-
918
- # Elevation is now measured, not assumed. WpmWin::IsElevatedTarget compares the target's
919
- # integrity RID against ours; a failure to read either side returns false rather than guessing,
920
- # because guessing 'elevated' would refuse every window whose handle read failed. The flag is
921
- # consumed by decide.ps1's table, which checks it BEFORE any capability -- so an elevated target
922
- # is refused outright and never probed for doors it cannot answer.
923
-
924
- $tpid = [WpmWin]::PidOf($Hwnd)
925
- $elevated = [WpmWin]::IsElevatedTarget($tpid)
926
-
927
- $facts = New-WpmFacts -Hwnd ($Hwnd.ToInt64().ToString()) -Family $fam `
928
- -MessageDoor ($doorKinds.Count -gt 0) -HasPattern $hasPattern -PatternKind $patKind `
929
- -Action $Action -FactsMeasured $true -ElevatedTarget $elevated `
930
- -UiaTreeEmpty $uiaTreeEmpty -UiaProbeFailed ($uiaErr -ne '')
931
-
932
- return @{
933
- facts = $facts
934
- cls = $cls
935
- family = $fam
936
- childHandles = $childHandles
937
- doorHandles = $doorHandles
938
- doorKinds = @($doorKinds | Sort-Object -Unique)
939
- uiaElement = $uiaElement
940
- uiaErr = $uiaErr
941
- # Why there is no element, when there is none. Previously uiaErr was produced and then read by
942
- # nobody (grep found zero consumers), so a point that resolved outside the target and a target
943
- # whose tree cannot be walked at all reached the caller as the same sentence: 'no message door
944
- # and no usable UIA pattern'. Two different worlds, one string -- and the fixes differ.
945
- uiaReason = $uiaReason
946
- # The two booleans that decide.ps1 splits 'unreachable' on travel INSIDE $facts, built through
947
- # the typed constructor above -- deliberately NOT duplicated here. A second copy of a measured
948
- # value in the same return object is the two-copies-drift bug this repo keeps meeting; the
949
- # first live-instance run of this very change caught exactly that shape (facts said False
950
- # while the raw measurement said True, because the constructor call had not been extended).
951
- pointResolved = $pointResolved
952
- pid = [WpmWin]::PidOf($Hwnd)
953
- }
954
- }
955
-
956
- function Get-WpmFocusEntry {
957
- # The focus table entry required by R2'.4: foreground HWND, the control that holds focus, and the
958
- # owning thread id (needed for the input-queue join). Keyed by HWND, never by pid: on this
959
- # desktop ApplicationFrameHost owns every UWP frame, so pid both misses the target's own
960
- # CoreWindow and blames unrelated apps.
961
- $g = [WpmWin]::GuiFocusOfForeground()
962
- $fg = [WpmWin]::FgHandle()
963
- return @{
964
- fgHwnd = $fg.ToInt64().ToString()
965
- fgPid = ([WpmWin]::PidOf($fg)).ToString()
966
- activeHwnd = ([IntPtr]$g[0]).ToInt64().ToString()
967
- focusHwnd = ([IntPtr]$g[1]).ToInt64().ToString()
968
- threadId = $g[2]
969
- lastInputAgeMs = [WpmWin]::LastInputAgeMs()
970
- }
971
- }
972
-
973
- function Restore-WpmFocus {
974
- <#
975
- Put the foreground back, honouring the restore table. Returns the table's verdict plus what the
976
- syscall actually did, so 'we decided to restore' and 'it worked' stay separate numbers.
977
- #>
978
- param([hashtable]$Entry, [string]$RaisedHwnd, [string]$TargetPid, [string]$RaisedElsewhere = '', [bool]$AlreadyRestored = $false)
979
-
980
- # The foreground moved to a window that is NOT our target. That is never ours to reverse: either
981
- # the target app opened its own window (a dialog, same pid) or a third party took the focus.
982
- # This branch has to come first. An earlier version set RaisedHwnd to whatever held the
983
- # foreground after the action, so a dialog launched by the action looked like "our raised window"
984
- # and got restored away -- the exact failure R2'.6 exists to prevent, caught by the measurement
985
- # rather than by review.
986
- if ($RaisedElsewhere -and -not $RaisedHwnd) {
987
- $ep = [WpmWin]::PidOf([IntPtr][int64]$RaisedElsewhere)
988
- if ($TargetPid -and ("$ep" -eq "$TargetPid")) {
989
- return @{ restore = $false; outcome = 'skip-dialog'; setFg = ''; joined = ''; fgAfter = $RaisedElsewhere
990
- reason = 'the target app opened this window itself (same pid); restoring would close the dialog it just opened' }
991
- }
992
- return @{ restore = $false; outcome = 'skip-taken'; setFg = ''; joined = ''; fgAfter = $RaisedElsewhere
993
- reason = 'a third-party window holds the foreground; never pull it from the owner' }
994
- }
995
-
996
- $cur = [WpmWin]::FgHandle()
997
- $verdict = Get-WpmRestoreDecision -CurrentFg ($cur.ToInt64().ToString()) -RaisedHwnd $RaisedHwnd `
998
- -TargetPid $TargetPid -CurrentFgPid ([WpmWin]::PidOf($cur)).ToString() `
999
- -RaisedHappened ([bool]($RaisedHwnd -ne '')) -AlreadyRestored $AlreadyRestored
1000
-
1001
- $res = @{ restore = $verdict.restore; outcome = $verdict.outcome; reason = $verdict.reason
1002
- setFg = ''; joined = ''; fgAfter = '' }
1003
-
1004
- if ($verdict.restore -and $Entry -and $Entry.fgHwnd) {
1005
- $want = [IntPtr][int64]$Entry.fgHwnd
1006
- if ([WpmWin]::IsWindow($want)) {
1007
- $r = [WpmWin]::RestoreForeground($want)
1008
- $parts = $r.Split('|')
1009
- $res.setFg = $parts[0]; $res.joined = $parts[1]; $res.fgAfter = $parts[2]
1010
- } else {
1011
- # The window we would restore to no longer exists. Nothing legal is left to do: this process
1012
- # may not move the owner's focus to a window it does not own, and the target window belongs
1013
- # to another process. Reported so the caller can surface it instead of pretending.
1014
- $res.outcome = 'skip-vanished'; $res.reason = 'the window that held focus before the action no longer exists'
1015
- }
1016
- }
1017
- return $res
1018
- }
1019
-
1020
- # ==================================================================================================
1021
- # 0.6.0 INPUT RELIABILITY: the read-back primitive, expressed as the fact it is and not as a verdict.
1022
- # ==================================================================================================
1023
-
1024
- function Read-WpmControlText {
1025
- <#
1026
- What the CONTROL says it holds, through WM_GETTEXT. Returns the control's own three numbers plus one
1027
- derived flag, and the derivation is stated because it is the whole safety property of the feature:
1028
-
1029
- exposesText = NOT (chars == 0 AND length > 0)
1030
-
1031
- Measured 2026-11-23 on an ES_PASSWORD edit (findings 8.1): WM_GETTEXT returns an EMPTY string while
1032
- WM_GETTEXTLENGTH returns the real length. That combination cannot mean "the field is empty" -- the
1033
- control is reporting a length it refuses to spell out. Treating it as "empty, and therefore my write
1034
- did not land" would be wrong twice over: it would report a mismatch that did not happen, and if the
1035
- engine had tried to be cleverer and print what it read, a password field is exactly where printing a
1036
- value stops being a diagnostic. So the read is reported as UNAVAILABLE, no text is carried anywhere,
1037
- and the effect keeps the value the write itself earned.
1038
- #>
1039
- param([IntPtr]$Hwnd, [int]$TimeoutMs = 200)
1040
- $length = -1
1041
- try { $length = [WpmWin]::TextLength($Hwnd) } catch { }
1042
- $r = [WpmWin]::ReadText($Hwnd, [uint32][Math]::Max(1, $TimeoutMs))
1043
- $okRead = [bool]$r[0]
1044
- $chars = [int]$r[1]
1045
- $text = [string]$r[2]
1046
- return @{
1047
- ok = $okRead; chars = $chars; text = $text; length = $length
1048
- exposesText = ($okRead -and -not ($chars -eq 0 -and $length -gt 0))
1049
- truncated = ($okRead -and $length -gt 0 -and $chars -lt $length)
1050
- reason = if (-not $okRead) { 'the timed read failed (target not answering within the budget)'
1051
- } elseif ($chars -eq 0 -and $length -gt 0) { 'the control reports a length but no text (password-masked or equivalent)'
1052
- } else { '' }
1053
- }
1054
- }
1055
-
1056
- # ==================================================================================================
1057
- # 0.7.0 DESKTOP CAPABILITIES: launch, clipboard, window. Three actions the product could not do
1058
- # before, and none of them is a door: they take no target's message queue, choose no channel, and
1059
- # produce no proof window -- so they live BESIDE Invoke-WpmAction rather than inside it. The door
1060
- # discipline (point ownership, the restore table, the proof window) is not widened by any of this.
1061
- # ==================================================================================================
1062
-
1063
- function Start-WpmApp {
1064
- <#
1065
- Launch a program. The HOST half is what decides whether this may run at all (appLaunchAllowed and
1066
- the exact-name whitelist, lib/index.js); by the time this function is reached the decision is made,
1067
- and this file reports only what the OS did.
1068
-
1069
- Why the return is a pid and NOT a window handle: measured, `Process.Start` returns while the app is
1070
- still loading and MainWindowHandle is 0 (1348 ms cold for notepad). A launch that claimed a window it
1071
- does not have yet would send every follow-up action to hwnd=0, so the window is waited for
1072
- separately, by Wait-WpmAppWindow, and reported honestly when it has not appeared.
1073
- #>
1074
- param([string]$Target, [string[]]$Arguments = @(), [string]$WorkingDirectory = '')
1075
- if (-not $Target) { return @{ ok = $false; reason = 'launch needs a target: an executable path or a resolvable program name' } }
1076
- try {
1077
- $psi = New-Object System.Diagnostics.ProcessStartInfo
1078
- $psi.FileName = $Target
1079
- $psi.UseShellExecute = $true # the documented way a shell start resolves .exe/app paths
1080
- if ($Arguments -and $Arguments.Count -gt 0) {
1081
- $psi.Arguments = ($Arguments -join ' ')
1082
- # The arguments are joined into one command line here. That is what the OS takes; the AUDIT logs
1083
- # them as given, because R1 in the plan says the whitelist cannot make parameters safe, only the
1084
- # record can make a bad one reviewable.
1085
- }
1086
- if ($WorkingDirectory) { $psi.WorkingDirectory = $WorkingDirectory }
1087
- $p = [System.Diagnostics.Process]::Start($psi)
1088
- if (-not $p) { return @{ ok = $false; reason = 'the OS started nothing for this target' } }
1089
- return @{ ok = $true; pid = [int]$p.Id; name = [string]$p.ProcessName;
1090
- fileName = [string]$p.MainModule.FileName; target = $Target }
1091
- } catch {
1092
- # Access denied, missing file, bad working directory. Reported as a failure of THIS action, with the
1093
- # OS's own sentence attached -- not folded into an engine refusal code it does not own.
1094
- return @{ ok = $false; reason = 'start failed: ' + $_.Exception.Message }
1095
- }
1096
- }
1097
-
1098
- function Wait-WpmAppWindow {
1099
- <#
1100
- Poll for the process's first real top-level window, up to `WaitMs`. Two answers, both honest:
1101
- found -> { ok=true; hwnd=...; waitedMs }
1102
- not yet -> { ok=true; hwnd=''; detail='window-not-yet'; waitedMs } -- NOT a failure. The program
1103
- did start; pretending otherwise would make a slow launch look like a dead one, and
1104
- pretending the window exists would send the next action to nothing.
1105
- #>
1106
- param([int]$ProcessId, [int]$WaitMs = 3000)
1107
- $budget = [Math]::Max(0, [Math]::Min(30000, $WaitMs))
1108
- $at = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1109
- $deadline = $at + $budget
1110
- while ($true) {
1111
- $p = $null
1112
- try { $p = Get-Process -Id $ProcessId -ErrorAction Stop } catch { $p = $null }
1113
- if (-not $p) {
1114
- return @{ ok = $false; hwnd = ''; reason = "process $ProcessId is gone"; waitedMs = [int]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $at) }
1115
- }
1116
- $h = [long]$p.MainWindowHandle
1117
- # Refresh: MainWindowHandle is cached on the Process object, and the whole reason this loop exists
1118
- # is that the first read is 0.
1119
- if ($h -le 0) { try { $p.Refresh() } catch { }; $h = [long]$p.MainWindowHandle }
1120
- if ($h -gt 0) {
1121
- return @{ ok = $true; hwnd = $h.ToString(); waitedMs = [int]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $at);
1122
- title = [string]$p.MainWindowTitle }
1123
- }
1124
- $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1125
- if ($now -ge $deadline) {
1126
- return @{ ok = $true; hwnd = ''; detail = 'window-not-yet'; waitedMs = [int]($now - $at);
1127
- note = "the process is running but has published no top-level window within $budget ms; keep polling, or address it by pid"
1128
- }
1129
- }
1130
- Start-Sleep -Milliseconds 50
1131
- }
1132
- }
1133
-
1134
- function Get-WpmClipboard {
1135
- <#
1136
- Read the SYSTEM clipboard. R8 in the plan is the reason this is written carefully: what is in the
1137
- clipboard may be a password or a token the owner copied seconds ago. So:
1138
- * text is capped at 64 KB and a longer payload is TRUNCATED AND SAYING so (`truncated=true`),
1139
- rather than either silently cutting or dumping the whole thing into a model's context;
1140
- * the audit records op/format/length, never the content (lib/index.js owns the audit line);
1141
- * a non-text, non-image clipboard answers `unsupported-format` with the format names it did find
1142
- -- an empty success would be indistinguishable from "the clipboard is empty".
1143
- Requires STA, which the worker already runs under (`powershell.exe -STA`); measured in findings 5.2.
1144
- #>
1145
- param([string]$Format = 'text', [int]$MaxChars = 65536)
1146
- Add-Type -AssemblyName System.Windows.Forms
1147
- $fmt = if ($Format -eq 'image') { 'image' } else { 'text' }
1148
- try {
1149
- if ($fmt -eq 'text') {
1150
- if (-not [System.Windows.Forms.Clipboard]::ContainsText()) {
1151
- return @{ ok = $false; reason = 'the clipboard holds no text'; formats = (Get-WpmClipboardFormats) }
1152
- }
1153
- $t = [System.Windows.Forms.Clipboard]::GetText()
1154
- if ($null -eq $t) { $t = '' }
1155
- $cap = [Math]::Max(1, $MaxChars)
1156
- $truncated = $t.Length -gt $cap
1157
- return @{ ok = $true; format = 'text'; chars = [int]$t.Length; text = $(if ($truncated) { $t.Substring(0, $cap) } else { $t }); truncated = $truncated }
1158
- }
1159
- if (-not [System.Windows.Forms.Clipboard]::ContainsImage()) {
1160
- return @{ ok = $false; reason = 'the clipboard holds no image'; formats = (Get-WpmClipboardFormats) }
1161
- }
1162
- $img = [System.Windows.Forms.Clipboard]::GetImage()
1163
- if (-not $img) { return @{ ok = $false; reason = 'the clipboard claimed an image and returned none' } }
1164
- $dir = Join-Path (Get-WpmDataDir) 'clipboard'
1165
- if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
1166
- $id = 'clip-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1167
- $file = Join-Path $dir ($id + '.png')
1168
- $img.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
1169
- $w = [int]$img.Width; $h = [int]$img.Height
1170
- $img.Dispose()
1171
- return @{ ok = $true; format = 'image'; file = $file; clipId = $id; width = $w; height = $h }
1172
- } catch {
1173
- # The clipboard is owned by whatever app last touched it and can be locked; that is a transient
1174
- # state of the desktop, reported as a failure of this action with the OS's sentence attached.
1175
- return @{ ok = $false; reason = 'clipboard read failed: ' + $_.Exception.Message }
1176
- }
1177
- }
1178
-
1179
- function Get-WpmClipboardFormats {
1180
- # The format NAMES, so a refusal can say what IS there instead of only what is not.
1181
- try {
1182
- $names = @([System.Windows.Forms.Clipboard]::GetDataObject().GetFormats())
1183
- return @($names | ForEach-Object { [string]$_ } | Select-Object -First 12)
1184
- } catch { return @() }
1185
- }
1186
-
1187
- function Set-WpmClipboard {
1188
- <#
1189
- Write the clipboard. `shotId` is accepted for an image so a screenshot can be pushed into the
1190
- clipboard without the caller ever handling the pixels -- the same "the engine does the arithmetic"
1191
- stance as space:"image" for a click. SetDataObject($true) flushes the data so it survives this
1192
- process, which is the documented difference between a clipboard write and a clipboard promise.
1193
- #>
1194
- param([string]$Format = 'text', [string]$Text = '', [string]$ShotId = '')
1195
- Add-Type -AssemblyName System.Windows.Forms
1196
- Add-Type -AssemblyName System.Drawing
1197
- $fmt = if ($Format -eq 'image') { 'image' } else { 'text' }
1198
- try {
1199
- if ($fmt -eq 'text') {
1200
- if (-not $Text) { return @{ ok = $false; reason = 'clipboard write needs text; an empty write is indistinguishable from a clipboard the owner already cleared' } }
1201
- [System.Windows.Forms.Clipboard]::Clear()
1202
- # SetDataObject($value, $true), NOT Flush(): `Flush` is a .NET Core API and this engine's floor is
1203
- # Windows PowerShell 5.1 (= .NET Framework 4.x), where the call does not exist. The first version
1204
- # of this branch threw "Clipboard does not contain a method named 'Flush'" -- a method that exists
1205
- # in the documentation people read and not in the runtime the product targets. The second argument
1206
- # is what makes the data survive this process, which is the whole behaviour being asked for.
1207
- [System.Windows.Forms.Clipboard]::SetDataObject($Text, $true)
1208
- $back = ''
1209
- try { $back = [string][System.Windows.Forms.Clipboard]::GetText() } catch { }
1210
- return @{ ok = $true; format = 'text'; chars = [int]$Text.Length; readbackChars = [int]$back.Length;
1211
- readbackMatches = ($back -ceq $Text) }
1212
- }
1213
- if (-not $ShotId) { return @{ ok = $false; reason = 'clipboard image write needs a shotId (the screenshot to put there) or a file' } }
1214
- if (-not $script:WpmShots.ContainsKey($ShotId)) {
1215
- return @{ ok = $false; stale = $true; reason = "shotId '$ShotId' is not a screenshot this worker still holds" }
1216
- }
1217
- $file = [string]$script:WpmShots[$ShotId].file
1218
- if (-not (Test-Path -LiteralPath $file)) { return @{ ok = $false; reason = "the shot's PNG is no longer on disk: $file" } }
1219
- # The shot's own recorded size travels along, so the engine can compare what the clipboard reports
1220
- # against what was asked. Without it the image write has no prediction to check and would have to
1221
- # claim success from "the clipboard now holds an image", which is a weaker statement than the text
1222
- # path can make.
1223
- $askedW = [int]$script:WpmShots[$ShotId].imageWidth
1224
- $askedH = [int]$script:WpmShots[$ShotId].imageHeight
1225
- $bmp = [System.Drawing.Image]::FromFile($file)
1226
- try {
1227
- [System.Windows.Forms.Clipboard]::Clear()
1228
- [System.Windows.Forms.Clipboard]::SetDataObject($bmp, $true)
1229
- } finally { $bmp.Dispose() }
1230
- $ok = $false; $w = 0; $h = 0
1231
- try {
1232
- if ([System.Windows.Forms.Clipboard]::ContainsImage()) {
1233
- $img = [System.Windows.Forms.Clipboard]::GetImage()
1234
- $w = [int]$img.Width; $h = [int]$img.Height; $img.Dispose(); $ok = $true
1235
- }
1236
- } catch { }
1237
- return @{ ok = $ok; format = 'image'; shotId = $ShotId; file = $file; width = $askedW; height = $askedH;
1238
- readbackWidth = $w; readbackHeight = $h }
1239
- } catch {
1240
- return @{ ok = $false; reason = 'clipboard write failed: ' + $_.Exception.Message }
1241
- }
1242
- }
1243
-
1244
- function Invoke-WpmWindowOp {
1245
- <#
1246
- One op on ONE window named by hwnd, and the verification is the OS's answer about the window, not
1247
- the return value of the call. That distinction is the whole point of this function: ShowWindow and
1248
- SetWindowPos return booleans about the CALL, and every action in this product that reported a call
1249
- instead of a state has eventually turned out to be the lying kind.
1250
- minimize -> IsIconic afterwards (must be true)
1251
- restore -> IsIconic afterwards (must be false)
1252
- move -> GetWindowRect afterwards (left/top must match what was asked)
1253
- resize -> GetWindowRect afterwards (width/height must match, within 2px)
1254
- topmost -> the WS_EX_TOPMOST bit, read back
1255
- `topmost` is the promotion of `MakeTopmostNoActivate`, which shipped as a TEST-SUPPORT primitive
1256
- (its comment says a model should not be able to topmost-raise arbitrary windows). 0.7.0 revisits
1257
- that: it is now reachable, it never activates the window, and the result still reports the ex-style
1258
- it read back -- see findings §5 for the reasoning that changed.
1259
-
1260
- WHAT THIS FUNCTION DELIBERATELY DOES NOT REPORT: the foreground. `restore` activates by definition
1261
- (SW_RESTORE is documented to bring the window up), so "did the owner lose focus" is a question about
1262
- the moment around this call rather than about the state after it -- and engine.ps1 reads
1263
- GetForegroundWindow on both sides and reports the pair, where this function can only see one.
1264
- #>
1265
- param([IntPtr]$Hwnd, [string]$Op, [int]$X = 0, [int]$Y = 0, [int]$Width = 0, [int]$Height = 0)
1266
- if (-not $Hwnd -or -not [WpmWin]::IsWindow($Hwnd)) {
1267
- return @{ ok = $false; refusal = 'no_hwnd'; reason = 'the hwnd does not identify a live window' }
1268
- }
1269
- $before = New-Object 'WpmWin+RECT'
1270
- [void][WpmWin]::GetWindowRect($Hwnd, [ref]$before)
1271
- switch ($Op) {
1272
- 'minimize' {
1273
- [void][WpmWin]::ShowWindow($Hwnd, [WpmWin]::SW_MINIMIZE)
1274
- $iconic = [WpmWin]::IsIconic($Hwnd)
1275
- return @{ ok = $iconic; op = $Op; iconic = $iconic;
1276
- reason = $(if ($iconic) { '' } else { 'ShowWindow(SW_MINIMIZE) returned and the window is still not iconic' }) }
1277
- }
1278
- 'restore' {
1279
- [void][WpmWin]::ShowWindow($Hwnd, [WpmWin]::SW_RESTORE)
1280
- $iconic = [WpmWin]::IsIconic($Hwnd)
1281
- return @{ ok = (-not $iconic); op = $Op; iconic = $iconic;
1282
- reason = $(if ($iconic) { 'the window is still iconic after SW_RESTORE' } else { '' }) }
1283
- }
1284
- 'move' {
1285
- # SWP_NOSIZE(1) | SWP_NOZORDER(4) | SWP_NOACTIVATE(10): a window move that stole the foreground
1286
- # would be exactly the disturbance the rest of this product refuses to cause.
1287
- $ok = [WpmWin]::SetWindowPos($Hwnd, [IntPtr]::Zero, $X, $Y, 0, 0, ([uint32]1 -bor [uint32]4 -bor [uint32]16))
1288
- $r = New-Object 'WpmWin+RECT'
1289
- [void][WpmWin]::GetWindowRect($Hwnd, [ref]$r)
1290
- $moved = ($r.Left -eq $X -and $r.Top -eq $Y)
1291
- return @{ ok = ($ok -and $moved); op = $Op; called = "$X,$Y"; rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)";
1292
- before = "$($before.Left),$($before.Top),$($before.Right),$($before.Bottom)";
1293
- reason = $(if (-not $ok) { 'SetWindowPos was refused' } elseif (-not $moved) { 'the call returned and the window did not land where it was told' } else { '' }) }
1294
- }
1295
- 'resize' {
1296
- $w = [Math]::Max(1, $Width); $h = [Math]::Max(1, $Height)
1297
- $ok = [WpmWin]::SetWindowPos($Hwnd, [IntPtr]::Zero, 0, 0, $w, $h, ([uint32]2 -bor [uint32]4 -bor [uint32]16))
1298
- $r = New-Object 'WpmWin+RECT'
1299
- [void][WpmWin]::GetWindowRect($Hwnd, [ref]$r)
1300
- $cw = $r.Right - $r.Left; $ch = $r.Bottom - $r.Top
1301
- # +-2 px: the window may clamp a size to its own minimum, and a 1px difference between the frame
1302
- # the app asks for and the rect Windows reports is normal, not a lie worth failing the action over.
1303
- $fits = ([Math]::Abs($cw - $w) -le 2) -and ([Math]::Abs($ch - $h) -le 2)
1304
- return @{ ok = ($ok -and $fits); op = $Op; asked = "${w}x${h}"; size = "${cw}x${ch}";
1305
- rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)";
1306
- reason = $(if (-not $ok) { 'SetWindowPos was refused' } elseif (-not $fits) { 'the window came back a different size than was asked (a clamp, not a no-op)' } else { '' }) }
1307
- }
1308
- 'topmost' {
1309
- $ok = [WpmWin]::MakeTopmostNoActivate($Hwnd)
1310
- $ex = [WpmWin]::GetWindowLong($Hwnd, [WpmWin]::GWL_EXSTYLE)
1311
- $isTop = ($ex -band [WpmWin]::WS_EX_TOPMOST) -ne 0
1312
- return @{ ok = ($ok -and $isTop); op = $Op; exStyle = ('0x' + $ex.ToString('X'));
1313
- topmost = $isTop; activated = 'no'
1314
- reason = $(if (-not $isTop) { 'the WS_EX_TOPMOST bit is not set on the window after the call' } else { '' }) }
1315
- }
1316
- default {
1317
- return @{ ok = $false; op = $Op; reason = "unknown window op '$Op'" }
1318
- }
1319
- }
1320
- }
1321
-
1322
- # ==================================================================================================
1323
- # 0.5.0 READ PATHS: a frame the model can read, a picture whose coordinates are DATA, and a preview
1324
- # that answers in text. None of the three writes an input-queue entry or takes the focus.
1325
- # ==================================================================================================
1326
-
1327
- function Get-WpmDataDir {
1328
- # The same base the takeover latch uses (takeover.ps1 Get-WpmTakeoverLatchPath) and the host half
1329
- # (lib/index.js abortLatchPath). One directory to open when something has to be inspected by hand.
1330
- $base = $env:LOCALAPPDATA
1331
- if (-not $base) { $base = [System.IO.Path]::GetTempPath() }
1332
- return (Join-Path $base 'wpm')
1333
- }
1334
-
1335
- function Get-WpmShotsDir {
1336
- $d = Join-Path (Get-WpmDataDir) 'shots'
1337
- if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
1338
- return $d
1339
- }
1340
-
1341
- function Get-WpmFrameRect {
1342
- <#
1343
- ONE frame rule, and the caller cannot silently get the wrong one.
1344
- Returns @{ ok; frame='dwm'|'win32'|'none'; hr; left; top; right; bottom }.
1345
- DWM(9 EXTENDED_FRAME_BOUNDS) is the ONLY source that agrees with the UIA children's coordinate
1346
- space; GetWindowRect is the documented fallback for RDP/Basic-theme hosts where the DWM call
1347
- returns a non-zero hr. Which one was used is a RETURNED FIELD, never a silent substitution.
1348
- #>
1349
- param([IntPtr]$Hwnd)
1350
- $d = [WpmWin]::DwmFrame($Hwnd)
1351
- if ($d[0] -eq 0 -and $d[3] -gt $d[1] -and $d[4] -gt $d[2]) {
1352
- return @{ ok = $true; frame = 'dwm'; hr = 0
1353
- left = [int]$d[1]; top = [int]$d[2]; right = [int]$d[3]; bottom = [int]$d[4] }
1354
- }
1355
- $w = [WpmWin]::WinRect($Hwnd)
1356
- if ($w[0] -eq 1 -and $w[3] -gt $w[1] -and $w[4] -gt $w[2]) {
1357
- return @{ ok = $true; frame = 'win32'; hr = [int]$d[0]
1358
- left = [int]$w[1]; top = [int]$w[2]; right = [int]$w[3]; bottom = [int]$w[4] }
1359
- }
1360
- return @{ ok = $false; frame = 'none'; hr = [int]$d[0]; left = 0; top = 0; right = 0; bottom = 0 }
1361
- }
1362
-
1363
- function Test-WpmFrameInsideRoot {
1364
- <#
1365
- The DECIDABLE frame check. "Every element rect is inside screenRect" was measured to be FALSE on
1366
- real windows -- Chromium/Electron trees report virtualized content far outside the viewport
1367
- (overhangs of 3px, 18px, 287px and 2720px measured here on 2026-11-23), so that rule refuses
1368
- ordinary windows. What holds is narrower and still worth asserting: the frame we CAPTURED must lie
1369
- inside the window's own rect as the accessibility tree reports it (the ROOT element's
1370
- BoundingRectangle, which measures equal to GetWindowRect -- the shadow space). Measured insets on 8
1371
- real windows: exactly 0,0,0,0 (borderless) or 8,8,8,8 (shadowed). A frame that pokes OUTSIDE the
1372
- root means the frame came from somewhere else, and refusing there is what keeps a wrong frame from
1373
- ever becoming a label.
1374
- #>
1375
- param([hashtable]$Frame, [hashtable]$RootRect, [int]$Tolerance = 2)
1376
- $insetL = [int]$Frame.left - [int]$RootRect.left
1377
- $insetT = [int]$Frame.top - [int]$RootRect.top
1378
- $insetR = [int]$RootRect.right - [int]$Frame.right
1379
- $insetB = [int]$RootRect.bottom - [int]$Frame.bottom
1380
- $ok = ($insetL -ge -$Tolerance) -and ($insetT -ge -$Tolerance) -and
1381
- ($insetR -ge -$Tolerance) -and ($insetB -ge -$Tolerance)
1382
- return @{ ok = $ok; insetLeft = $insetL; insetTop = $insetT; insetRight = $insetR; insetBottom = $insetB }
1383
- }
1384
-
1385
- function Get-WpmSnapshotTree {
1386
- <#
1387
- Walk the tree ONCE (FindAll(Descendants) + IsOffscreen), number what is visible, and hand back a
1388
- frame the model can answer with. Measured: 816 descendants / 71 visible / 291ms on an Electron
1389
- window, so TreeWalker (one cross-process COM round trip per node) is the wrong tool here and the
1390
- 300-element cap is deliberately loose.
1391
-
1392
- '0 element(s)' is a REAL answer on this desktop (Clash, Everything measured 0) and is reported as
1393
- such; it deliberately does NOT reuse uia_tree_empty, whose meaning is "UI Automation is switched
1394
- off in the application" and whose next step is relaunching the app.
1395
-
1396
- `interactableOnly` (default on) is the zero-cost first pass at a huge tree. `sinceSnapId` returns
1397
- added/removed/changed instead of re-describing an unchanged table -- the measured cost of a
1398
- multi-step flow is repeating the parts that did not move.
1399
- #>
1400
- param(
1401
- [IntPtr]$Hwnd,
1402
- [int]$MaxElements = 300,
1403
- [bool]$InteractableOnly = $true,
1404
- [string]$Intent = '',
1405
- [string]$SinceSnapId = ''
1406
- )
1407
- $cap = [Math]::Max(1, [Math]::Min(5000, $MaxElements))
1408
-
1409
- # The diff base is resolved BEFORE the walk: an unknown sinceSnapId is a stale reference, not an
1410
- # empty diff. Returning "no changes" for an id we never issued would be the most comfortable lie here.
1411
- $base = $null
1412
- if ($SinceSnapId) {
1413
- foreach ($s in @($script:WpmSnapshots)) {
1414
- if ($s -and $s.snapId -eq $SinceSnapId) { $base = $s; break }
1415
- }
1416
- if (-not $base) {
1417
- return @{ ok = $false; stale = $true
1418
- reason = "sinceSnapId '$SinceSnapId' is not a snapshot this worker still holds (it keeps the newest as a label base and the one before it as a diff base); take a new snapshot and diff against that id" }
1419
- }
1420
- }
1421
-
1422
- $frame = Get-WpmFrameRect $Hwnd
1423
- if (-not $frame.ok) {
1424
- return @{ ok = $false; stale = $false; frameCheck = 'unknown'
1425
- reason = "no usable window frame: DwmGetWindowAttribute hr=$($frame.hr) and GetWindowRect both failed, so there is no rectangle to measure elements against" }
1426
- }
1427
-
1428
- $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1429
-
1430
- # ---- THE DECIDABLE SELF-CHECK ------------------------------------------------------------------
1431
- # The obvious invariant -- "every element rect is contained in screenRect" -- was MEASURED to be
1432
- # false on real windows and is therefore NOT used: Chromium/Electron trees legitimately report
1433
- # virtualized content far outside the viewport (overhangs measured 3px, 18px, 287px and 2720px on
1434
- # this desktop, 2026-11-23), and a rule that refuses those snapshots refuses whole classes of
1435
- # ordinary windows. What IS decidable and cheap is the relationship the two coordinate sources
1436
- # state about the window itself: the ROOT element's rect (the tree's own claim, which measures equal
1437
- # to GetWindowRect -- shadow space) must CONTAIN the frame we captured. Measured on 8 real windows:
1438
- # it holds with insets of exactly 0px (borderless) or 8px/8px/8px/8px (shadowed), and a frame that
1439
- # pokes outside the root means the frame came from somewhere else. The inset is REPORTED as data so
1440
- # the shadow is visible instead of merely survived.
1441
- $frameCheck = 'unknown'
1442
- $insetL = 0; $insetT = 0; $insetR = 0; $insetB = 0
1443
- try {
1444
- $rb = $root.Current.BoundingRectangle
1445
- $rootRect = @{
1446
- left = [int][Math]::Round($rb.Left); top = [int][Math]::Round($rb.Top)
1447
- right = [int][Math]::Round($rb.Right); bottom = [int][Math]::Round($rb.Bottom)
1448
- }
1449
- $inside = Test-WpmFrameInsideRoot -Frame $frame -RootRect $rootRect
1450
- $insetL = [int]$inside.insetLeft; $insetT = [int]$inside.insetTop
1451
- $insetR = [int]$inside.insetRight; $insetB = [int]$inside.insetBottom
1452
- $frameCheck = if ($inside.ok) { 'pass' } else { 'fail' }
1453
- if ($frameCheck -eq 'fail') {
1454
- return @{ ok = $false; stale = $false; frame = $frame.frame; frameCheck = 'fail'
1455
- reason = "frame self-check failed: the captured frame ($($frame.left),$($frame.top),$($frame.right),$($frame.bottom), source=$($frame.frame)) is not contained in the window's own rect ($($rootRect.left),$($rootRect.top),$($rootRect.right),$($rootRect.bottom)) that the accessibility tree reports. The two sources disagree about where this window is, so no label from this snapshot is safe to act on. Re-read action=windows and compare rect= with this frame" }
1456
- }
1457
- } catch {
1458
- # An unreadable root rect cannot certify anything, and it must not be turned into a failure: the
1459
- # snapshot itself may still be useful, so the check reports 'unknown' rather than 'pass'.
1460
- $frameCheck = 'unknown'
1461
- }
1462
-
1463
- $all = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,
1464
- [System.Windows.Automation.Condition]::TrueCondition)
1465
- $total = $all.Count
1466
- $pats = Get-WpmUiaCached
1467
- $order = @('invoke', 'value', 'toggle', 'select', 'legacy')
1468
- $rows = @()
1469
- $truncated = $false
1470
- $outsideFrame = 0
1471
-
1472
- for ($i = 0; $i -lt $total; $i++) {
1473
- $el = $all[$i]
1474
- $off = $false
1475
- try { $off = [bool]$el.Current.IsOffscreen } catch { continue }
1476
- if ($off) { continue }
1477
-
1478
- $ct = ''; $nm = ''; $aid = ''
1479
- try { $ct = ([string]$el.Current.ControlType.ProgrammaticName) -replace '^ControlType\.', '' } catch { continue }
1480
- try { $nm = [string]$el.Current.Name } catch { }
1481
- try { $aid = [string]$el.Current.AutomationId } catch { }
1482
-
1483
- # Sub-element rects are in the DWM/real space (measured); the ROOT element is the one that reports
1484
- # the shadow-inclusive rect, and FindAll(Descendants) never returns the root -- so nothing here
1485
- # mixes the two spaces.
1486
- $rc = @{ left = 0; top = 0; right = 0; bottom = 0 }
1487
- try {
1488
- $b = $el.Current.BoundingRectangle
1489
- $rc = @{
1490
- left = [int][Math]::Round($b.Left); top = [int][Math]::Round($b.Top)
1491
- right = [int][Math]::Round($b.Right); bottom = [int][Math]::Round($b.Bottom)
1492
- }
1493
- } catch { }
1494
-
1495
- # A label exists to be POINTED AT inside the capture. An element with no overlap with the frame
1496
- # cannot be clicked within it (the point-ownership assertion would refuse), so handing out a
1497
- # number for it would hand out a trap. It is excluded and COUNTED, never silently dropped.
1498
- $overlaps = ($rc.right -gt $frame.left) -and ($rc.left -lt $frame.right) -and
1499
- ($rc.bottom -gt $frame.top) -and ($rc.top -lt $frame.bottom)
1500
- if (-not $overlaps) { $outsideFrame++; continue }
1501
-
1502
- $kinds = @()
1503
- foreach ($k in $order) {
1504
- if (-not $pats.ContainsKey($k)) { continue }
1505
- $obj = $null
1506
- try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
1507
- if ($obj) { $kinds += $k }
1508
- }
1509
- if ($InteractableOnly -and $kinds.Count -eq 0) { continue }
1510
-
1511
- if ($rows.Count -ge $cap) { $truncated = $true; break }
1512
-
1513
- $rid = ''
1514
- try { $rid = (@($el.GetRuntimeId()) -join '.') } catch { $rid = '' }
1515
-
1516
- $rows += @{
1517
- label = ($rows.Count + 1)
1518
- controlType = $ct
1519
- name = $nm
1520
- automationId = $aid
1521
- runtimeId = $rid
1522
- rect = $rc
1523
- patterns = @($kinds)
1524
- }
1525
- }
1526
-
1527
- # ---- the delta, by UIA RuntimeId (measured stable across queries, 71/71) --------------------
1528
- $delta = $null
1529
- if ($base) {
1530
- $oldByRid = @{}
1531
- foreach ($r in @($base.elements)) { if ($r.runtimeId) { $oldByRid[$r.runtimeId] = $r } }
1532
- $newByRid = @{}
1533
- foreach ($r in $rows) { if ($r.runtimeId) { $newByRid[$r.runtimeId] = $r } }
1534
- $added = @(); $removed = @(); $changed = @(); $same = 0
1535
- foreach ($r in $rows) {
1536
- if (-not $r.runtimeId) { continue }
1537
- if (-not $oldByRid.ContainsKey($r.runtimeId)) { $added += $r; continue }
1538
- $o = $oldByRid[$r.runtimeId]
1539
- $why = @()
1540
- if ([string]$o.name -ne [string]$r.name) { $why += 'name' }
1541
- if ([string]$o.controlType -ne [string]$r.controlType) { $why += 'controlType' }
1542
- if ([string]$o.automationId -ne [string]$r.automationId) { $why += 'automationId' }
1543
- if (([int]$o.rect.left -ne [int]$r.rect.left) -or ([int]$o.rect.top -ne [int]$r.rect.top) -or
1544
- ([int]$o.rect.right -ne [int]$r.rect.right) -or ([int]$o.rect.bottom -ne [int]$r.rect.bottom)) { $why += 'rect' }
1545
- if ((@($o.patterns) -join ',') -ne (@($r.patterns) -join ',')) { $why += 'patterns' }
1546
- if ($why.Count -gt 0) {
1547
- $changed += @{ label = $r.label; controlType = $r.controlType; name = $r.name
1548
- automationId = $r.automationId; rect = $r.rect; patterns = @($r.patterns); changed = $why }
1549
- } else { $same++ }
1550
- }
1551
- foreach ($o in @($base.elements)) {
1552
- if (-not $o.runtimeId) { continue }
1553
- if (-not $newByRid.ContainsKey($o.runtimeId)) {
1554
- $removed += @{ label = $o.label; controlType = $o.controlType; name = $o.name
1555
- automationId = $o.automationId; rect = $o.rect; patterns = @($o.patterns) }
1556
- }
1557
- }
1558
- $delta = @{ sinceSnapId = $base.snapId; added = @($added); removed = @($removed)
1559
- changed = @($changed); unchanged = $same }
1560
- }
1561
-
1562
- $script:WpmSnapSeq = $script:WpmSnapSeq + 1
1563
- $snapId = 'snap-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + '-' + $script:WpmSnapSeq
1564
- $entry = @{
1565
- snapId = $snapId
1566
- hwnd = $Hwnd.ToInt64().ToString()
1567
- frame = $frame.frame
1568
- frameCheck = $frameCheck
1569
- frameInset = @{ left = $insetL; top = $insetT; right = $insetR; bottom = $insetB }
1570
- intent = $Intent
1571
- createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1572
- total = $total
1573
- count = $rows.Count
1574
- outsideFrame = $outsideFrame
1575
- truncated = $truncated
1576
- elements = @($rows)
1577
- }
1578
- # Newest first. Capacity 2, for one reason each: [0] resolves LABEL references, [1] is the only
1579
- # valid sinceSnapId. Dropping the older one is what makes a superseded snapId a reportable
1580
- # stale_ref instead of a silent success against a frame the caller can no longer see.
1581
- $prev = @($script:WpmSnapshots)
1582
- $script:WpmSnapshots = @($entry) + @($prev | Select-Object -First 1)
1583
-
1584
- # The intent travels WITH the frame as a file too, so a deciding subagent (or a human reading the
1585
- # directory afterwards) gets "what this frame was for" without the conversation around it. One file,
1586
- # overwritten each snapshot: bounded by construction.
1587
- try {
1588
- $dataDir = Get-WpmDataDir
1589
- if (-not (Test-Path -LiteralPath $dataDir)) { New-Item -ItemType Directory -Force -Path $dataDir | Out-Null }
1590
- $payload = $entry | ConvertTo-Json -Depth 8 -Compress
1591
- [System.IO.File]::WriteAllText((Join-Path $dataDir 'last-snapshot.json'), $payload,
1592
- (New-Object System.Text.UTF8Encoding($false)))
1593
- } catch { }
1594
-
1595
- return @{ ok = $true; stale = $false; snapId = $snapId; frame = $frame.frame; frameCheck = $frameCheck
1596
- frameInset = @{ left = $insetL; top = $insetT; right = $insetR; bottom = $insetB }
1597
- intent = $Intent; total = $total; count = $rows.Count; outsideFrame = $outsideFrame
1598
- truncated = $truncated; elements = @($rows); delta = $delta }
1599
- }
1600
-
1601
- function Resolve-WpmSnapshotLabel {
1602
- <#
1603
- Resolve a snapshot LABEL back to the ELEMENT (by UIA RuntimeId), so a labelled action keeps the
1604
- silent UIA-pattern path and never degrades into a coordinate click. Every failure to resolve is a
1605
- stale reference, not a guess: the frame the caller read is gone.
1606
- #>
1607
- param([IntPtr]$Hwnd, [int]$Label, [string]$SnapId)
1608
- $snap = $null
1609
- $all = @($script:WpmSnapshots)
1610
- if ($all.Count -gt 0) { $snap = $all[0] }
1611
- if (-not $snap) {
1612
- return @{ ok = $false; stale = $true; reason = 'no snapshot has been taken by this worker; take one and act on its labels' }
1613
- }
1614
- if ($SnapId -and $SnapId -ne $snap.snapId) {
1615
- return @{ ok = $false; stale = $true
1616
- reason = "snapId '$SnapId' was superseded by '$($snap.snapId)'; a label only means something inside the frame that printed it, so take a new snapshot" }
1617
- }
1618
- if ([string]$snap.hwnd -ne $Hwnd.ToInt64().ToString()) {
1619
- return @{ ok = $false; stale = $true
1620
- reason = "the newest snapshot is of hwnd=$($snap.hwnd), not this target; take a snapshot of this window" }
1621
- }
1622
- $row = $null
1623
- foreach ($r in @($snap.elements)) { if ([int]$r.label -eq $Label) { $row = $r; break } }
1624
- if (-not $row) {
1625
- return @{ ok = $false; stale = $true
1626
- reason = "label $Label is not in snapshot $($snap.snapId) (it printed $($snap.count) element(s))" }
1627
- }
1628
- if (-not $row.runtimeId) {
1629
- return @{ ok = $false; stale = $true
1630
- reason = "label $Label carried no stable runtime id, so it cannot be re-found; take a new snapshot" }
1631
- }
1632
- $el = $null
1633
- try {
1634
- $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1635
- $found = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,
1636
- [System.Windows.Automation.Condition]::TrueCondition)
1637
- for ($i = 0; $i -lt $found.Count; $i++) {
1638
- $cand = $found[$i]
1639
- $rid = ''
1640
- try { $rid = (@($cand.GetRuntimeId()) -join '.') } catch { continue }
1641
- if ($rid -eq $row.runtimeId) { $el = $cand; break }
1642
- }
1643
- } catch {
1644
- return @{ ok = $false; stale = $true; reason = 'the tree could not be re-walked: ' + $_.Exception.Message }
1645
- }
1646
- if (-not $el) {
1647
- return @{ ok = $false; stale = $true
1648
- reason = "the element behind label $Label is no longer in the tree; take a new snapshot" }
1649
- }
1650
- $pats = Get-WpmUiaCached
1651
- $kind = 'none'
1652
- foreach ($k in @('invoke', 'value', 'toggle', 'select', 'legacy')) {
1653
- if (-not $pats.ContainsKey($k)) { continue }
1654
- $obj = $null
1655
- try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
1656
- if ($obj) { $kind = $k; break }
1657
- }
1658
- if ($kind -eq 'none') {
1659
- return @{ ok = $false; stale = $true
1660
- reason = "the element behind label $Label no longer exposes a usable UIA pattern; take a new snapshot" }
1661
- }
1662
- return @{ ok = $true; stale = $false; element = $el; patternKind = $kind; row = $row; snapId = $snap.snapId }
1663
- }
1664
-
1665
- function Get-WpmScreenshot {
1666
- <#
1667
- CopyFromScreen over the DWM frame (or the virtual screen on explicit request) and return the
1668
- MAPPING as data. Why the picture is not returned inline: a plugin cannot mint an inline image
1669
- block without the host's attachment service (measured: ImageBlock needs an ImageAttachmentRef from
1670
- an app.asar-only package), so the file is written and the caller reads it. What this action is
1671
- really for is the second half: `scale`/`identity`/`screenRect` let a caller hand IMAGE coordinates
1672
- back to click space:'image' and never multiply anything itself.
1673
-
1674
- scale = imagePixels / screenPixels. identity is true only when scale==1.0. Nothing is resampled
1675
- unless maxWidth asked for it, because a resized image IS a different coordinate system.
1676
- #>
1677
- param([IntPtr]$Hwnd, [bool]$FullScreen = $false, [int]$MaxWidth = 0, [int]$Keep = 10)
1678
- Add-Type -AssemblyName System.Drawing
1679
-
1680
- if ($FullScreen) {
1681
- $vs = [WpmWin]::VirtualScreen()
1682
- $frame = @{ ok = $true; frame = 'dwm'; hr = 0
1683
- left = [int]$vs[0]; top = [int]$vs[1]; right = ([int]$vs[0] + [int]$vs[2]); bottom = ([int]$vs[1] + [int]$vs[3]) }
1684
- } else {
1685
- $frame = Get-WpmFrameRect $Hwnd
1686
- if (-not $frame.ok) {
1687
- return @{ ok = $false
1688
- reason = "no usable window frame: DwmGetWindowAttribute hr=$($frame.hr) and GetWindowRect both failed" }
1689
- }
1690
- }
1691
-
1692
- $w = $frame.right - $frame.left
1693
- $h = $frame.bottom - $frame.top
1694
- if ($w -le 0 -or $h -le 0) { return @{ ok = $false; reason = "the captured rectangle is empty ($($w)x$($h))" } }
1695
-
1696
- $bmp = $null
1697
- $resized = $null
1698
- $hbmp = [IntPtr]::Zero
1699
- # THE PATH IS REPORTED, NEVER SWAPPED SILENTLY. Same discipline as `frame`: 'dwm' versus 'win32' is a
1700
- # coordinate fact, and 'bitblt' versus 'gdiplus' is a content fact (a 32bppRgb surface instead of
1701
- # 32bppArgb, and any difference in what an occluded window paints). A caller comparing two screenshots
1702
- # has to be able to see that the producer changed, so the field is mandatory in the result.
1703
- $captureBackend = 'gdiplus'
1704
- $captureNote = ''
1705
- try {
1706
- $capReason = ''
1707
- try { $hbmp = [WpmWin]::CaptureBitBlt($frame.left, $frame.top, $w, $h, [ref]$capReason) }
1708
- catch { $hbmp = [IntPtr]::Zero; $capReason = $_.Exception.Message }
1709
- if ($hbmp -ne [IntPtr]::Zero) {
1710
- try {
1711
- $bmp = [System.Drawing.Image]::FromHbitmap($hbmp)
1712
- $captureBackend = 'bitblt'
1713
- } catch {
1714
- # FromHbitmap can refuse (a format it cannot map). That is a capture failure, not a crash, and
1715
- # the fallback below is the documented answer -- an exception here would turn a fast path into a
1716
- # lost screenshot.
1717
- $bmp = $null
1718
- $capReason = 'FromHbitmap: ' + $_.Exception.Message
1719
- } finally {
1720
- [void][WpmWin]::FreeHbitmap($hbmp)
1721
- $hbmp = [IntPtr]::Zero
1722
- }
1723
- }
1724
- if (-not $bmp) {
1725
- $captureNote = "bitblt-unavailable($capReason)"
1726
- $bmp = New-Object System.Drawing.Bitmap($w, $h)
1727
- $g = [System.Drawing.Graphics]::FromImage($bmp)
1728
- try { $g.CopyFromScreen($frame.left, $frame.top, 0, 0, (New-Object System.Drawing.Size($w, $h))) }
1729
- finally { $g.Dispose() }
1730
- $captureBackend = 'gdiplus'
1731
- }
1732
-
1733
- $scale = 1.0
1734
- $imgW = $w
1735
- $imgH = $h
1736
- $out = $bmp
1737
- $cap = [Math]::Max(0, [Math]::Min(7680, $MaxWidth))
1738
- if ($cap -gt 0 -and $w -gt $cap) {
1739
- $imgW = $cap
1740
- $imgH = [int][Math]::Max(1, [Math]::Round($h * ($cap / [double]$w)))
1741
- $resized = New-Object System.Drawing.Bitmap($imgW, $imgH)
1742
- $g2 = [System.Drawing.Graphics]::FromImage($resized)
1743
- try {
1744
- $g2.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
1745
- $g2.DrawImage($bmp, 0, 0, $imgW, $imgH)
1746
- } finally { $g2.Dispose() }
1747
- $out = $resized
1748
- $scale = [Math]::Round($imgW / [double]$w, 6)
1749
- }
1750
-
1751
- $dir = Get-WpmShotsDir
1752
- $script:WpmShotSeq = $script:WpmShotSeq + 1
1753
- $shotId = 'shot-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + '-' + $script:WpmShotSeq
1754
- $file = Join-Path $dir ($shotId + '.png')
1755
- $out.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
1756
- $bytes = (Get-Item -LiteralPath $file).Length
1757
- $keepN = [Math]::Max(1, [Math]::Min(200, $Keep))
1758
-
1759
- # Retention: newest `shotsKeep` survive, older PNGs in THIS directory are deleted. The registry is
1760
- # pruned against the same list, so a shotId that was cleaned up resolves to stale_ref rather than
1761
- # to a file that is no longer there.
1762
- $files = @(Get-ChildItem -LiteralPath $dir -Filter '*.png' -File -ErrorAction SilentlyContinue |
1763
- Sort-Object LastWriteTimeUtc -Descending)
1764
- for ($i = $keepN; $i -lt $files.Count; $i++) {
1765
- try { Remove-Item -LiteralPath $files[$i].FullName -Force } catch { }
1766
- }
1767
- $script:WpmShots[$shotId] = @{
1768
- shotId = $shotId; file = $file; scale = $scale; identity = ($scale -eq 1.0)
1769
- left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom
1770
- imageWidth = [int]$imgW; imageHeight = [int]$imgH; frame = $frame.frame
1771
- captureBackend = $captureBackend
1772
- createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1773
- }
1774
- # Drop registry entries for shots the retention pass just removed.
1775
- $live = @{}
1776
- for ($i = 0; $i -lt [Math]::Min($keepN, $files.Count); $i++) { $live[$files[$i].BaseName] = $true }
1777
- foreach ($key in @($script:WpmShots.Keys)) {
1778
- if (-not $live.ContainsKey($key)) { $script:WpmShots.Remove($key) }
1779
- }
1780
-
1781
- return @{ ok = $true
1782
- shotId = $shotId; file = $file
1783
- screenRect = @{ left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom }
1784
- imageSize = @{ width = [int]$imgW; height = [int]$imgH }
1785
- scale = $scale; identity = ($scale -eq 1.0); frame = $frame.frame
1786
- captureBackend = $captureBackend; captureNote = $captureNote
1787
- dpiAware = [bool]$script:WpmDpiAware; bytes = [long]$bytes; shotsKeep = $keepN
1788
- capturedAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }
1789
- } finally {
1790
- if ($hbmp -ne [IntPtr]::Zero) { [void][WpmWin]::FreeHbitmap($hbmp) }
1791
- if ($resized) { $resized.Dispose() }
1792
- if ($bmp) { $bmp.Dispose() }
1793
- }
1794
- }
1795
-
1796
- function Convert-WpmImagePoint {
1797
- <#
1798
- THE MULTIPLICATION THE MODEL MUST NOT DO. space:'image' + shotId -> a screen point, using the
1799
- scale the screenshot itself reported. screenX = screenRect.left + round(imageX / scale), which is
1800
- the inverse of scale = imagePixels/screenPixels; a shot that was never issued, or one the
1801
- retention policy already deleted, answers ok=false so the caller can report stale_ref instead of
1802
- reinterpreting image pixels as screen pixels.
1803
- #>
1804
- param([string]$ShotId, [int]$X, [int]$Y)
1805
- if (-not $ShotId) { return @{ ok = $false; stale = $true; reason = 'space="image" needs a shotId: image coordinates only exist relative to a capture' } }
1806
- if (-not $script:WpmShots.ContainsKey($ShotId)) {
1807
- return @{ ok = $false; stale = $true
1808
- reason = "shotId '$ShotId' is not a screenshot this worker still holds (the retention policy keeps the newest shotsKeep); take a new screenshot" }
1809
- }
1810
- $shot = $script:WpmShots[$ShotId]
1811
- $scale = [double]$shot.scale
1812
- if ($scale -le 0) { return @{ ok = $false; stale = $true; reason = "shotId '$ShotId' has a non-positive scale ($scale)" } }
1813
- if ($X -lt 0 -or $Y -lt 0 -or $X -ge [int]$shot.imageWidth -or $Y -ge [int]$shot.imageHeight) {
1814
- return @{ ok = $false; stale = $false
1815
- reason = "image point ($X,$Y) is outside the captured image ($($shot.imageWidth)x$($shot.imageHeight)); an image coordinate must address a pixel that exists" }
1816
- }
1817
- $sx = [int]$shot.left + [int][Math]::Round($X / $scale)
1818
- $sy = [int]$shot.top + [int][Math]::Round($Y / $scale)
1819
- return @{ ok = $true; stale = $false; x = $sx; y = $sy; scale = $scale; shotId = $ShotId }
1820
- }
1821
-
1822
- function Get-WpmPreviewAt {
1823
- <#
1824
- WHAT IS UNDER THAT POINT -- answered by the OS, as text. This is the confirmation step that makes
1825
- an irreversible click reviewable without a picture: AutomationElement.FromPoint plus the
1826
- ancestry proof the click path already uses (if the climb never meets the target root, the point
1827
- belongs to another window and the answer is a refusal). No input queue entry, no focus change:
1828
- the marker is drawn by the caller through overlay.ps1, which is a click-through request.
1829
- #>
1830
- param([IntPtr]$Hwnd, [int]$X, [int]$Y)
1831
- $out = @{ ok = $true; outside = $false; atPoint = $false; name = ''
1832
- controlType = ''; automationId = ''
1833
- rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1834
- reason = '' }
1835
- try {
1836
- $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1837
- if (-not $root) {
1838
- return @{ ok = $false; outside = $false; atPoint = $false; name = ''; controlType = ''
1839
- automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1840
- reason = 'target window has no UI Automation element' }
1841
- }
1842
- $pt = New-Object System.Windows.Point([double]$X, [double]$Y)
1843
- $hitEl = [System.Windows.Automation.AutomationElement]::FromPoint($pt)
1844
- if (-not $hitEl) {
1845
- $out.reason = 'nothing at that point is exposed to UI Automation'
1846
- return $out
1847
- }
1848
- $out.atPoint = $true
1849
-
1850
- $walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker
1851
- $el = $hitEl
1852
- $sawRoot = $false
1853
- $hop = 0
1854
- while ($el -and $hop -lt 24) {
1855
- if ($el -eq $root) { $sawRoot = $true; break }
1856
- try { $el = $walker.GetParent($el) } catch { $el = $null }
1857
- $hop++
1858
- }
1859
- if (-not $sawRoot) {
1860
- return @{ ok = $false; outside = $true; atPoint = $true; name = ''; controlType = ''
1861
- automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1862
- reason = 'the element under that point does not belong to the target window' }
1863
- }
1864
-
1865
- try { $out.controlType = ([string]$hitEl.Current.ControlType.ProgrammaticName) -replace '^ControlType\.', '' } catch { }
1866
- try { $out.name = [string]$hitEl.Current.Name } catch { }
1867
- try { $out.automationId = [string]$hitEl.Current.AutomationId } catch { }
1868
- try {
1869
- $b = $hitEl.Current.BoundingRectangle
1870
- $out.rect = @{
1871
- left = [int][Math]::Round($b.Left); top = [int][Math]::Round($b.Top)
1872
- right = [int][Math]::Round($b.Right); bottom = [int][Math]::Round($b.Bottom)
1873
- }
1874
- } catch { }
1875
- return $out
1876
- } catch {
1877
- return @{ ok = $false; outside = $false; atPoint = $false; name = ''; controlType = ''
1878
- automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1879
- reason = 'the point probe threw: ' + $_.Exception.Message }
1880
- }
1881
- }
1
+ # win.ps1 -- the IO half of the R2' engine: probe a target's doors, act through the cheapest
2
+ # door it has, and put the owner's focus back when the action cost them a flash.
3
+ #
4
+ # Layering is deliberate. decide.ps1 owns every judgement (pure, unit-tested). This file owns
5
+ # every syscall and no judgement: it reports facts, and it executes what it is told. When a
6
+ # behaviour is wrong, the question is then 'was the fact wrong or the table wrong', and those
7
+ # live in different files with different tests.
8
+ #
9
+ # WHAT THIS FILE REFUSES TO DO, because the stance predates the code:
10
+ # * no SendInput / keybd_event / mouse_event -- no physical injection, not even as a fallback
11
+ # * no forged Alt key to defeat the foreground lock (it works; it also drops the owner's next
12
+ # keystroke into whichever window the trick raised)
13
+ # * no acting on a window this process did not create, UNLESS it was named as the target by
14
+ # hwnd -- and the restore path only ever reverses an activation this process caused
15
+ #
16
+ # All coordinates crossing this boundary are SCREEN pixels. Client-space conversion happens only
17
+ # at the moment a message is posted to a child window, because lParam for WM_LBUTTONDOWN is
18
+ # child-relative and getting that wrong clicks the title bar instead of the control.
19
+
20
+ Set-StrictMode -Version 2.0
21
+
22
+ Add-Type -AssemblyName WindowsBase
23
+ Add-Type -AssemblyName UIAutomationClient
24
+ Add-Type -AssemblyName UIAutomationTypes
25
+
26
+ if (-not ('WpmWin' -as [type])) {
27
+ Add-Type -TypeDefinition @'
28
+ using System;
29
+ using System.Collections.Generic;
30
+ using System.Runtime.InteropServices;
31
+ using System.Text;
32
+ using System.Threading;
33
+
34
+ public static class WpmWin
35
+ {
36
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; }
37
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
38
+ [StructLayout(LayoutKind.Sequential)] public struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
39
+ [StructLayout(LayoutKind.Sequential)] public struct GUITHREADINFO
40
+ {
41
+ public uint cbSize; public uint flags; public IntPtr hwndActive; public IntPtr hwndFocus;
42
+ public IntPtr hwndCapture; public IntPtr hwndMenuOwner; public IntPtr hwndMoveSize;
43
+ public IntPtr hwndCaret; public RECT rcCaret;
44
+ }
45
+
46
+ public delegate bool EnumProc(IntPtr h, IntPtr l);
47
+
48
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr l);
49
+ [DllImport("user32.dll")] public static extern bool EnumChildWindows(IntPtr parent, EnumProc cb, IntPtr l);
50
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassNameW(IntPtr h, StringBuilder s, int n);
51
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n);
52
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
53
+ [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
54
+ [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
55
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
56
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
57
+
58
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
59
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
60
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
61
+ [DllImport("user32.dll")] static extern bool AttachThreadInput(uint attach, uint to, bool join);
62
+ [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
63
+ [DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint tid, ref GUITHREADINFO gti);
64
+
65
+ [DllImport("user32.dll")] public static extern IntPtr SendMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
66
+ [DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
67
+
68
+ [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
69
+ [DllImport("user32.dll")] public static extern IntPtr ChildWindowFromPointEx(IntPtr h, POINT p, uint flags);
70
+ [DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr h, ref POINT p);
71
+ [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
72
+ [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h, uint flags);
73
+
74
+ [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO l);
75
+ [DllImport("kernel32.dll")] static extern ulong GetTickCount64();
76
+
77
+ // ---- integrity level: the REAL elevated_target check -------------------------------------
78
+ // The old comment in Get-WpmFacts said this was deliberately unwired because "a wrong check is
79
+ // worse than none". That is still true, which is why the check below is the documented,
80
+ // side-effect-free one: OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION) -> GetTokenInformation
81
+ // (TokenIntegrityLevel) -> the RID's last sub-authority. No writes, no SeDebug privilege, and
82
+ // it degrades to -1 (unknown) on any failure -- unknown is NOT treated as elevated, because
83
+ // that would refuse every window the moment a handle read failed, which is the opposite wrong
84
+ // check. Unknown instead falls through to the door probe, and a genuinely elevated target then
85
+ // simply produces no effect, which the app-side verification reports as unverified.
86
+ [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
87
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
88
+ [DllImport("advapi32.dll")] static extern bool OpenProcessToken(IntPtr p, uint access, out IntPtr tok);
89
+ [DllImport("advapi32.dll", SetLastError = true)]
90
+ static extern bool GetTokenInformation(IntPtr tok, int cls, IntPtr info, uint len, out uint need);
91
+ [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr h);
92
+
93
+ const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
94
+ const uint TOKEN_QUERY = 0x0008;
95
+ const int TokenIntegrityLevel = 25;
96
+
97
+ /// <summary>Integrity RID of a pid: 0x1000 low, 0x2000 medium, 0x3000 high, 0x4000 system. -1 = unknown.</summary>
98
+ public static long IntegrityOf(uint pid)
99
+ {
100
+ IntPtr proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
101
+ if (proc == IntPtr.Zero) return -1;
102
+ try
103
+ {
104
+ IntPtr tok;
105
+ if (!OpenProcessToken(proc, TOKEN_QUERY, out tok)) return -1;
106
+ try
107
+ {
108
+ uint need;
109
+ // Two-pass: the SIZE-PROBE call is DOCUMENTED to fail -- it returns FALSE with
110
+ // ERROR_INSUFFICIENT_BUFFER and fills `needed`. Treating that false as a dead end
111
+ // made every read come back unknown on the first run of test/integrity-probe.ps1,
112
+ // which is exactly how a 'wrong check is worse than none' failure looks in the wild:
113
+ // the flag stayed false everywhere, so nothing was refused and nothing was claimed.
114
+ // The real condition is `needed > 0`, not the return value.
115
+ GetTokenInformation(tok, TokenIntegrityLevel, IntPtr.Zero, 0, out need);
116
+ if (need == 0) return -1;
117
+ IntPtr buf = Marshal.AllocHGlobal((int)need);
118
+ try
119
+ {
120
+ if (!GetTokenInformation(tok, TokenIntegrityLevel, buf, need, out need)) return -1;
121
+ // TOKEN_MANDATORY_LABEL { SID_AND_ATTRIBUTES Label }; Label.Sid is at offset 0.
122
+ IntPtr sid = Marshal.ReadIntPtr(buf);
123
+ if (sid == IntPtr.Zero) return -1;
124
+ // SID layout: Revision(1) | SubAuthorityCount(1) | IdentifierAuthority(6) |
125
+ // SubAuthority(4*n). The integrity RID is the LAST sub-authority.
126
+ //
127
+ // GetLengthSid was the first attempt and is NOT used: on this host it returns
128
+ // TRUE with length 0 for a SID whose bytes read back correctly (revision 1,
129
+ // count 1, authority 0x10, RID 0x2000 = medium) -- a silent contradiction that
130
+ // made every read come back unknown. The length is therefore computed from the
131
+ // SID's own header, which is the authoritative source anyway. Two wrong
132
+ // behaviours this replaced, both discovered only by measuring: trusting the
133
+ // size-probe's return value, and trusting GetLengthSid's output.
134
+ int rev = Marshal.ReadByte(sid, 0);
135
+ int count = Marshal.ReadByte(sid, 1);
136
+ if (rev != 1 || count < 1 || count > 15) return -1;
137
+ int needed = 8 + 4 * count;
138
+ if (needed > (int)need) return -1; // header claims more than the buffer holds
139
+ // The integrity RID is the LAST sub-authority.
140
+ return (long)BitConverter.ToUInt32(
141
+ new byte[] { Marshal.ReadByte(sid, 8 + 4 * (count - 1)),
142
+ Marshal.ReadByte(sid, 9 + 4 * (count - 1)),
143
+ Marshal.ReadByte(sid, 10 + 4 * (count - 1)),
144
+ Marshal.ReadByte(sid, 11 + 4 * (count - 1)) }, 0);
145
+ }
146
+ finally { Marshal.FreeHGlobal(buf); }
147
+ }
148
+ finally { CloseHandle(tok); }
149
+ }
150
+ finally { CloseHandle(proc); }
151
+ }
152
+
153
+ /// <summary>Whether the target outruns us. Equal integrity is NOT elevated for our purposes.</summary>
154
+ public static bool IsElevatedTarget(uint pid)
155
+ {
156
+ long mine = IntegrityOf((uint)System.Diagnostics.Process.GetCurrentProcess().Id);
157
+ long theirs = IntegrityOf(pid);
158
+ if (mine < 0 || theirs < 0) return false; // unknown never claims elevated
159
+ return theirs > mine;
160
+ }
161
+
162
+ // ---- overlay support: ex-styles, hotkey, and the cross-thread control board --------------
163
+ // WpmCtl is the ONE shared state between the worker's main thread (stdin/protocol/actions)
164
+ // and the overlay thread (WPF dispatcher, global hotkey). A PowerShell script variable is
165
+ // not visible across runspaces, so a static holder is the honest shape; the bools are
166
+ // volatile because the hotkey handler writes them from another thread while actions read
167
+ // them mid-flight.
168
+ [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr h, int i);
169
+ [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr h, int i, int v);
170
+ [DllImport("user32.dll")] public static extern bool RegisterHotKey(IntPtr h, int id, uint mods, uint vk);
171
+ [DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr h, int id);
172
+
173
+ public const int GWL_EXSTYLE = -20;
174
+ public const int WS_EX_TOPMOST = 0x00000008;
175
+ public const int WS_EX_TRANSPARENT = 0x00000020;
176
+ public const int WS_EX_LAYERED = 0x00080000;
177
+ public const int WS_EX_NOACTIVATE = 0x08000000;
178
+ public const int WM_HOTKEY = 0x0312;
179
+ public const int WM_CLOSE = 0x0010;
180
+ public const uint MOD_CONTROL = 0x0002;
181
+ public const uint MOD_ALT = 0x0001;
182
+
183
+ [DllImport("user32.dll", SetLastError=true)] static extern bool SetProcessDPIAware();
184
+ [DllImport("user32.dll", SetLastError=true)] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr ctx);
185
+
186
+ /// <summary>
187
+ /// Declare this process DPI aware, BEFORE any window exists.
188
+ /// Why this is not cosmetic: PowerShell starts DPI UNAWARE, so Windows virtualises every
189
+ /// coordinate it passes to user32. The engine receives PHYSICAL screen pixels (that is what a
190
+ /// click point is), the marker is placed through the same user32 -- and with an unaware process
191
+ /// a target of (470,410) rendered the marker at (303,263), exactly /1.5 on this 150% display.
192
+ /// Two components, one coordinate space, or the AI cursor points at the wrong place while every
193
+ /// style assertion still passes. Must run before any window is created (per-process setting);
194
+ /// returns false when the manifest already set it, which is success, not failure.
195
+ /// </summary>
196
+ public static bool EnsureDpiAware() {
197
+ try { SetThreadDpiAwarenessContext(new IntPtr(-4)); } catch { } // PER_MONITOR_AWARE_V2
198
+ try { return SetProcessDPIAware(); } catch { return false; }
199
+ }
200
+
201
+ [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
202
+ public const uint SWP_NOZORDER = 0x0004;
203
+ public const uint SWP_NOACTIVATE = 0x0010;
204
+
205
+ /// <summary>
206
+ /// Move a window in PHYSICAL pixels without activating it or changing its z-order.
207
+ /// This exists instead of WPF's Window.Left/Top because WPF's units are device independent while
208
+ /// every coordinate this product receives from Win32 is physical. Measured on this machine
209
+ /// (150% display): setting Left/Top put the marker at (303,263) for a target of (470,410) -- the
210
+ /// DIP conversion and the window's actual rendering disagreed by the scale factor, and no amount
211
+ /// of matrix arithmetic inside the process fixes a process-wide DPI-awareness mismatch.
212
+ /// SetWindowPos takes the same units the caller has, so there is nothing left to guess.
213
+ /// </summary>
214
+ public static bool MoveNoActivate(IntPtr h, int x, int y, int cx, int cy) {
215
+ return SetWindowPos(h, IntPtr.Zero, x, y, cx, cy, SWP_NOZORDER | SWP_NOACTIVATE);
216
+ }
217
+
218
+ /// <summary>
219
+ /// Put THIS window at the top of the topmost band without activating it. Exists for the desktop
220
+ /// test arms, which assert facts about a screen point ("WindowFromPoint at the marker returns my
221
+ /// base"; "the click lands on my target's button"). A third-party full-screen window -- a video
222
+ /// player that went fullscreen while these lines were written (measured live: PotPlayer owned every
223
+ /// test point) -- makes WindowFromPoint return the OCCLUDER. When that happens the ENGINE IS RIGHT
224
+ /// to refuse: it must never act under a window the caller did not name. What broke is the arm's
225
+ /// PREMISE, not the product. Raising the test's OWN window into the topmost band uses the same
226
+ /// mechanism the overlay relies on (HWND_TOPMOST + SWP_NOACTIVATE): z-order changes,
227
+ /// GetForegroundWindow does not. This is a test-support primitive, NOT a product surface -- there is
228
+ /// no reason to let a model topmost-raise arbitrary windows, so no such action exists in
229
+ /// tools.json; scripts/raise-topmost.ps1 is the only product-adjacent caller and it is a test
230
+ /// helper under scripts/, not exposed through wpm.
231
+ /// </summary>
232
+ public static bool MakeTopmostNoActivate(IntPtr h) {
233
+ // SWP_NOMOVE(0x2) | SWP_NOSIZE(0x1) | SWP_NOACTIVATE(0x10), insert after HWND_TOPMOST(-1).
234
+ return SetWindowPos(h, new IntPtr(-1), 0, 0, 0, 0, 0x2u | 0x1u | 0x10u);
235
+ }
236
+
237
+ /// <summary>Add ex-style bits and return the new value (the trio lives here, once).</summary>
238
+ public static int AddExStyles(IntPtr h, int bits) {
239
+ int v = GetWindowLong(h, GWL_EXSTYLE);
240
+ SetWindowLong(h, GWL_EXSTYLE, v | bits);
241
+ return v | bits;
242
+ }
243
+
244
+ public const int SW_MINIMIZE = 6;
245
+ public const int SW_SHOWNA = 8;
246
+ public const int SW_RESTORE = 9;
247
+
248
+ public static string Cls(IntPtr h) { var s = new StringBuilder(512); GetClassNameW(h, s, s.Capacity); return s.ToString(); }
249
+ public static string Txt(IntPtr h) { var s = new StringBuilder(1024); GetWindowTextW(h, s, s.Capacity); return s.ToString(); }
250
+ public static string Fg() { return GetForegroundWindow().ToInt64().ToString(); }
251
+ public static IntPtr FgHandle() { return GetForegroundWindow(); }
252
+ public static string Cursor() { POINT p; GetCursorPos(out p); return p.X + "," + p.Y; }
253
+ public static uint PidOf(IntPtr h) { uint p; GetWindowThreadProcessId(h, out p); return p; }
254
+
255
+ // One proof sample: cursor x/y, foreground HWND, focused-control HWND, and the age of the last
256
+ // PHYSICAL input. Every read is a non-disturbing query (GetCursorPos, GetForegroundWindow,
257
+ // GetGUIThreadInfo, GetLastInputInfo change nothing), which is the property that makes it safe to
258
+ // call in a tight loop DURING an action -- unlike spawning a fresh PowerShell per poll, which can
259
+ // itself steal the foreground and contaminate the measured quantity (src/lib/sampler.mjs).
260
+ public static string[] Sample()
261
+ {
262
+ POINT cp; GetCursorPos(out cp);
263
+ IntPtr fg = GetForegroundWindow();
264
+ GUITHREADINFO g = new GUITHREADINFO();
265
+ g.cbSize = (uint)Marshal.SizeOf(typeof(GUITHREADINFO));
266
+ uint pid; uint tid = GetWindowThreadProcessId(fg, out pid);
267
+ long focusHwnd = 0;
268
+ if (GetGUIThreadInfo(tid, ref g)) focusHwnd = g.hwndFocus.ToInt64();
269
+ long age = LastInputAgeMs(); // the one tick-difference calculation; -1 when unreadable
270
+ return new string[] {
271
+ cp.X.ToString(), cp.Y.ToString(),
272
+ fg.ToInt64().ToString(), focusHwnd.ToString(), age.ToString()
273
+ };
274
+ }
275
+ public static IntPtr Root(IntPtr h) { IntPtr r = GetAncestor(h, 2); return r == IntPtr.Zero ? h : r; }
276
+
277
+ public static List<long> Children(IntPtr parent)
278
+ {
279
+ var acc = new List<long>();
280
+ EnumChildWindows(parent, delegate (IntPtr h, IntPtr l) { if (IsWindowVisible(h)) acc.Add(h.ToInt64()); return true; }, IntPtr.Zero);
281
+ return acc;
282
+ }
283
+
284
+ // Age of the last physical input, in ms; -1 when the call fails. Callers must treat -1 as
285
+ // UNKNOWN rather than as 'idle' -- counting unknown as idle is how a software-caused change
286
+ // gets laundered into 'the owner was away'.
287
+ public static long LastInputAgeMs()
288
+ {
289
+ LASTINPUTINFO i = new LASTINPUTINFO();
290
+ i.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
291
+ if (!GetLastInputInfo(ref i)) return -1;
292
+ uint now = (uint)(GetTickCount64() & 0xFFFFFFFF);
293
+ return (long)((now - i.dwTime) & 0xFFFFFFFF);
294
+ }
295
+
296
+ // hwndActive / hwndFocus for the foreground thread. hwndFocus is the CONTROL inside the
297
+ // window; that distinction is what makes 'the window came back' testable separately from
298
+ // 'the caret came back'.
299
+ public static long[] GuiFocusOfForeground()
300
+ {
301
+ GUITHREADINFO g = new GUITHREADINFO();
302
+ g.cbSize = (uint)Marshal.SizeOf(typeof(GUITHREADINFO));
303
+ IntPtr fg = GetForegroundWindow();
304
+ uint pid; uint tid = GetWindowThreadProcessId(fg, out pid);
305
+ if (!GetGUIThreadInfo(tid, ref g)) return new long[] { 0, 0, 0 };
306
+ return new long[] { g.hwndActive.ToInt64(), g.hwndFocus.ToInt64(), (long)tid };
307
+ }
308
+
309
+ // Restore the foreground to a window we previously took it from. Joins the input queue of the
310
+ // thread that OWNS THE CURRENT foreground (the documented unlock) rather than of the window
311
+ // being restored to -- the earlier failure in this repo was joining the wrong one and
312
+ // concluding the door was locked.
313
+ public static string RestoreForeground(IntPtr want)
314
+ {
315
+ IntPtr cur = GetForegroundWindow();
316
+ uint pid; uint tid = GetWindowThreadProcessId(cur, out pid);
317
+ bool joined = AttachThreadInput(GetCurrentThreadId(), tid, true);
318
+ bool ok = false;
319
+ try { ok = SetForegroundWindow(want); }
320
+ finally { if (joined) AttachThreadInput(GetCurrentThreadId(), tid, false); }
321
+ Thread.Sleep(40);
322
+ return (ok ? "true" : "false") + "|" + (joined ? "true" : "false") + "|" + GetForegroundWindow().ToInt64();
323
+ }
324
+
325
+ // Click a child control by POSTING mouse messages inside it. lParam is child-relative, which
326
+ // is why the conversion happens here and not at the call site.
327
+ public static string MessageClick(IntPtr child, int screenX, int screenY)
328
+ {
329
+ POINT p = new POINT(); p.X = screenX; p.Y = screenY;
330
+ if (!ScreenToClient(child, ref p)) return "convert-failed";
331
+ IntPtr lp = (IntPtr)((p.Y * 0x10000) + (p.X & 0xFFFF));
332
+ SendMessageW(child, 0x0201, (IntPtr)1, lp);
333
+ Thread.Sleep(30);
334
+ SendMessageW(child, 0x0202, IntPtr.Zero, lp);
335
+ return "ok|" + p.X + "," + p.Y;
336
+ }
337
+
338
+ public static string MessageText(IntPtr child, string text, bool replace)
339
+ {
340
+ if (!replace)
341
+ {
342
+ for (int i = 0; i < text.Length; i++) SendMessageW(child, 0x0102, (IntPtr)text[i], IntPtr.Zero);
343
+ return "char|" + text.Length;
344
+ }
345
+ SendMessageString(child, 0x000C, IntPtr.Zero, text);
346
+ return "settext|" + text.Length;
347
+ }
348
+
349
+ // ---- 0.6.0: reading the value back, and putting the caret somewhere on purpose -------------
350
+ // WHY THESE PRIMITIVES DID NOT EXIST BEFORE. The message door only ever SENT; every claim about
351
+ // "the field now contains this" was a report of what SendMessage returned, which is a statement
352
+ // about delivery, not about the application's state. Measured on 2026-11-23 (findings 8.2) with an
353
+ // in-process oracle: on a plain Win32 EDIT that has never held focus, WM_CHAR is INERT -- every
354
+ // character is accepted and nothing changes -- while the shipped answer was `reported-by-send`.
355
+ // The read is what turns that from a false success into a visible one.
356
+ //
357
+ // ONE MORE THING THIS FIXED, found by running the syscall instead of trusting the import: the
358
+ // previous WM_SETTEXT binding was declared as `SendMessageStrW`, which user32.dll does not export
359
+ // (.tmp/_t-sendmessagestrw.ps1: EntryPointNotFoundException, first call, every call). So
360
+ // `type` with replace:true threw and surfaced as `action_failed` on EVERY target, and no test in
361
+ // the repo exercised it. The entry point is now pinned explicitly, because a marshaller resolves
362
+ // the name it is given and an alias that exists in nobody's header is not a name.
363
+ [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageW")]
364
+ public static extern IntPtr SendMessageString(IntPtr h, uint m, IntPtr w, string l);
365
+
366
+ [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageW")]
367
+ public static extern IntPtr SendMessageBuffer(IntPtr h, uint m, IntPtr w, [Out()] StringBuilder l);
368
+
369
+ // The hang-proof read. A plain SendMessageW(WM_GETTEXT) to a window whose thread is busy blocks
370
+ // this worker indefinitely, and a read is never worth wedging the sidecar for: with a budget the
371
+ // answer degrades to `unavailable`, which the engine reports instead of inventing.
372
+ [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageTimeoutW")]
373
+ public static extern IntPtr SendMessageTimeoutBuffer(IntPtr h, uint m, IntPtr w, [Out()] StringBuilder l,
374
+ uint flags, uint ms, out IntPtr res);
375
+
376
+ [DllImport("user32.dll")] public static extern bool IsWindowEnabled(IntPtr h);
377
+
378
+ public const uint WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E;
379
+ public const uint WM_CHAR = 0x0102, EM_SETSEL = 0x00B1, EM_GETSEL = 0x00B0;
380
+ public const uint SMTO_ABORTIFHUNG = 0x0002;
381
+
382
+ /// <summary>WM_GETTEXTLENGTH. A length the CONTROL reports, not a length we computed.</summary>
383
+ public static int TextLength(IntPtr h) { return (int)(long)SendMessageW(h, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero); }
384
+
385
+ /// <summary>{ok, chars, text} from WM_GETTEXT, sized from the control's own WM_GETTEXTLENGTH.
386
+ /// The buffer is deliberately one char LONGER than the reported length: the control writes a
387
+ /// terminating NUL into the buffer it is handed, and a measured truncation (a 1000-char buffer
388
+ /// against a 5000-char value came back as 999) has to stay visible rather than become the answer.</summary>
389
+ public static object[] ReadText(IntPtr h, uint ms)
390
+ {
391
+ int len = TextLength(h);
392
+ if (len < 0) len = 0;
393
+ if (len > 65536) len = 65536; // a capped read, reported as truncated downstream
394
+ var sb = new StringBuilder(len + 2);
395
+ IntPtr res;
396
+ IntPtr r = SendMessageTimeoutBuffer(h, WM_GETTEXT, (IntPtr)(len + 1), sb, SMTO_ABORTIFHUNG, ms, out res);
397
+ if (r == IntPtr.Zero) return new object[] { false, -1, "" };
398
+ int n = (int)(long)res;
399
+ string s = sb.ToString();
400
+ if (n >= 0 && n <= s.Length) s = s.Substring(0, n);
401
+ return new object[] { true, n, s };
402
+ }
403
+
404
+ /// <summary>{start, end} from EM_GETSEL -- the control's own answer about where a typed
405
+ /// character will land, which is what makes an expected-value model computable (findings 8.2).</summary>
406
+ public static int[] GetSel(IntPtr h)
407
+ {
408
+ long r = (long)SendMessageW(h, EM_GETSEL, IntPtr.Zero, IntPtr.Zero);
409
+ return new int[] { (int)(r & 0xFFFF), (int)((r >> 16) & 0xFFFF) };
410
+ }
411
+
412
+ /// <summary>EM_SETSEL. NOTE: -1 is NOT used for `end` -- measured on WinForms EDIT it leaves the
413
+ /// selection at 0,0 and the typed character goes to the FRONT (findings 8.2). The caller passes
414
+ /// the length it read from the control.</summary>
415
+ public static void SetSel(IntPtr h, int a, int b) { SendMessageW(h, EM_SETSEL, (IntPtr)a, (IntPtr)b); }
416
+
417
+ /// <summary>
418
+ /// Write text through the message door with an explicit caret intention, and report BOTH what was
419
+ /// asked for and what the control says its selection now is. The selection is read back rather than
420
+ /// echoed because the whole point is that the control, not the caller, decides where text goes:
421
+ /// EM_SETSEL(6,6) on a buffer whose WM_GETTEXTLENGTH is 6 came back as 4,4 on a value containing a
422
+ /// newline, and an engine that reported the requested pair would have been describing a wish.
423
+ /// mode: 'settext' (whole-value replace) | 'char' (per-character, inserted at the reported sel).
424
+ /// </summary>
425
+ public static object[] MessageTextAt(IntPtr child, string text, bool replace, string caret)
426
+ {
427
+ if (replace)
428
+ {
429
+ SendMessageString(child, WM_SETTEXT, IntPtr.Zero, text);
430
+ if (caret == "start") SetSel(child, 0, 0);
431
+ else if (caret == "end") { int l = TextLength(child); SetSel(child, l, l); }
432
+ int[] rs = GetSel(child);
433
+ return new object[] { "settext", text.Length, rs[0], rs[1] };
434
+ }
435
+ int askedStart = -1, askedEnd = -1;
436
+ if (caret == "start") { SetSel(child, 0, 0); askedStart = 0; askedEnd = 0; }
437
+ else if (caret == "end") { int l = TextLength(child); SetSel(child, l, l); askedStart = l; askedEnd = l; }
438
+ int[] sel = GetSel(child);
439
+ for (int i = 0; i < text.Length; i++) SendMessageW(child, WM_CHAR, (IntPtr)text[i], IntPtr.Zero);
440
+ return new object[] { "char", text.Length, sel[0], sel[1], askedStart, askedEnd };
441
+ }
442
+
443
+ // ---- 0.5.0: the frame, the virtual screen, and the capture footprint ---------------------
444
+ // THE FRAME COMES FROM DWM, NOT FROM GetWindowRect. Measured on this desktop (2026-11-23):
445
+ // GetWindowRect returns -8,-8,1928,1040 while DwmGetWindowAttribute(EXTENDED_FRAME_BOUNDS)
446
+ // returns 0,0,1920,1032 -- four 8px differences that are the invisible resize shadow. The UIA
447
+ // tree MIXES the two spaces (the ROOT element reports the shadow-inclusive rect, its children the
448
+ // real one), so any arithmetic that mixes them is 8px wrong and looks right. `screenRect` is
449
+ // therefore DWM-only, and the fallback is REPORTED as frame='win32' rather than hidden: an 8px
450
+ // offset with no field to explain it is the failure mode this whole change is written against.
451
+ [DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int attr, out RECT r, int size);
452
+ [DllImport("user32.dll")] static extern int GetSystemMetrics(int i);
453
+
454
+ /// <summary>{hr, left, top, right, bottom}. hr==0 means the DWM answer is usable.</summary>
455
+ public static long[] DwmFrame(IntPtr h)
456
+ {
457
+ RECT r;
458
+ int hr = DwmGetWindowAttribute(h, 9 /* DWMWA_EXTENDED_FRAME_BOUNDS */, out r, Marshal.SizeOf(typeof(RECT)));
459
+ if (hr != 0) return new long[] { hr, 0, 0, 0, 0 };
460
+ return new long[] { 0, r.Left, r.Top, r.Right, r.Bottom };
461
+ }
462
+
463
+ /// <summary>{ok, left, top, right, bottom} from GetWindowRect -- the documented FALLBACK only.</summary>
464
+ public static long[] WinRect(IntPtr h)
465
+ {
466
+ RECT r;
467
+ if (!GetWindowRect(h, out r)) return new long[] { 0, 0, 0, 0, 0 };
468
+ return new long[] { 1, r.Left, r.Top, r.Right, r.Bottom };
469
+ }
470
+
471
+ /// <summary>{x, y, width, height} of the virtual screen (all monitors, physical pixels).</summary>
472
+ public static int[] VirtualScreen()
473
+ {
474
+ const int SM_XVIRTUALSCREEN = 76, SM_YVIRTUALSCREEN = 77;
475
+ const int SM_CXVIRTUALSCREEN = 78, SM_CYVIRTUALSCREEN = 79;
476
+ return new int[] { GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN),
477
+ GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN) };
478
+ }
479
+
480
+ // ---- 0.6.0-B: the cheaper capture, with the SAME semantics as the one it replaces -----------
481
+ // WHY. Measured on this host (findings 8.4): the capture is not the bottleneck -- PNG encoding is
482
+ // (37-39ms of a ~70ms screenshot). But the capture half still costs 22-33ms through
483
+ // Graphics.CopyFromScreen and 16-21ms through a direct BitBlt, so the cheap primitive is taken and
484
+ // the encoder is left alone. JPEG (10ms, but it smears text), WIC (158ms, slower), and 24bpp
485
+ // (7% smaller) were all measured and all rejected.
486
+ //
487
+ // WHY THE SOURCE DC IS THE SCREEN AND NOT THE WINDOW. Get-WpmScreenshot has always captured the
488
+ // frame RECTANGLE OUT OF THE SCREEN, which is what makes its coordinates the same system a click
489
+ // uses and what makes an occluding window appear in the picture (honestly: the picture shows what a
490
+ // user would see). Capturing with GetWindowDC/PrintWindow would be a DIFFERENT product -- unoccluded,
491
+ // and no longer the screen the coordinates refer to. Equivalence was measured, not assumed: on a
492
+ // static scene the two paths give identical size, identical content, 0 max per-channel difference
493
+ // over 17388 sampled points, and byte-identical PNGs (findings 8.3). The one difference is reported:
494
+ // FromHbitmap yields Format32bppRgb where CopyFromScreen yields Format32bppArgb.
495
+ [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleDC(IntPtr dc);
496
+ [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr h);
497
+ [DllImport("user32.dll")] static extern int ReleaseDC(IntPtr h, IntPtr dc);
498
+ [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleBitmap(IntPtr dc, int w, int h);
499
+ [DllImport("gdi32.dll")] static extern IntPtr SelectObject(IntPtr dc, IntPtr obj);
500
+ [DllImport("gdi32.dll")] static extern bool BitBlt(IntPtr dc, int x, int y, int w, int h,
501
+ IntPtr srcDc, int srcX, int srcY, uint rop);
502
+ [DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr obj);
503
+ [DllImport("gdi32.dll")] static extern bool DeleteDC(IntPtr dc);
504
+ const uint SRCCOPY = 0x00CC0020;
505
+
506
+ /// <summary>
507
+ /// Capture a SCREEN rectangle into a new HBITMAP through BitBlt. Returns IntPtr.Zero with a named
508
+ /// reason on ANY failure -- the caller falls back to CopyFromScreen and reports which path it used.
509
+ /// Every GDI object created here is released on every path, including the partial ones: a leaked DC
510
+ /// in a long-lived worker is the kind of bug that shows up as "the app stopped painting" an hour in.
511
+ /// The returned handle is owned by the caller and must be passed to FreeHbitmap.
512
+ /// </summary>
513
+ public static IntPtr CaptureBitBlt(int x, int y, int w, int h, out string reason)
514
+ {
515
+ reason = "";
516
+ if (w <= 0 || h <= 0) { reason = "empty rectangle " + w + "x" + h; return IntPtr.Zero; }
517
+ IntPtr screen = GetDC(IntPtr.Zero);
518
+ if (screen == IntPtr.Zero) { reason = "GetDC(NULL) returned no screen DC"; return IntPtr.Zero; }
519
+ IntPtr mem = IntPtr.Zero, bmp = IntPtr.Zero, old = IntPtr.Zero;
520
+ try
521
+ {
522
+ mem = CreateCompatibleDC(screen);
523
+ if (mem == IntPtr.Zero) { reason = "CreateCompatibleDC failed"; return IntPtr.Zero; }
524
+ bmp = CreateCompatibleBitmap(screen, w, h);
525
+ if (bmp == IntPtr.Zero) { reason = "CreateCompatibleBitmap failed"; return IntPtr.Zero; }
526
+ old = SelectObject(mem, bmp);
527
+ if (!BitBlt(mem, 0, 0, w, h, screen, x, y, SRCCOPY)) { reason = "BitBlt refused"; DeleteObject(bmp); return IntPtr.Zero; }
528
+ return bmp;
529
+ }
530
+ finally
531
+ {
532
+ // `old` is restored before the memory DC goes away, and the screen DC is always released.
533
+ if (mem != IntPtr.Zero && old != IntPtr.Zero) SelectObject(mem, old);
534
+ if (mem != IntPtr.Zero) DeleteDC(mem);
535
+ ReleaseDC(IntPtr.Zero, screen);
536
+ }
537
+ }
538
+
539
+ /// <summary>Release an HBITMAP from CaptureBitBlt. Safe to call after FromHbitmap: that call copies
540
+ /// the bits into managed memory, so the native handle has nothing left to alias.</summary>
541
+ public static bool FreeHbitmap(IntPtr h) { return h != IntPtr.Zero && DeleteObject(h); }
542
+ }
543
+ '@
544
+ }
545
+
546
+ if (-not ('WpmCtl' -as [type])) {
547
+ Add-Type -TypeDefinition @'
548
+ using System;
549
+ public static class WpmCtl {
550
+ public static volatile bool Paused = false;
551
+ public static volatile bool OverlayOn = false;
552
+ public static volatile bool HotkeyOk = false;
553
+ // The chord that ACTUALLY registered, not the one the docs promise: on this machine Ctrl+Alt+Q
554
+ // is already owned by another app (RegisterHotKey -> 1409, measured in
555
+ // scripts/hotkey-availability.ps1, 7/8 other candidates free). A silent fallback would make the
556
+ // README's "Ctrl+Alt+Q" untrue with nothing to notice; the real chord is reported instead.
557
+ public static string HotkeyLabel = "";
558
+ // Marker placement travels through these fields INSTEAD of a cross-thread Dispatcher.Invoke.
559
+ // Measured (.tmp/ov-seg.log): Invoke(priority, Action) from the worker's thread cost 1818ms and
560
+ // sometimes never returned -- the delegate is a PowerShell scriptblock and the overlay thread is
561
+ // already inside Dispatcher.Run(), so the engine has to reach a runspace that is busy. Writing
562
+ // three fields costs nothing, and the overlay's own pump applies them from its own thread.
563
+ public static volatile int MarkerX = -1;
564
+ public static volatile int MarkerY = -1;
565
+ public static volatile bool MarkerHide = false;
566
+ public static volatile int MarkerSeq = 0; // incremented per request; the pump compares it
567
+ // volatile is illegal on long in C# (the compiler rejects it, which is the point: a 64-bit
568
+ // read is not guaranteed atomic). The hwnd is written once before any reader exists and read
569
+ // as a value, so plain static is honest here; Interlocked would be the answer if it changed.
570
+ public static long OverlayHwnd = 0;
571
+ public static string Reason = "";
572
+ public static object Dispatcher = null; // overlay thread's WPF dispatcher (set by that thread)
573
+ public static object Window = null; // the marker window (touched ONLY on its own thread)
574
+ public static object Timer = null; // auto-hide timer (same rule)
575
+
576
+ // ---- R3 takeover surface (spec.md §2) ------------------------------------------------------
577
+ // Same rule as the marker fields: the HUD thread owns the window and reads these; the engine writes
578
+ // the request fields. No scriptblock is ever marshalled across the threads.
579
+ public static volatile bool HudOn = false;
580
+ public static volatile bool TakeoverAbort = false; // HUD button / abort chord / worker abort
581
+ public static volatile bool AbortChordOk = false;
582
+ // volatile is ILLEGAL on string in C# (like long below): a reference write is atomic, so a plain
583
+ // static is the honest declaration and not a weaker one.
584
+ public static string HudPhase = "";
585
+ public static string HudAction = "";
586
+ public static string AbortChordLabel = "";
587
+ public static volatile int HudElapsedMs = 0;
588
+ public static volatile int HudMaxMs = 0;
589
+ public static volatile int HudSeq = 0;
590
+ public static volatile int InjectedChars = 0;
591
+ public static long HudHwnd = 0;
592
+ }
593
+ '@
594
+ }
595
+
596
+ # Before anything can create a window. See EnsureDpiAware: an unaware process virtualises the same
597
+ # coordinates the engine uses for clicks, which is how the marker ended up off by the display scale.
598
+ $script:WpmDpiAware = [WpmWin]::EnsureDpiAware()
599
+
600
+ $script:WpmUia = $null
601
+ # ---- 0.5.0 state. Deliberately IN-PROCESS and BOUNDED: a label is only meaningful in the frame that
602
+ # printed it, so this holds at most two snapshots (the newest for label references, the previous as a
603
+ # sinceSnapId diff base) and at most shotsKeep screenshots. A worker restart empties both, which is
604
+ # exactly what makes a stale id a real, reportable condition instead of an unbounded cache.
605
+ $script:WpmSnapshots = @()
606
+ $script:WpmShots = @{}
607
+ $script:WpmSnapSeq = 0
608
+ $script:WpmShotSeq = 0
609
+ function Get-WpmUiaCached {
610
+ # Each pattern type is resolved independently and a missing one is simply absent from the table.
611
+ # The first version built the table in one literal, and on this runtime
612
+ # [System.Windows.Automation.LegacyIAccessiblePattern] does not exist -- so the constructor threw,
613
+ # the table came back empty, every target reported 'no pattern', and the engine refused windows
614
+ # that demonstrably had patterns. One optional identifier took the whole engine down because the
615
+ # lookup was all-or-nothing. Now a missing type costs only that type.
616
+ if (-not $script:WpmUia) {
617
+ $t = @{}
618
+ $map = @{
619
+ invoke = 'System.Windows.Automation.InvokePattern'
620
+ value = 'System.Windows.Automation.ValuePattern'
621
+ toggle = 'System.Windows.Automation.TogglePattern'
622
+ select = 'System.Windows.Automation.SelectionItemPattern'
623
+ legacy = 'System.Windows.Automation.LegacyIAccessiblePattern'
624
+ range = 'System.Windows.Automation.RangeValuePattern'
625
+ }
626
+ foreach ($k in $map.Keys) {
627
+ try {
628
+ # Resolve against the assemblies already loaded by Add-Type -AssemblyName above. Probing
629
+ # by assembly-qualified name failed here because the assembly's simple name is not what
630
+ # GetType expects, and guessing names is how a resolver turns into a silent 'type not
631
+ # found'. Asking the loaded assemblies what they actually contain cannot guess wrong.
632
+ $ty = $null
633
+ foreach ($asm in [AppDomain]::CurrentDomain.GetAssemblies()) {
634
+ try { $ty = $asm.GetType($map[$k]); } catch { $ty = $null }
635
+ if ($ty) { break }
636
+ }
637
+ if ($ty) {
638
+ # Pattern is a public static FIELD on these classes, not a property. Asking only for a
639
+ # property returned $null for every pattern and produced 'no identifiers resolved' -- the
640
+ # same shape of mistake as reading an empty field as evidence.
641
+ $v = $null
642
+ $pr = $ty.GetProperty('Pattern')
643
+ if ($pr) { $v = $pr.GetValue($null) }
644
+ if (-not $v) {
645
+ $fl = $ty.GetField('Pattern')
646
+ if ($fl) { $v = $fl.GetValue($null) }
647
+ }
648
+ if ($v) { $t[$k] = $v }
649
+ }
650
+ } catch { }
651
+ }
652
+ if ($t.Count -eq 0) { throw 'no UIA pattern identifiers resolved; the automation client is unusable' }
653
+ $script:WpmUia = $t
654
+ }
655
+ return $script:WpmUia
656
+ }
657
+
658
+ function Test-WpmUiaTreeHasContent([IntPtr]$Hwnd, [int]$MaxElements = 200) {
659
+ <#
660
+ Does this target's accessibility tree contain ANY content element, or is it shell only?
661
+ Returns $true when at least one element carries a content control type, $false when the
662
+ walked tree is only structural chrome, and $false when the walk itself cannot run (a walk
663
+ that failed must not be reported as "measured empty" -- the caller distinguishes that world
664
+ through the probe error, not through this answer).
665
+
666
+ WHY CONTENT, NOT COUNT. "The tree is empty" cannot mean Count == 0: a Chromium window with
667
+ renderer accessibility off still exposes ONE shell element -- the Chrome_RenderWidgetHostHWND
668
+ pane ("Chrome Legacy Window") -- so uTools measures raw=1 while carrying zero drivable
669
+ content, and the same window measured raw=0 earlier the same day depending on its own state.
670
+ What never changed across every re-read was the CONTENT count: 0 for the a11y-off window,
671
+ hundreds for the a11y-on ones (DSH 514 at census time, 1019 later; ZCode 497). The stable
672
+ boundary is structural, not numeric: shell types (Pane/Group/Image/Text/Thumb/Separator/
673
+ TitleBar) are the window's own chrome; anything else -- Button, Edit, Document, Custom --
674
+ is something an application chose to expose. Custom counts as content deliberately: it may
675
+ be undrivable, but calling it "empty" would claim the app has a11y off, and a wrong
676
+ uia_tree_empty is a worse lie than an honest unreachable.
677
+
678
+ Measured on 2026-11-21 (see scripts/uia-tree-content.ps1, which reads the same two counters
679
+ with the same shell list). This is also why NO retry/polling exists for a tree that answers
680
+ empty: three in-place reads over 2.2s produced zero content elements every time -- there is
681
+ nothing to wait for. The switch is launch-time: --force-renderer-accessibility.
682
+ #>
683
+ try {
684
+ $rootEl = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
685
+ $all = $rootEl.FindAll([System.Windows.Automation.TreeScope]::Descendants,
686
+ [System.Windows.Automation.Condition]::TrueCondition)
687
+ $n = [Math]::Min($all.Count, $MaxElements)
688
+ for ($i = 0; $i -lt $n; $i++) {
689
+ $t = ''
690
+ try { $t = $all[$i].Current.ControlType.ProgrammaticName -replace 'ControlType\.', '' } catch { continue }
691
+ if (@('Pane', 'Group', 'Image', 'Text', 'Thumb', 'Separator', 'TitleBar') -notcontains $t) { return $true }
692
+ }
693
+ return $false
694
+ } catch {
695
+ return $false
696
+ }
697
+ }
698
+
699
+ function Get-WpmFamily([IntPtr]$Hwnd, [string]$Cls) {
700
+ # Family decides which door is even possible, so it is measured from the class name rather than
701
+ # guessed from the title: a title is the user's text, a class is the toolkit's identity.
702
+ if ($Cls -like 'CASCADIA_HOSTING_WINDOW_CLASS*') { return 'terminal' }
703
+ if ($Cls -like 'WindowsForms10*') { return 'winforms' }
704
+ if ($Cls -like 'HwndWrapper*') { return 'wpf' }
705
+ if ($Cls -eq 'ApplicationFrameWindow' -or $Cls -eq 'Windows.UI.Core.CoreWindow') { return 'uwp' }
706
+ if ($Cls -like 'Chrome_WidgetWin*') { return 'chromium' }
707
+ if ($Cls -like 'Edit' -or $Cls -like 'RichEdit*' -or $Cls -eq '#32770') { return 'win32-classic' }
708
+ return 'unknown'
709
+ }
710
+
711
+ function Resolve-WpmUiaElementAtPoint {
712
+ <#
713
+ WHICH UIA ELEMENT SITS UNDER A SCREEN POINT -- the UIA twin of Resolve-WpmChildAtPoint.
714
+
715
+ WHY THIS EXISTS. The UIA tier used to take the FIRST descendant carrying any usable pattern and
716
+ invoke that, while the contract (src/schema/tools.json) says x/y are REQUIRED and that a point
717
+ which does not resolve inside the target is refused "instead of being sent somewhere else". On a
718
+ target with no message door -- WPF, UWP, WinUI3, i.e. most modern apps -- 'click 500,300' would
719
+ therefore Invoke whichever control happened to come first in tree order and return ok:true. That
720
+ is not a refusal, it is a wrong action reported as a right one, and it also breaks the marker's
721
+ promise (the marker is drawn at the requested point, which was then not the point acted on).
722
+
723
+ THE WALK-UP. AutomationElement.FromPoint returns the DEEPEST element at the point, which for a
724
+ button is usually its text child; the Invoke pattern lives on the ancestor. So the search climbs
725
+ from the hit element towards the target root and takes the nearest ancestor that has a usable
726
+ pattern. Climbing stops at the target's own root element: beyond it lies the caller's other
727
+ windows, and acting there would be acting on a window nobody named.
728
+
729
+ ANCESTRY IS PROVEN, NOT ASSUMED. If the climb reaches a null parent without meeting the target
730
+ root, the point belongs to a different window and the answer is a refusal -- the same rule the
731
+ message tier enforces with Root(hit) -ne Hwnd.
732
+ #>
733
+ param([IntPtr]$Hwnd, [int]$X, [int]$Y)
734
+
735
+ $out = @{ element = $null; patternKind = 'none'; err = ''; atPoint = $false; reason = '' }
736
+ try {
737
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
738
+ if (-not $root) { $out.err = 'target window has no UIA element'; $out.reason = 'target element unavailable'; return $out }
739
+
740
+ $pt = New-Object System.Windows.Point([double]$X, [double]$Y)
741
+ $hitEl = [System.Windows.Automation.AutomationElement]::FromPoint($pt)
742
+ if (-not $hitEl) { $out.reason = 'nothing at that point is exposed to UI Automation'; return $out }
743
+ $out.atPoint = $true
744
+
745
+ # ANCESTRY FIRST, PATTERN SECOND. The first version of this function searched for a pattern
746
+ # while climbing and returned the moment it found one -- which re-created the very bug it was
747
+ # written to kill, one level down: a click at a point OUTSIDE the target climbed into the
748
+ # taskbar, found a patterned button there, invoked it, and reported ok:true. Caught by the
749
+ # 'point outside the target' arm of test/uia-click-truth.mjs. The order is the invariant:
750
+ # prove the point belongs to THIS window, and only then ask what at the point can be driven.
751
+ $walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker
752
+ $path = @()
753
+ $el = $hitEl
754
+ $sawRoot = $false
755
+ $hop = 0
756
+ while ($el -and $hop -lt 24) {
757
+ if ($el -eq $root) { $sawRoot = $true; break }
758
+ $path += $el
759
+ try { $el = $walker.GetParent($el) } catch { $el = $null }
760
+ $hop++
761
+ }
762
+ if ($el -eq $root) { $sawRoot = $true }
763
+
764
+ if (-not $sawRoot) {
765
+ # The climb ended without meeting the target root: the point is in another window, and
766
+ # acting there would be acting on a window nobody named.
767
+ $out.element = $null
768
+ $out.patternKind = 'none'
769
+ $out.reason = 'the element under that point does not belong to the target window'
770
+ return $out
771
+ }
772
+
773
+ $pats = Get-WpmUiaCached
774
+ foreach ($node in $path) {
775
+ foreach ($k in @('invoke', 'value', 'toggle', 'select', 'legacy')) {
776
+ if (-not $pats.ContainsKey($k)) { continue }
777
+ $obj = $null
778
+ $has = $false
779
+ try { $has = $node.TryGetCurrentPattern($pats[$k], [ref]$obj) } catch { $has = $false; $obj = $null }
780
+ if ($has -and $obj) { $out.element = $node; $out.patternKind = $k; return $out }
781
+ }
782
+ }
783
+ $out.reason = 'the element under that point exposes no usable UIA pattern'
784
+ return $out
785
+ } catch {
786
+ $out.err = $_.Exception.Message
787
+ $out.reason = 'the point probe threw'
788
+ return $out
789
+ }
790
+ }
791
+
792
+ function Get-WpmFacts {
793
+ <#
794
+ Measure a target's doors. Returns the hashtable decide.ps1 consumes, plus the raw handles the
795
+ executor needs. Cached per hwnd because UIA enumeration costs hundreds of ms and a batch of 50
796
+ clicks must not pay it 50 times -- but the cache is keyed on hwnd AND invalidated by the caller
797
+ when the window set changes, never assumed fresh.
798
+ #>
799
+ param([IntPtr]$Hwnd, [string]$Action = 'click', [string]$ElementName = '', [int]$X = -1, [int]$Y = -1, [switch]$NoCache)
800
+
801
+ $cls = [WpmWin]::Cls($Hwnd)
802
+ $fam = Get-WpmFamily $Hwnd $cls
803
+ $kids = @([WpmWin]::Children($Hwnd))
804
+ $childHandles = @()
805
+ $doorKinds = @()
806
+ $doorHandles = @()
807
+ foreach ($k in $kids) {
808
+ $kh = [IntPtr]$k
809
+ $kc = [WpmWin]::Cls($kh)
810
+ # WinForms child classes are NOT 'Edit'/'Button': they are
811
+ # WindowsForms10.EDIT.app.0.<hash>_rN_adN / .BUTTON. / .RichEdit20W.
812
+ # and the old exact-ish match ('Edit', 'Button') never hit one of those -- the message door
813
+ # silently did not exist on the one toolkit where it demonstrably works, and the engine
814
+ # reported WinForms as `unreachable`. Found end-to-end by test/llm-action-battery.mjs; the
815
+ # census scripts had their own matching and never exercised this path. The base class is the
816
+ # segment after the `WindowsForms10.` prefix, taken before the next dot.
817
+ $base = $kc
818
+ if ($kc -like 'WindowsForms10.*') { $base = (($kc -split '\.')[1]) }
819
+ $kind = ''
820
+ if ($base -like 'Edit*' -or $base -like 'RichEdit*' -or $kc -like '*TextBox*') { $kind = 'text' }
821
+ elseif ($base -like 'BUTTON*' -or $base -like 'Button*' -or $kc -eq 'ComboBox') { $kind = 'click' }
822
+ if ($kind) {
823
+ $doorKinds += $kind
824
+ $childHandles += $kh
825
+ $doorHandles += @{ kind = $kind; hwnd = $kh }
826
+ }
827
+ }
828
+
829
+ # An element named by the caller always gets a UIA probe, even when a message door exists: the
830
+ # door tiers address a whole window, so 'click the Save button' cannot be expressed in them
831
+ # without coordinates. Naming an element is how a caller asks for a specific control instead of
832
+ # whichever one happens to be found first -- and 'first found' is not a contract, it is an
833
+ # accident of tree order that changes between app versions.
834
+ $hasPattern = $false
835
+ $patKind = 'none'
836
+ $uiaElement = $null
837
+ $uiaErr = ''
838
+ $uiaReason = ''
839
+ $scanProbed = $false
840
+
841
+ # A CLICK WITH COORDINATES IS RESOLVED AT THE POINT, never by tree order. See
842
+ # Resolve-WpmUiaElementAtPoint for what went wrong before this: the first descendant carrying a
843
+ # pattern was invoked regardless of x/y, so an unnamed click on a WPF/UWP/WinUI target acted on a
844
+ # control the caller never pointed at -- and answered ok:true. Naming an element (ElementName) is
845
+ # a different contract: there the caller asked for that control, so tree scan is correct.
846
+ $pointResolved = $false
847
+ if ($doorKinds.Count -eq 0 -and -not $ElementName -and $Action -eq 'click' -and $X -ge 0 -and $Y -ge 0) {
848
+ $pr = Resolve-WpmUiaElementAtPoint -Hwnd $Hwnd -X $X -Y $Y
849
+ $uiaErr = $pr.err
850
+ $uiaReason = $pr.reason
851
+ $pointResolved = $true
852
+ if ($pr.element) {
853
+ $hasPattern = $true
854
+ $patKind = $pr.patternKind
855
+ $uiaElement = $pr.element
856
+ }
857
+ } elseif ($doorKinds.Count -eq 0 -or $ElementName) {
858
+ $scanProbed = $true
859
+ try {
860
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
861
+ $cond = New-Object System.Windows.Automation.PropertyCondition(
862
+ [System.Windows.Automation.AutomationElement]::IsEnabledProperty, $true)
863
+ $found = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants, $cond)
864
+ $pats = Get-WpmUiaCached
865
+ $limit = [Math]::Min($found.Count, 200)
866
+ for ($i = 0; $i -lt $limit; $i++) {
867
+ $el = $found[$i]
868
+ if ($ElementName) {
869
+ # Match on Name or AutomationId. The two are different fields: Name is the visible label
870
+ # (localised, may change), AutomationId is the developer's id (stable). Accepting either
871
+ # keeps the caller from having to know which one a given app populates.
872
+ $nm = ''; $aid = ''
873
+ try { $nm = [string]$el.Current.Name } catch { }
874
+ try { $aid = [string]$el.Current.AutomationId } catch { }
875
+ if ($nm -ne $ElementName -and $aid -ne $ElementName) { continue }
876
+ }
877
+ foreach ($k in @('invoke', 'value', 'toggle', 'select', 'legacy')) {
878
+ if (-not $pats.ContainsKey($k)) { continue }
879
+ $obj = $null
880
+ try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
881
+ if ($obj) { $hasPattern = $true; $patKind = $k; $uiaElement = $el; break }
882
+ }
883
+ if ($hasPattern) { break }
884
+ }
885
+ } catch {
886
+ # NOT swallowed. A silent catch here made the probe report 'no pattern' on a target that
887
+ # demonstrably had one, and the engine then refused a perfectly reachable window -- with no
888
+ # diagnostic anywhere. The error travels out with the facts so a refusal can say why.
889
+ $uiaErr = $_.Exception.Message
890
+ }
891
+ }
892
+
893
+ # EMPTY TREE vs PATTERN-LESS CONTENT, measured rather than folded into one word. When the UIA
894
+ # probe ran and found nothing usable, two different worlds produce the same hasPattern=false:
895
+ # a tree that was never populated (the app has a11y off -- uTools walks to one shell Pane and
896
+ # zero content elements, and no amount of re-querying changes that), and a tree that is alive
897
+ # but offers nothing at the named point or element (ZCode/DSH walk to hundreds of elements).
898
+ # They get different refusal codes (decide.ps1), so this measurement runs only when the probe
899
+ # actually ran -- never to decorate a target whose message door already decided the route.
900
+ $uiaTreeEmpty = $false
901
+ # THE DIAGNOSIS ONLY APPLIES TO A WINDOW THAT HAS NO OTHER DOOR. This condition used to be just
902
+ # "the probe ran and found no pattern", which mislabels a whole class of target: name an element on a
903
+ # WinForms window and `engine.ps1` suppresses its message door (a window message cannot address "the
904
+ # control called X"), the UIA scan then finds nothing drivable, and the engine reported
905
+ # `uia_tree_empty` -- "the application has accessibility switched off, relaunch it with
906
+ # --force-renderer-accessibility". That advice is not merely useless for WinForms, it is WRONG about
907
+ # the cause: the window demonstrably has a real door, we shut it ourselves. Measured 2026-11-23: the
908
+ # WinForms positive control walks to three Panes carrying the controls' own names and automation ids
909
+ # through the MSAA bridge (content=0, so `Test-WpmUiaTreeHasContent` says "no content"), while the
910
+ # genuine a11y-off sample (uTools) and a bare desktop shell have the same shape -- so the tree alone
911
+ # cannot separate them. The door CAN: a target we measured a door on must not be diagnosed as
912
+ # accessibilty-off, whatever its tree looks like. Doors present => the honest code is `unreachable`
913
+ # ("nothing addressable at that name"), which points at a next step that exists.
914
+ if (-not $hasPattern -and ($pointResolved -or $scanProbed) -and ($doorKinds.Count -eq 0)) {
915
+ $uiaTreeEmpty = -not (Test-WpmUiaTreeHasContent $Hwnd)
916
+ }
917
+
918
+ # Elevation is now measured, not assumed. WpmWin::IsElevatedTarget compares the target's
919
+ # integrity RID against ours; a failure to read either side returns false rather than guessing,
920
+ # because guessing 'elevated' would refuse every window whose handle read failed. The flag is
921
+ # consumed by decide.ps1's table, which checks it BEFORE any capability -- so an elevated target
922
+ # is refused outright and never probed for doors it cannot answer.
923
+
924
+ $tpid = [WpmWin]::PidOf($Hwnd)
925
+ $elevated = [WpmWin]::IsElevatedTarget($tpid)
926
+
927
+ $facts = New-WpmFacts -Hwnd ($Hwnd.ToInt64().ToString()) -Family $fam `
928
+ -MessageDoor ($doorKinds.Count -gt 0) -HasPattern $hasPattern -PatternKind $patKind `
929
+ -Action $Action -FactsMeasured $true -ElevatedTarget $elevated `
930
+ -UiaTreeEmpty $uiaTreeEmpty -UiaProbeFailed ($uiaErr -ne '')
931
+
932
+ return @{
933
+ facts = $facts
934
+ cls = $cls
935
+ family = $fam
936
+ childHandles = $childHandles
937
+ doorHandles = $doorHandles
938
+ doorKinds = @($doorKinds | Sort-Object -Unique)
939
+ uiaElement = $uiaElement
940
+ uiaErr = $uiaErr
941
+ # Why there is no element, when there is none. Previously uiaErr was produced and then read by
942
+ # nobody (grep found zero consumers), so a point that resolved outside the target and a target
943
+ # whose tree cannot be walked at all reached the caller as the same sentence: 'no message door
944
+ # and no usable UIA pattern'. Two different worlds, one string -- and the fixes differ.
945
+ uiaReason = $uiaReason
946
+ # The two booleans that decide.ps1 splits 'unreachable' on travel INSIDE $facts, built through
947
+ # the typed constructor above -- deliberately NOT duplicated here. A second copy of a measured
948
+ # value in the same return object is the two-copies-drift bug this repo keeps meeting; the
949
+ # first live-instance run of this very change caught exactly that shape (facts said False
950
+ # while the raw measurement said True, because the constructor call had not been extended).
951
+ pointResolved = $pointResolved
952
+ pid = [WpmWin]::PidOf($Hwnd)
953
+ }
954
+ }
955
+
956
+ function Get-WpmFocusEntry {
957
+ # The focus table entry required by R2'.4: foreground HWND, the control that holds focus, and the
958
+ # owning thread id (needed for the input-queue join). Keyed by HWND, never by pid: on this
959
+ # desktop ApplicationFrameHost owns every UWP frame, so pid both misses the target's own
960
+ # CoreWindow and blames unrelated apps.
961
+ $g = [WpmWin]::GuiFocusOfForeground()
962
+ $fg = [WpmWin]::FgHandle()
963
+ return @{
964
+ fgHwnd = $fg.ToInt64().ToString()
965
+ fgPid = ([WpmWin]::PidOf($fg)).ToString()
966
+ activeHwnd = ([IntPtr]$g[0]).ToInt64().ToString()
967
+ focusHwnd = ([IntPtr]$g[1]).ToInt64().ToString()
968
+ threadId = $g[2]
969
+ lastInputAgeMs = [WpmWin]::LastInputAgeMs()
970
+ }
971
+ }
972
+
973
+ function Restore-WpmFocus {
974
+ <#
975
+ Put the foreground back, honouring the restore table. Returns the table's verdict plus what the
976
+ syscall actually did, so 'we decided to restore' and 'it worked' stay separate numbers.
977
+ #>
978
+ param([hashtable]$Entry, [string]$RaisedHwnd, [string]$TargetPid, [string]$RaisedElsewhere = '', [bool]$AlreadyRestored = $false)
979
+
980
+ # The foreground moved to a window that is NOT our target. That is never ours to reverse: either
981
+ # the target app opened its own window (a dialog, same pid) or a third party took the focus.
982
+ # This branch has to come first. An earlier version set RaisedHwnd to whatever held the
983
+ # foreground after the action, so a dialog launched by the action looked like "our raised window"
984
+ # and got restored away -- the exact failure R2'.6 exists to prevent, caught by the measurement
985
+ # rather than by review.
986
+ if ($RaisedElsewhere -and -not $RaisedHwnd) {
987
+ $ep = [WpmWin]::PidOf([IntPtr][int64]$RaisedElsewhere)
988
+ if ($TargetPid -and ("$ep" -eq "$TargetPid")) {
989
+ return @{ restore = $false; outcome = 'skip-dialog'; setFg = ''; joined = ''; fgAfter = $RaisedElsewhere
990
+ reason = 'the target app opened this window itself (same pid); restoring would close the dialog it just opened' }
991
+ }
992
+ return @{ restore = $false; outcome = 'skip-taken'; setFg = ''; joined = ''; fgAfter = $RaisedElsewhere
993
+ reason = 'a third-party window holds the foreground; never pull it from the owner' }
994
+ }
995
+
996
+ $cur = [WpmWin]::FgHandle()
997
+ $verdict = Get-WpmRestoreDecision -CurrentFg ($cur.ToInt64().ToString()) -RaisedHwnd $RaisedHwnd `
998
+ -TargetPid $TargetPid -CurrentFgPid ([WpmWin]::PidOf($cur)).ToString() `
999
+ -RaisedHappened ([bool]($RaisedHwnd -ne '')) -AlreadyRestored $AlreadyRestored
1000
+
1001
+ $res = @{ restore = $verdict.restore; outcome = $verdict.outcome; reason = $verdict.reason
1002
+ setFg = ''; joined = ''; fgAfter = '' }
1003
+
1004
+ if ($verdict.restore -and $Entry -and $Entry.fgHwnd) {
1005
+ $want = [IntPtr][int64]$Entry.fgHwnd
1006
+ if ([WpmWin]::IsWindow($want)) {
1007
+ $r = [WpmWin]::RestoreForeground($want)
1008
+ $parts = $r.Split('|')
1009
+ $res.setFg = $parts[0]; $res.joined = $parts[1]; $res.fgAfter = $parts[2]
1010
+ } else {
1011
+ # The window we would restore to no longer exists. Nothing legal is left to do: this process
1012
+ # may not move the owner's focus to a window it does not own, and the target window belongs
1013
+ # to another process. Reported so the caller can surface it instead of pretending.
1014
+ $res.outcome = 'skip-vanished'; $res.reason = 'the window that held focus before the action no longer exists'
1015
+ }
1016
+ }
1017
+ return $res
1018
+ }
1019
+
1020
+ # ==================================================================================================
1021
+ # 0.6.0 INPUT RELIABILITY: the read-back primitive, expressed as the fact it is and not as a verdict.
1022
+ # ==================================================================================================
1023
+
1024
+ function Read-WpmControlText {
1025
+ <#
1026
+ What the CONTROL says it holds, through WM_GETTEXT. Returns the control's own three numbers plus one
1027
+ derived flag, and the derivation is stated because it is the whole safety property of the feature:
1028
+
1029
+ exposesText = NOT (chars == 0 AND length > 0)
1030
+
1031
+ Measured 2026-11-23 on an ES_PASSWORD edit (findings 8.1): WM_GETTEXT returns an EMPTY string while
1032
+ WM_GETTEXTLENGTH returns the real length. That combination cannot mean "the field is empty" -- the
1033
+ control is reporting a length it refuses to spell out. Treating it as "empty, and therefore my write
1034
+ did not land" would be wrong twice over: it would report a mismatch that did not happen, and if the
1035
+ engine had tried to be cleverer and print what it read, a password field is exactly where printing a
1036
+ value stops being a diagnostic. So the read is reported as UNAVAILABLE, no text is carried anywhere,
1037
+ and the effect keeps the value the write itself earned.
1038
+ #>
1039
+ param([IntPtr]$Hwnd, [int]$TimeoutMs = 200)
1040
+ $length = -1
1041
+ try { $length = [WpmWin]::TextLength($Hwnd) } catch { }
1042
+ $r = [WpmWin]::ReadText($Hwnd, [uint32][Math]::Max(1, $TimeoutMs))
1043
+ $okRead = [bool]$r[0]
1044
+ $chars = [int]$r[1]
1045
+ $text = [string]$r[2]
1046
+ return @{
1047
+ ok = $okRead; chars = $chars; text = $text; length = $length
1048
+ exposesText = ($okRead -and -not ($chars -eq 0 -and $length -gt 0))
1049
+ truncated = ($okRead -and $length -gt 0 -and $chars -lt $length)
1050
+ reason = if (-not $okRead) { 'the timed read failed (target not answering within the budget)'
1051
+ } elseif ($chars -eq 0 -and $length -gt 0) { 'the control reports a length but no text (password-masked or equivalent)'
1052
+ } else { '' }
1053
+ }
1054
+ }
1055
+
1056
+ # ==================================================================================================
1057
+ # 0.7.0 DESKTOP CAPABILITIES: launch, clipboard, window. Three actions the product could not do
1058
+ # before, and none of them is a door: they take no target's message queue, choose no channel, and
1059
+ # produce no proof window -- so they live BESIDE Invoke-WpmAction rather than inside it. The door
1060
+ # discipline (point ownership, the restore table, the proof window) is not widened by any of this.
1061
+ # ==================================================================================================
1062
+
1063
+ function Start-WpmApp {
1064
+ <#
1065
+ Launch a program. The HOST half is what decides whether this may run at all (appLaunchAllowed and
1066
+ the exact-name whitelist, lib/index.js); by the time this function is reached the decision is made,
1067
+ and this file reports only what the OS did.
1068
+
1069
+ Why the return is a pid and NOT a window handle: measured, `Process.Start` returns while the app is
1070
+ still loading and MainWindowHandle is 0 (1348 ms cold for notepad). A launch that claimed a window it
1071
+ does not have yet would send every follow-up action to hwnd=0, so the window is waited for
1072
+ separately, by Wait-WpmAppWindow, and reported honestly when it has not appeared.
1073
+ #>
1074
+ param([string]$Target, [string[]]$Arguments = @(), [string]$WorkingDirectory = '')
1075
+ if (-not $Target) { return @{ ok = $false; reason = 'launch needs a target: an executable path or a resolvable program name' } }
1076
+ try {
1077
+ $psi = New-Object System.Diagnostics.ProcessStartInfo
1078
+ $psi.FileName = $Target
1079
+ $psi.UseShellExecute = $true # the documented way a shell start resolves .exe/app paths
1080
+ if ($Arguments -and $Arguments.Count -gt 0) {
1081
+ $psi.Arguments = ($Arguments -join ' ')
1082
+ # The arguments are joined into one command line here. That is what the OS takes; the AUDIT logs
1083
+ # them as given, because R1 in the plan says the whitelist cannot make parameters safe, only the
1084
+ # record can make a bad one reviewable.
1085
+ }
1086
+ if ($WorkingDirectory) { $psi.WorkingDirectory = $WorkingDirectory }
1087
+ $p = [System.Diagnostics.Process]::Start($psi)
1088
+ if (-not $p) { return @{ ok = $false; reason = 'the OS started nothing for this target' } }
1089
+ return @{ ok = $true; pid = [int]$p.Id; name = [string]$p.ProcessName;
1090
+ fileName = [string]$p.MainModule.FileName; target = $Target }
1091
+ } catch {
1092
+ # Access denied, missing file, bad working directory. Reported as a failure of THIS action, with the
1093
+ # OS's own sentence attached -- not folded into an engine refusal code it does not own.
1094
+ return @{ ok = $false; reason = 'start failed: ' + $_.Exception.Message }
1095
+ }
1096
+ }
1097
+
1098
+ function Wait-WpmAppWindow {
1099
+ <#
1100
+ Poll for the process's first real top-level window, up to `WaitMs`. Two answers, both honest:
1101
+ found -> { ok=true; hwnd=...; waitedMs }
1102
+ not yet -> { ok=true; hwnd=''; detail='window-not-yet'; waitedMs } -- NOT a failure. The program
1103
+ did start; pretending otherwise would make a slow launch look like a dead one, and
1104
+ pretending the window exists would send the next action to nothing.
1105
+ #>
1106
+ param([int]$ProcessId, [int]$WaitMs = 3000)
1107
+ $budget = [Math]::Max(0, [Math]::Min(30000, $WaitMs))
1108
+ $at = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1109
+ $deadline = $at + $budget
1110
+ while ($true) {
1111
+ $p = $null
1112
+ try { $p = Get-Process -Id $ProcessId -ErrorAction Stop } catch { $p = $null }
1113
+ if (-not $p) {
1114
+ return @{ ok = $false; hwnd = ''; reason = "process $ProcessId is gone"; waitedMs = [int]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $at) }
1115
+ }
1116
+ $h = [long]$p.MainWindowHandle
1117
+ # Refresh: MainWindowHandle is cached on the Process object, and the whole reason this loop exists
1118
+ # is that the first read is 0.
1119
+ if ($h -le 0) { try { $p.Refresh() } catch { }; $h = [long]$p.MainWindowHandle }
1120
+ if ($h -gt 0) {
1121
+ return @{ ok = $true; hwnd = $h.ToString(); waitedMs = [int]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $at);
1122
+ title = [string]$p.MainWindowTitle }
1123
+ }
1124
+ $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1125
+ if ($now -ge $deadline) {
1126
+ return @{ ok = $true; hwnd = ''; detail = 'window-not-yet'; waitedMs = [int]($now - $at);
1127
+ note = "the process is running but has published no top-level window within $budget ms; keep polling, or address it by pid"
1128
+ }
1129
+ }
1130
+ Start-Sleep -Milliseconds 50
1131
+ }
1132
+ }
1133
+
1134
+ function Get-WpmClipboard {
1135
+ <#
1136
+ Read the SYSTEM clipboard. R8 in the plan is the reason this is written carefully: what is in the
1137
+ clipboard may be a password or a token the owner copied seconds ago. So:
1138
+ * text is capped at 64 KB and a longer payload is TRUNCATED AND SAYING so (`truncated=true`),
1139
+ rather than either silently cutting or dumping the whole thing into a model's context;
1140
+ * the audit records op/format/length, never the content (lib/index.js owns the audit line);
1141
+ * a non-text, non-image clipboard answers `unsupported-format` with the format names it did find
1142
+ -- an empty success would be indistinguishable from "the clipboard is empty".
1143
+ Requires STA, which the worker already runs under (`powershell.exe -STA`); measured in findings 5.2.
1144
+ #>
1145
+ param([string]$Format = 'text', [int]$MaxChars = 65536)
1146
+ Add-Type -AssemblyName System.Windows.Forms
1147
+ $fmt = if ($Format -eq 'image') { 'image' } else { 'text' }
1148
+ try {
1149
+ if ($fmt -eq 'text') {
1150
+ if (-not [System.Windows.Forms.Clipboard]::ContainsText()) {
1151
+ return @{ ok = $false; reason = 'the clipboard holds no text'; formats = (Get-WpmClipboardFormats) }
1152
+ }
1153
+ $t = [System.Windows.Forms.Clipboard]::GetText()
1154
+ if ($null -eq $t) { $t = '' }
1155
+ $cap = [Math]::Max(1, $MaxChars)
1156
+ $truncated = $t.Length -gt $cap
1157
+ return @{ ok = $true; format = 'text'; chars = [int]$t.Length; text = $(if ($truncated) { $t.Substring(0, $cap) } else { $t }); truncated = $truncated }
1158
+ }
1159
+ if (-not [System.Windows.Forms.Clipboard]::ContainsImage()) {
1160
+ return @{ ok = $false; reason = 'the clipboard holds no image'; formats = (Get-WpmClipboardFormats) }
1161
+ }
1162
+ $img = [System.Windows.Forms.Clipboard]::GetImage()
1163
+ if (-not $img) { return @{ ok = $false; reason = 'the clipboard claimed an image and returned none' } }
1164
+ $dir = Join-Path (Get-WpmDataDir) 'clipboard'
1165
+ if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
1166
+ $id = 'clip-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1167
+ $file = Join-Path $dir ($id + '.png')
1168
+ $img.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
1169
+ $w = [int]$img.Width; $h = [int]$img.Height
1170
+ $img.Dispose()
1171
+ return @{ ok = $true; format = 'image'; file = $file; clipId = $id; width = $w; height = $h }
1172
+ } catch {
1173
+ # The clipboard is owned by whatever app last touched it and can be locked; that is a transient
1174
+ # state of the desktop, reported as a failure of this action with the OS's sentence attached.
1175
+ return @{ ok = $false; reason = 'clipboard read failed: ' + $_.Exception.Message }
1176
+ }
1177
+ }
1178
+
1179
+ function Get-WpmClipboardFormats {
1180
+ # The format NAMES, so a refusal can say what IS there instead of only what is not.
1181
+ try {
1182
+ $names = @([System.Windows.Forms.Clipboard]::GetDataObject().GetFormats())
1183
+ return @($names | ForEach-Object { [string]$_ } | Select-Object -First 12)
1184
+ } catch { return @() }
1185
+ }
1186
+
1187
+ function Set-WpmClipboard {
1188
+ <#
1189
+ Write the clipboard. `shotId` is accepted for an image so a screenshot can be pushed into the
1190
+ clipboard without the caller ever handling the pixels -- the same "the engine does the arithmetic"
1191
+ stance as space:"image" for a click. SetDataObject($true) flushes the data so it survives this
1192
+ process, which is the documented difference between a clipboard write and a clipboard promise.
1193
+ #>
1194
+ param([string]$Format = 'text', [string]$Text = '', [string]$ShotId = '')
1195
+ Add-Type -AssemblyName System.Windows.Forms
1196
+ Add-Type -AssemblyName System.Drawing
1197
+ $fmt = if ($Format -eq 'image') { 'image' } else { 'text' }
1198
+ try {
1199
+ if ($fmt -eq 'text') {
1200
+ if (-not $Text) { return @{ ok = $false; reason = 'clipboard write needs text; an empty write is indistinguishable from a clipboard the owner already cleared' } }
1201
+ [System.Windows.Forms.Clipboard]::Clear()
1202
+ # SetDataObject($value, $true), NOT Flush(): `Flush` is a .NET Core API and this engine's floor is
1203
+ # Windows PowerShell 5.1 (= .NET Framework 4.x), where the call does not exist. The first version
1204
+ # of this branch threw "Clipboard does not contain a method named 'Flush'" -- a method that exists
1205
+ # in the documentation people read and not in the runtime the product targets. The second argument
1206
+ # is what makes the data survive this process, which is the whole behaviour being asked for.
1207
+ [System.Windows.Forms.Clipboard]::SetDataObject($Text, $true)
1208
+ $back = ''
1209
+ try { $back = [string][System.Windows.Forms.Clipboard]::GetText() } catch { }
1210
+ return @{ ok = $true; format = 'text'; chars = [int]$Text.Length; readbackChars = [int]$back.Length;
1211
+ readbackMatches = ($back -ceq $Text) }
1212
+ }
1213
+ if (-not $ShotId) { return @{ ok = $false; reason = 'clipboard image write needs a shotId (the screenshot to put there) or a file' } }
1214
+ if (-not $script:WpmShots.ContainsKey($ShotId)) {
1215
+ return @{ ok = $false; stale = $true; reason = "shotId '$ShotId' is not a screenshot this worker still holds" }
1216
+ }
1217
+ $file = [string]$script:WpmShots[$ShotId].file
1218
+ if (-not (Test-Path -LiteralPath $file)) { return @{ ok = $false; reason = "the shot's PNG is no longer on disk: $file" } }
1219
+ # The shot's own recorded size travels along, so the engine can compare what the clipboard reports
1220
+ # against what was asked. Without it the image write has no prediction to check and would have to
1221
+ # claim success from "the clipboard now holds an image", which is a weaker statement than the text
1222
+ # path can make.
1223
+ $askedW = [int]$script:WpmShots[$ShotId].imageWidth
1224
+ $askedH = [int]$script:WpmShots[$ShotId].imageHeight
1225
+ $bmp = [System.Drawing.Image]::FromFile($file)
1226
+ try {
1227
+ [System.Windows.Forms.Clipboard]::Clear()
1228
+ [System.Windows.Forms.Clipboard]::SetDataObject($bmp, $true)
1229
+ } finally { $bmp.Dispose() }
1230
+ $ok = $false; $w = 0; $h = 0
1231
+ try {
1232
+ if ([System.Windows.Forms.Clipboard]::ContainsImage()) {
1233
+ $img = [System.Windows.Forms.Clipboard]::GetImage()
1234
+ $w = [int]$img.Width; $h = [int]$img.Height; $img.Dispose(); $ok = $true
1235
+ }
1236
+ } catch { }
1237
+ return @{ ok = $ok; format = 'image'; shotId = $ShotId; file = $file; width = $askedW; height = $askedH;
1238
+ readbackWidth = $w; readbackHeight = $h }
1239
+ } catch {
1240
+ return @{ ok = $false; reason = 'clipboard write failed: ' + $_.Exception.Message }
1241
+ }
1242
+ }
1243
+
1244
+ function Invoke-WpmWindowOp {
1245
+ <#
1246
+ One op on ONE window named by hwnd, and the verification is the OS's answer about the window, not
1247
+ the return value of the call. That distinction is the whole point of this function: ShowWindow and
1248
+ SetWindowPos return booleans about the CALL, and every action in this product that reported a call
1249
+ instead of a state has eventually turned out to be the lying kind.
1250
+ minimize -> IsIconic afterwards (must be true)
1251
+ restore -> IsIconic afterwards (must be false)
1252
+ move -> GetWindowRect afterwards (left/top must match what was asked)
1253
+ resize -> GetWindowRect afterwards (width/height must match, within 2px)
1254
+ topmost -> the WS_EX_TOPMOST bit, read back
1255
+ `topmost` is the promotion of `MakeTopmostNoActivate`, which shipped as a TEST-SUPPORT primitive
1256
+ (its comment says a model should not be able to topmost-raise arbitrary windows). 0.7.0 revisits
1257
+ that: it is now reachable, it never activates the window, and the result still reports the ex-style
1258
+ it read back -- see findings §5 for the reasoning that changed.
1259
+
1260
+ WHAT THIS FUNCTION DELIBERATELY DOES NOT REPORT: the foreground. `restore` activates by definition
1261
+ (SW_RESTORE is documented to bring the window up), so "did the owner lose focus" is a question about
1262
+ the moment around this call rather than about the state after it -- and engine.ps1 reads
1263
+ GetForegroundWindow on both sides and reports the pair, where this function can only see one.
1264
+ #>
1265
+ param([IntPtr]$Hwnd, [string]$Op, [int]$X = 0, [int]$Y = 0, [int]$Width = 0, [int]$Height = 0)
1266
+ if (-not $Hwnd -or -not [WpmWin]::IsWindow($Hwnd)) {
1267
+ return @{ ok = $false; refusal = 'no_hwnd'; reason = 'the hwnd does not identify a live window' }
1268
+ }
1269
+ $before = New-Object 'WpmWin+RECT'
1270
+ [void][WpmWin]::GetWindowRect($Hwnd, [ref]$before)
1271
+ switch ($Op) {
1272
+ 'minimize' {
1273
+ [void][WpmWin]::ShowWindow($Hwnd, [WpmWin]::SW_MINIMIZE)
1274
+ $iconic = [WpmWin]::IsIconic($Hwnd)
1275
+ return @{ ok = $iconic; op = $Op; iconic = $iconic;
1276
+ reason = $(if ($iconic) { '' } else { 'ShowWindow(SW_MINIMIZE) returned and the window is still not iconic' }) }
1277
+ }
1278
+ 'restore' {
1279
+ [void][WpmWin]::ShowWindow($Hwnd, [WpmWin]::SW_RESTORE)
1280
+ $iconic = [WpmWin]::IsIconic($Hwnd)
1281
+ return @{ ok = (-not $iconic); op = $Op; iconic = $iconic;
1282
+ reason = $(if ($iconic) { 'the window is still iconic after SW_RESTORE' } else { '' }) }
1283
+ }
1284
+ 'move' {
1285
+ # SWP_NOSIZE(1) | SWP_NOZORDER(4) | SWP_NOACTIVATE(10): a window move that stole the foreground
1286
+ # would be exactly the disturbance the rest of this product refuses to cause.
1287
+ $ok = [WpmWin]::SetWindowPos($Hwnd, [IntPtr]::Zero, $X, $Y, 0, 0, ([uint32]1 -bor [uint32]4 -bor [uint32]16))
1288
+ $r = New-Object 'WpmWin+RECT'
1289
+ [void][WpmWin]::GetWindowRect($Hwnd, [ref]$r)
1290
+ $moved = ($r.Left -eq $X -and $r.Top -eq $Y)
1291
+ return @{ ok = ($ok -and $moved); op = $Op; called = "$X,$Y"; rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)";
1292
+ before = "$($before.Left),$($before.Top),$($before.Right),$($before.Bottom)";
1293
+ reason = $(if (-not $ok) { 'SetWindowPos was refused' } elseif (-not $moved) { 'the call returned and the window did not land where it was told' } else { '' }) }
1294
+ }
1295
+ 'resize' {
1296
+ $w = [Math]::Max(1, $Width); $h = [Math]::Max(1, $Height)
1297
+ $ok = [WpmWin]::SetWindowPos($Hwnd, [IntPtr]::Zero, 0, 0, $w, $h, ([uint32]2 -bor [uint32]4 -bor [uint32]16))
1298
+ $r = New-Object 'WpmWin+RECT'
1299
+ [void][WpmWin]::GetWindowRect($Hwnd, [ref]$r)
1300
+ $cw = $r.Right - $r.Left; $ch = $r.Bottom - $r.Top
1301
+ # +-2 px: the window may clamp a size to its own minimum, and a 1px difference between the frame
1302
+ # the app asks for and the rect Windows reports is normal, not a lie worth failing the action over.
1303
+ $fits = ([Math]::Abs($cw - $w) -le 2) -and ([Math]::Abs($ch - $h) -le 2)
1304
+ return @{ ok = ($ok -and $fits); op = $Op; asked = "${w}x${h}"; size = "${cw}x${ch}";
1305
+ rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)";
1306
+ reason = $(if (-not $ok) { 'SetWindowPos was refused' } elseif (-not $fits) { 'the window came back a different size than was asked (a clamp, not a no-op)' } else { '' }) }
1307
+ }
1308
+ 'topmost' {
1309
+ $ok = [WpmWin]::MakeTopmostNoActivate($Hwnd)
1310
+ $ex = [WpmWin]::GetWindowLong($Hwnd, [WpmWin]::GWL_EXSTYLE)
1311
+ $isTop = ($ex -band [WpmWin]::WS_EX_TOPMOST) -ne 0
1312
+ return @{ ok = ($ok -and $isTop); op = $Op; exStyle = ('0x' + $ex.ToString('X'));
1313
+ topmost = $isTop; activated = 'no'
1314
+ reason = $(if (-not $isTop) { 'the WS_EX_TOPMOST bit is not set on the window after the call' } else { '' }) }
1315
+ }
1316
+ default {
1317
+ return @{ ok = $false; op = $Op; reason = "unknown window op '$Op'" }
1318
+ }
1319
+ }
1320
+ }
1321
+
1322
+ # ==================================================================================================
1323
+ # 0.5.0 READ PATHS: a frame the model can read, a picture whose coordinates are DATA, and a preview
1324
+ # that answers in text. None of the three writes an input-queue entry or takes the focus.
1325
+ # ==================================================================================================
1326
+
1327
+ function Get-WpmDataDir {
1328
+ # The same base the takeover latch uses (takeover.ps1 Get-WpmTakeoverLatchPath) and the host half
1329
+ # (lib/index.js abortLatchPath). One directory to open when something has to be inspected by hand.
1330
+ $base = $env:LOCALAPPDATA
1331
+ if (-not $base) { $base = [System.IO.Path]::GetTempPath() }
1332
+ return (Join-Path $base 'wpm')
1333
+ }
1334
+
1335
+ function Get-WpmShotsDir {
1336
+ $d = Join-Path (Get-WpmDataDir) 'shots'
1337
+ if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
1338
+ return $d
1339
+ }
1340
+
1341
+ function Get-WpmFrameRect {
1342
+ <#
1343
+ ONE frame rule, and the caller cannot silently get the wrong one.
1344
+ Returns @{ ok; frame='dwm'|'win32'|'none'; hr; left; top; right; bottom }.
1345
+ DWM(9 EXTENDED_FRAME_BOUNDS) is the ONLY source that agrees with the UIA children's coordinate
1346
+ space; GetWindowRect is the documented fallback for RDP/Basic-theme hosts where the DWM call
1347
+ returns a non-zero hr. Which one was used is a RETURNED FIELD, never a silent substitution.
1348
+ #>
1349
+ param([IntPtr]$Hwnd)
1350
+ $d = [WpmWin]::DwmFrame($Hwnd)
1351
+ if ($d[0] -eq 0 -and $d[3] -gt $d[1] -and $d[4] -gt $d[2]) {
1352
+ return @{ ok = $true; frame = 'dwm'; hr = 0
1353
+ left = [int]$d[1]; top = [int]$d[2]; right = [int]$d[3]; bottom = [int]$d[4] }
1354
+ }
1355
+ $w = [WpmWin]::WinRect($Hwnd)
1356
+ if ($w[0] -eq 1 -and $w[3] -gt $w[1] -and $w[4] -gt $w[2]) {
1357
+ return @{ ok = $true; frame = 'win32'; hr = [int]$d[0]
1358
+ left = [int]$w[1]; top = [int]$w[2]; right = [int]$w[3]; bottom = [int]$w[4] }
1359
+ }
1360
+ return @{ ok = $false; frame = 'none'; hr = [int]$d[0]; left = 0; top = 0; right = 0; bottom = 0 }
1361
+ }
1362
+
1363
+ function Test-WpmFrameInsideRoot {
1364
+ <#
1365
+ The DECIDABLE frame check. "Every element rect is inside screenRect" was measured to be FALSE on
1366
+ real windows -- Chromium/Electron trees report virtualized content far outside the viewport
1367
+ (overhangs of 3px, 18px, 287px and 2720px measured here on 2026-11-23), so that rule refuses
1368
+ ordinary windows. What holds is narrower and still worth asserting: the frame we CAPTURED must lie
1369
+ inside the window's own rect as the accessibility tree reports it (the ROOT element's
1370
+ BoundingRectangle, which measures equal to GetWindowRect -- the shadow space). Measured insets on 8
1371
+ real windows: exactly 0,0,0,0 (borderless) or 8,8,8,8 (shadowed). A frame that pokes OUTSIDE the
1372
+ root means the frame came from somewhere else, and refusing there is what keeps a wrong frame from
1373
+ ever becoming a label.
1374
+ #>
1375
+ param([hashtable]$Frame, [hashtable]$RootRect, [int]$Tolerance = 2)
1376
+ $insetL = [int]$Frame.left - [int]$RootRect.left
1377
+ $insetT = [int]$Frame.top - [int]$RootRect.top
1378
+ $insetR = [int]$RootRect.right - [int]$Frame.right
1379
+ $insetB = [int]$RootRect.bottom - [int]$Frame.bottom
1380
+ $ok = ($insetL -ge -$Tolerance) -and ($insetT -ge -$Tolerance) -and
1381
+ ($insetR -ge -$Tolerance) -and ($insetB -ge -$Tolerance)
1382
+ return @{ ok = $ok; insetLeft = $insetL; insetTop = $insetT; insetRight = $insetR; insetBottom = $insetB }
1383
+ }
1384
+
1385
+ function Get-WpmSnapshotTree {
1386
+ <#
1387
+ Walk the tree ONCE (FindAll(Descendants) + IsOffscreen), number what is visible, and hand back a
1388
+ frame the model can answer with. Measured: 816 descendants / 71 visible / 291ms on an Electron
1389
+ window, so TreeWalker (one cross-process COM round trip per node) is the wrong tool here and the
1390
+ 300-element cap is deliberately loose.
1391
+
1392
+ '0 element(s)' is a REAL answer on this desktop (Clash, Everything measured 0) and is reported as
1393
+ such; it deliberately does NOT reuse uia_tree_empty, whose meaning is "UI Automation is switched
1394
+ off in the application" and whose next step is relaunching the app.
1395
+
1396
+ `interactableOnly` (default on) is the zero-cost first pass at a huge tree. `sinceSnapId` returns
1397
+ added/removed/changed instead of re-describing an unchanged table -- the measured cost of a
1398
+ multi-step flow is repeating the parts that did not move.
1399
+ #>
1400
+ param(
1401
+ [IntPtr]$Hwnd,
1402
+ [int]$MaxElements = 300,
1403
+ [bool]$InteractableOnly = $true,
1404
+ [string]$Intent = '',
1405
+ [string]$SinceSnapId = ''
1406
+ )
1407
+ $cap = [Math]::Max(1, [Math]::Min(5000, $MaxElements))
1408
+
1409
+ # The diff base is resolved BEFORE the walk: an unknown sinceSnapId is a stale reference, not an
1410
+ # empty diff. Returning "no changes" for an id we never issued would be the most comfortable lie here.
1411
+ $base = $null
1412
+ if ($SinceSnapId) {
1413
+ foreach ($s in @($script:WpmSnapshots)) {
1414
+ if ($s -and $s.snapId -eq $SinceSnapId) { $base = $s; break }
1415
+ }
1416
+ if (-not $base) {
1417
+ return @{ ok = $false; stale = $true
1418
+ reason = "sinceSnapId '$SinceSnapId' is not a snapshot this worker still holds (it keeps the newest as a label base and the one before it as a diff base); take a new snapshot and diff against that id" }
1419
+ }
1420
+ }
1421
+
1422
+ $frame = Get-WpmFrameRect $Hwnd
1423
+ if (-not $frame.ok) {
1424
+ return @{ ok = $false; stale = $false; frameCheck = 'unknown'
1425
+ reason = "no usable window frame: DwmGetWindowAttribute hr=$($frame.hr) and GetWindowRect both failed, so there is no rectangle to measure elements against" }
1426
+ }
1427
+
1428
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1429
+
1430
+ # ---- THE DECIDABLE SELF-CHECK ------------------------------------------------------------------
1431
+ # The obvious invariant -- "every element rect is contained in screenRect" -- was MEASURED to be
1432
+ # false on real windows and is therefore NOT used: Chromium/Electron trees legitimately report
1433
+ # virtualized content far outside the viewport (overhangs measured 3px, 18px, 287px and 2720px on
1434
+ # this desktop, 2026-11-23), and a rule that refuses those snapshots refuses whole classes of
1435
+ # ordinary windows. What IS decidable and cheap is the relationship the two coordinate sources
1436
+ # state about the window itself: the ROOT element's rect (the tree's own claim, which measures equal
1437
+ # to GetWindowRect -- shadow space) must CONTAIN the frame we captured. Measured on 8 real windows:
1438
+ # it holds with insets of exactly 0px (borderless) or 8px/8px/8px/8px (shadowed), and a frame that
1439
+ # pokes outside the root means the frame came from somewhere else. The inset is REPORTED as data so
1440
+ # the shadow is visible instead of merely survived.
1441
+ $frameCheck = 'unknown'
1442
+ $insetL = 0; $insetT = 0; $insetR = 0; $insetB = 0
1443
+ try {
1444
+ $rb = $root.Current.BoundingRectangle
1445
+ $rootRect = @{
1446
+ left = [int][Math]::Round($rb.Left); top = [int][Math]::Round($rb.Top)
1447
+ right = [int][Math]::Round($rb.Right); bottom = [int][Math]::Round($rb.Bottom)
1448
+ }
1449
+ $inside = Test-WpmFrameInsideRoot -Frame $frame -RootRect $rootRect
1450
+ $insetL = [int]$inside.insetLeft; $insetT = [int]$inside.insetTop
1451
+ $insetR = [int]$inside.insetRight; $insetB = [int]$inside.insetBottom
1452
+ $frameCheck = if ($inside.ok) { 'pass' } else { 'fail' }
1453
+ if ($frameCheck -eq 'fail') {
1454
+ return @{ ok = $false; stale = $false; frame = $frame.frame; frameCheck = 'fail'
1455
+ reason = "frame self-check failed: the captured frame ($($frame.left),$($frame.top),$($frame.right),$($frame.bottom), source=$($frame.frame)) is not contained in the window's own rect ($($rootRect.left),$($rootRect.top),$($rootRect.right),$($rootRect.bottom)) that the accessibility tree reports. The two sources disagree about where this window is, so no label from this snapshot is safe to act on. Re-read action=windows and compare rect= with this frame" }
1456
+ }
1457
+ } catch {
1458
+ # An unreadable root rect cannot certify anything, and it must not be turned into a failure: the
1459
+ # snapshot itself may still be useful, so the check reports 'unknown' rather than 'pass'.
1460
+ $frameCheck = 'unknown'
1461
+ }
1462
+
1463
+ $all = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,
1464
+ [System.Windows.Automation.Condition]::TrueCondition)
1465
+ $total = $all.Count
1466
+ $pats = Get-WpmUiaCached
1467
+ $order = @('invoke', 'value', 'toggle', 'select', 'legacy')
1468
+ $rows = @()
1469
+ $truncated = $false
1470
+ $outsideFrame = 0
1471
+
1472
+ for ($i = 0; $i -lt $total; $i++) {
1473
+ $el = $all[$i]
1474
+ $off = $false
1475
+ try { $off = [bool]$el.Current.IsOffscreen } catch { continue }
1476
+ if ($off) { continue }
1477
+
1478
+ $ct = ''; $nm = ''; $aid = ''
1479
+ try { $ct = ([string]$el.Current.ControlType.ProgrammaticName) -replace '^ControlType\.', '' } catch { continue }
1480
+ try { $nm = [string]$el.Current.Name } catch { }
1481
+ try { $aid = [string]$el.Current.AutomationId } catch { }
1482
+
1483
+ # Sub-element rects are in the DWM/real space (measured); the ROOT element is the one that reports
1484
+ # the shadow-inclusive rect, and FindAll(Descendants) never returns the root -- so nothing here
1485
+ # mixes the two spaces.
1486
+ $rc = @{ left = 0; top = 0; right = 0; bottom = 0 }
1487
+ try {
1488
+ $b = $el.Current.BoundingRectangle
1489
+ $rc = @{
1490
+ left = [int][Math]::Round($b.Left); top = [int][Math]::Round($b.Top)
1491
+ right = [int][Math]::Round($b.Right); bottom = [int][Math]::Round($b.Bottom)
1492
+ }
1493
+ } catch { }
1494
+
1495
+ # A label exists to be POINTED AT inside the capture. An element with no overlap with the frame
1496
+ # cannot be clicked within it (the point-ownership assertion would refuse), so handing out a
1497
+ # number for it would hand out a trap. It is excluded and COUNTED, never silently dropped.
1498
+ $overlaps = ($rc.right -gt $frame.left) -and ($rc.left -lt $frame.right) -and
1499
+ ($rc.bottom -gt $frame.top) -and ($rc.top -lt $frame.bottom)
1500
+ if (-not $overlaps) { $outsideFrame++; continue }
1501
+
1502
+ $kinds = @()
1503
+ foreach ($k in $order) {
1504
+ if (-not $pats.ContainsKey($k)) { continue }
1505
+ $obj = $null
1506
+ try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
1507
+ if ($obj) { $kinds += $k }
1508
+ }
1509
+ if ($InteractableOnly -and $kinds.Count -eq 0) { continue }
1510
+
1511
+ if ($rows.Count -ge $cap) { $truncated = $true; break }
1512
+
1513
+ $rid = ''
1514
+ try { $rid = (@($el.GetRuntimeId()) -join '.') } catch { $rid = '' }
1515
+
1516
+ $rows += @{
1517
+ label = ($rows.Count + 1)
1518
+ controlType = $ct
1519
+ name = $nm
1520
+ automationId = $aid
1521
+ runtimeId = $rid
1522
+ rect = $rc
1523
+ patterns = @($kinds)
1524
+ }
1525
+ }
1526
+
1527
+ # ---- the delta, by UIA RuntimeId (measured stable across queries, 71/71) --------------------
1528
+ $delta = $null
1529
+ if ($base) {
1530
+ $oldByRid = @{}
1531
+ foreach ($r in @($base.elements)) { if ($r.runtimeId) { $oldByRid[$r.runtimeId] = $r } }
1532
+ $newByRid = @{}
1533
+ foreach ($r in $rows) { if ($r.runtimeId) { $newByRid[$r.runtimeId] = $r } }
1534
+ $added = @(); $removed = @(); $changed = @(); $same = 0
1535
+ foreach ($r in $rows) {
1536
+ if (-not $r.runtimeId) { continue }
1537
+ if (-not $oldByRid.ContainsKey($r.runtimeId)) { $added += $r; continue }
1538
+ $o = $oldByRid[$r.runtimeId]
1539
+ $why = @()
1540
+ if ([string]$o.name -ne [string]$r.name) { $why += 'name' }
1541
+ if ([string]$o.controlType -ne [string]$r.controlType) { $why += 'controlType' }
1542
+ if ([string]$o.automationId -ne [string]$r.automationId) { $why += 'automationId' }
1543
+ if (([int]$o.rect.left -ne [int]$r.rect.left) -or ([int]$o.rect.top -ne [int]$r.rect.top) -or
1544
+ ([int]$o.rect.right -ne [int]$r.rect.right) -or ([int]$o.rect.bottom -ne [int]$r.rect.bottom)) { $why += 'rect' }
1545
+ if ((@($o.patterns) -join ',') -ne (@($r.patterns) -join ',')) { $why += 'patterns' }
1546
+ if ($why.Count -gt 0) {
1547
+ $changed += @{ label = $r.label; controlType = $r.controlType; name = $r.name
1548
+ automationId = $r.automationId; rect = $r.rect; patterns = @($r.patterns); changed = $why }
1549
+ } else { $same++ }
1550
+ }
1551
+ foreach ($o in @($base.elements)) {
1552
+ if (-not $o.runtimeId) { continue }
1553
+ if (-not $newByRid.ContainsKey($o.runtimeId)) {
1554
+ $removed += @{ label = $o.label; controlType = $o.controlType; name = $o.name
1555
+ automationId = $o.automationId; rect = $o.rect; patterns = @($o.patterns) }
1556
+ }
1557
+ }
1558
+ $delta = @{ sinceSnapId = $base.snapId; added = @($added); removed = @($removed)
1559
+ changed = @($changed); unchanged = $same }
1560
+ }
1561
+
1562
+ $script:WpmSnapSeq = $script:WpmSnapSeq + 1
1563
+ $snapId = 'snap-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + '-' + $script:WpmSnapSeq
1564
+ $entry = @{
1565
+ snapId = $snapId
1566
+ hwnd = $Hwnd.ToInt64().ToString()
1567
+ frame = $frame.frame
1568
+ frameCheck = $frameCheck
1569
+ frameInset = @{ left = $insetL; top = $insetT; right = $insetR; bottom = $insetB }
1570
+ intent = $Intent
1571
+ createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1572
+ total = $total
1573
+ count = $rows.Count
1574
+ outsideFrame = $outsideFrame
1575
+ truncated = $truncated
1576
+ elements = @($rows)
1577
+ }
1578
+ # Newest first. Capacity 2, for one reason each: [0] resolves LABEL references, [1] is the only
1579
+ # valid sinceSnapId. Dropping the older one is what makes a superseded snapId a reportable
1580
+ # stale_ref instead of a silent success against a frame the caller can no longer see.
1581
+ $prev = @($script:WpmSnapshots)
1582
+ $script:WpmSnapshots = @($entry) + @($prev | Select-Object -First 1)
1583
+
1584
+ # The intent travels WITH the frame as a file too, so a deciding subagent (or a human reading the
1585
+ # directory afterwards) gets "what this frame was for" without the conversation around it. One file,
1586
+ # overwritten each snapshot: bounded by construction.
1587
+ try {
1588
+ $dataDir = Get-WpmDataDir
1589
+ if (-not (Test-Path -LiteralPath $dataDir)) { New-Item -ItemType Directory -Force -Path $dataDir | Out-Null }
1590
+ $payload = $entry | ConvertTo-Json -Depth 8 -Compress
1591
+ [System.IO.File]::WriteAllText((Join-Path $dataDir 'last-snapshot.json'), $payload,
1592
+ (New-Object System.Text.UTF8Encoding($false)))
1593
+ } catch { }
1594
+
1595
+ return @{ ok = $true; stale = $false; snapId = $snapId; frame = $frame.frame; frameCheck = $frameCheck
1596
+ frameInset = @{ left = $insetL; top = $insetT; right = $insetR; bottom = $insetB }
1597
+ intent = $Intent; total = $total; count = $rows.Count; outsideFrame = $outsideFrame
1598
+ truncated = $truncated; elements = @($rows); delta = $delta }
1599
+ }
1600
+
1601
+ function Resolve-WpmSnapshotLabel {
1602
+ <#
1603
+ Resolve a snapshot LABEL back to the ELEMENT (by UIA RuntimeId), so a labelled action keeps the
1604
+ silent UIA-pattern path and never degrades into a coordinate click. Every failure to resolve is a
1605
+ stale reference, not a guess: the frame the caller read is gone.
1606
+ #>
1607
+ param([IntPtr]$Hwnd, [int]$Label, [string]$SnapId)
1608
+ $snap = $null
1609
+ $all = @($script:WpmSnapshots)
1610
+ if ($all.Count -gt 0) { $snap = $all[0] }
1611
+ if (-not $snap) {
1612
+ return @{ ok = $false; stale = $true; reason = 'no snapshot has been taken by this worker; take one and act on its labels' }
1613
+ }
1614
+ if ($SnapId -and $SnapId -ne $snap.snapId) {
1615
+ return @{ ok = $false; stale = $true
1616
+ reason = "snapId '$SnapId' was superseded by '$($snap.snapId)'; a label only means something inside the frame that printed it, so take a new snapshot" }
1617
+ }
1618
+ if ([string]$snap.hwnd -ne $Hwnd.ToInt64().ToString()) {
1619
+ return @{ ok = $false; stale = $true
1620
+ reason = "the newest snapshot is of hwnd=$($snap.hwnd), not this target; take a snapshot of this window" }
1621
+ }
1622
+ $row = $null
1623
+ foreach ($r in @($snap.elements)) { if ([int]$r.label -eq $Label) { $row = $r; break } }
1624
+ if (-not $row) {
1625
+ return @{ ok = $false; stale = $true
1626
+ reason = "label $Label is not in snapshot $($snap.snapId) (it printed $($snap.count) element(s))" }
1627
+ }
1628
+ if (-not $row.runtimeId) {
1629
+ return @{ ok = $false; stale = $true
1630
+ reason = "label $Label carried no stable runtime id, so it cannot be re-found; take a new snapshot" }
1631
+ }
1632
+ $el = $null
1633
+ try {
1634
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1635
+ $found = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,
1636
+ [System.Windows.Automation.Condition]::TrueCondition)
1637
+ for ($i = 0; $i -lt $found.Count; $i++) {
1638
+ $cand = $found[$i]
1639
+ $rid = ''
1640
+ try { $rid = (@($cand.GetRuntimeId()) -join '.') } catch { continue }
1641
+ if ($rid -eq $row.runtimeId) { $el = $cand; break }
1642
+ }
1643
+ } catch {
1644
+ return @{ ok = $false; stale = $true; reason = 'the tree could not be re-walked: ' + $_.Exception.Message }
1645
+ }
1646
+ if (-not $el) {
1647
+ return @{ ok = $false; stale = $true
1648
+ reason = "the element behind label $Label is no longer in the tree; take a new snapshot" }
1649
+ }
1650
+ $pats = Get-WpmUiaCached
1651
+ $kind = 'none'
1652
+ foreach ($k in @('invoke', 'value', 'toggle', 'select', 'legacy')) {
1653
+ if (-not $pats.ContainsKey($k)) { continue }
1654
+ $obj = $null
1655
+ try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
1656
+ if ($obj) { $kind = $k; break }
1657
+ }
1658
+ if ($kind -eq 'none') {
1659
+ return @{ ok = $false; stale = $true
1660
+ reason = "the element behind label $Label no longer exposes a usable UIA pattern; take a new snapshot" }
1661
+ }
1662
+ return @{ ok = $true; stale = $false; element = $el; patternKind = $kind; row = $row; snapId = $snap.snapId }
1663
+ }
1664
+
1665
+ function Get-WpmScreenshot {
1666
+ <#
1667
+ CopyFromScreen over the DWM frame (or the virtual screen on explicit request) and return the
1668
+ MAPPING as data. Why the picture is not returned inline: a plugin cannot mint an inline image
1669
+ block without the host's attachment service (measured: ImageBlock needs an ImageAttachmentRef from
1670
+ an app.asar-only package), so the file is written and the caller reads it. What this action is
1671
+ really for is the second half: `scale`/`identity`/`screenRect` let a caller hand IMAGE coordinates
1672
+ back to click space:'image' and never multiply anything itself.
1673
+
1674
+ scale = imagePixels / screenPixels. identity is true only when scale==1.0. Nothing is resampled
1675
+ unless maxWidth asked for it, because a resized image IS a different coordinate system.
1676
+ #>
1677
+ param([IntPtr]$Hwnd, [bool]$FullScreen = $false, [int]$MaxWidth = 0, [int]$Keep = 10)
1678
+ Add-Type -AssemblyName System.Drawing
1679
+
1680
+ if ($FullScreen) {
1681
+ $vs = [WpmWin]::VirtualScreen()
1682
+ $frame = @{ ok = $true; frame = 'dwm'; hr = 0
1683
+ left = [int]$vs[0]; top = [int]$vs[1]; right = ([int]$vs[0] + [int]$vs[2]); bottom = ([int]$vs[1] + [int]$vs[3]) }
1684
+ } else {
1685
+ $frame = Get-WpmFrameRect $Hwnd
1686
+ if (-not $frame.ok) {
1687
+ return @{ ok = $false
1688
+ reason = "no usable window frame: DwmGetWindowAttribute hr=$($frame.hr) and GetWindowRect both failed" }
1689
+ }
1690
+ }
1691
+
1692
+ $w = $frame.right - $frame.left
1693
+ $h = $frame.bottom - $frame.top
1694
+ if ($w -le 0 -or $h -le 0) { return @{ ok = $false; reason = "the captured rectangle is empty ($($w)x$($h))" } }
1695
+
1696
+ $bmp = $null
1697
+ $resized = $null
1698
+ $hbmp = [IntPtr]::Zero
1699
+ # THE PATH IS REPORTED, NEVER SWAPPED SILENTLY. Same discipline as `frame`: 'dwm' versus 'win32' is a
1700
+ # coordinate fact, and 'bitblt' versus 'gdiplus' is a content fact (a 32bppRgb surface instead of
1701
+ # 32bppArgb, and any difference in what an occluded window paints). A caller comparing two screenshots
1702
+ # has to be able to see that the producer changed, so the field is mandatory in the result.
1703
+ $captureBackend = 'gdiplus'
1704
+ $captureNote = ''
1705
+ try {
1706
+ $capReason = ''
1707
+ try { $hbmp = [WpmWin]::CaptureBitBlt($frame.left, $frame.top, $w, $h, [ref]$capReason) }
1708
+ catch { $hbmp = [IntPtr]::Zero; $capReason = $_.Exception.Message }
1709
+ if ($hbmp -ne [IntPtr]::Zero) {
1710
+ try {
1711
+ $bmp = [System.Drawing.Image]::FromHbitmap($hbmp)
1712
+ $captureBackend = 'bitblt'
1713
+ } catch {
1714
+ # FromHbitmap can refuse (a format it cannot map). That is a capture failure, not a crash, and
1715
+ # the fallback below is the documented answer -- an exception here would turn a fast path into a
1716
+ # lost screenshot.
1717
+ $bmp = $null
1718
+ $capReason = 'FromHbitmap: ' + $_.Exception.Message
1719
+ } finally {
1720
+ [void][WpmWin]::FreeHbitmap($hbmp)
1721
+ $hbmp = [IntPtr]::Zero
1722
+ }
1723
+ }
1724
+ if (-not $bmp) {
1725
+ $captureNote = "bitblt-unavailable($capReason)"
1726
+ $bmp = New-Object System.Drawing.Bitmap($w, $h)
1727
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
1728
+ try { $g.CopyFromScreen($frame.left, $frame.top, 0, 0, (New-Object System.Drawing.Size($w, $h))) }
1729
+ finally { $g.Dispose() }
1730
+ $captureBackend = 'gdiplus'
1731
+ }
1732
+
1733
+ $scale = 1.0
1734
+ $imgW = $w
1735
+ $imgH = $h
1736
+ $out = $bmp
1737
+ $cap = [Math]::Max(0, [Math]::Min(7680, $MaxWidth))
1738
+ if ($cap -gt 0 -and $w -gt $cap) {
1739
+ $imgW = $cap
1740
+ $imgH = [int][Math]::Max(1, [Math]::Round($h * ($cap / [double]$w)))
1741
+ $resized = New-Object System.Drawing.Bitmap($imgW, $imgH)
1742
+ $g2 = [System.Drawing.Graphics]::FromImage($resized)
1743
+ try {
1744
+ $g2.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
1745
+ $g2.DrawImage($bmp, 0, 0, $imgW, $imgH)
1746
+ } finally { $g2.Dispose() }
1747
+ $out = $resized
1748
+ $scale = [Math]::Round($imgW / [double]$w, 6)
1749
+ }
1750
+
1751
+ $dir = Get-WpmShotsDir
1752
+ $script:WpmShotSeq = $script:WpmShotSeq + 1
1753
+ $shotId = 'shot-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + '-' + $script:WpmShotSeq
1754
+ $file = Join-Path $dir ($shotId + '.png')
1755
+ $out.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
1756
+ $bytes = (Get-Item -LiteralPath $file).Length
1757
+ $keepN = [Math]::Max(1, [Math]::Min(200, $Keep))
1758
+
1759
+ # Retention: newest `shotsKeep` survive, older PNGs in THIS directory are deleted. The registry is
1760
+ # pruned against the same list, so a shotId that was cleaned up resolves to stale_ref rather than
1761
+ # to a file that is no longer there.
1762
+ $files = @(Get-ChildItem -LiteralPath $dir -Filter '*.png' -File -ErrorAction SilentlyContinue |
1763
+ Sort-Object LastWriteTimeUtc -Descending)
1764
+ for ($i = $keepN; $i -lt $files.Count; $i++) {
1765
+ try { Remove-Item -LiteralPath $files[$i].FullName -Force } catch { }
1766
+ }
1767
+ $script:WpmShots[$shotId] = @{
1768
+ shotId = $shotId; file = $file; scale = $scale; identity = ($scale -eq 1.0)
1769
+ left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom
1770
+ imageWidth = [int]$imgW; imageHeight = [int]$imgH; frame = $frame.frame
1771
+ captureBackend = $captureBackend
1772
+ createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1773
+ }
1774
+ # Drop registry entries for shots the retention pass just removed.
1775
+ $live = @{}
1776
+ for ($i = 0; $i -lt [Math]::Min($keepN, $files.Count); $i++) { $live[$files[$i].BaseName] = $true }
1777
+ foreach ($key in @($script:WpmShots.Keys)) {
1778
+ if (-not $live.ContainsKey($key)) { $script:WpmShots.Remove($key) }
1779
+ }
1780
+
1781
+ return @{ ok = $true
1782
+ shotId = $shotId; file = $file
1783
+ screenRect = @{ left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom }
1784
+ imageSize = @{ width = [int]$imgW; height = [int]$imgH }
1785
+ scale = $scale; identity = ($scale -eq 1.0); frame = $frame.frame
1786
+ captureBackend = $captureBackend; captureNote = $captureNote
1787
+ dpiAware = [bool]$script:WpmDpiAware; bytes = [long]$bytes; shotsKeep = $keepN
1788
+ capturedAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }
1789
+ } finally {
1790
+ if ($hbmp -ne [IntPtr]::Zero) { [void][WpmWin]::FreeHbitmap($hbmp) }
1791
+ if ($resized) { $resized.Dispose() }
1792
+ if ($bmp) { $bmp.Dispose() }
1793
+ }
1794
+ }
1795
+
1796
+ function Convert-WpmImagePoint {
1797
+ <#
1798
+ THE MULTIPLICATION THE MODEL MUST NOT DO. space:'image' + shotId -> a screen point, using the
1799
+ scale the screenshot itself reported. screenX = screenRect.left + round(imageX / scale), which is
1800
+ the inverse of scale = imagePixels/screenPixels; a shot that was never issued, or one the
1801
+ retention policy already deleted, answers ok=false so the caller can report stale_ref instead of
1802
+ reinterpreting image pixels as screen pixels.
1803
+ #>
1804
+ param([string]$ShotId, [int]$X, [int]$Y)
1805
+ if (-not $ShotId) { return @{ ok = $false; stale = $true; reason = 'space="image" needs a shotId: image coordinates only exist relative to a capture' } }
1806
+ if (-not $script:WpmShots.ContainsKey($ShotId)) {
1807
+ return @{ ok = $false; stale = $true
1808
+ reason = "shotId '$ShotId' is not a screenshot this worker still holds (the retention policy keeps the newest shotsKeep); take a new screenshot" }
1809
+ }
1810
+ $shot = $script:WpmShots[$ShotId]
1811
+ $scale = [double]$shot.scale
1812
+ if ($scale -le 0) { return @{ ok = $false; stale = $true; reason = "shotId '$ShotId' has a non-positive scale ($scale)" } }
1813
+ if ($X -lt 0 -or $Y -lt 0 -or $X -ge [int]$shot.imageWidth -or $Y -ge [int]$shot.imageHeight) {
1814
+ return @{ ok = $false; stale = $false
1815
+ reason = "image point ($X,$Y) is outside the captured image ($($shot.imageWidth)x$($shot.imageHeight)); an image coordinate must address a pixel that exists" }
1816
+ }
1817
+ $sx = [int]$shot.left + [int][Math]::Round($X / $scale)
1818
+ $sy = [int]$shot.top + [int][Math]::Round($Y / $scale)
1819
+ return @{ ok = $true; stale = $false; x = $sx; y = $sy; scale = $scale; shotId = $ShotId }
1820
+ }
1821
+
1822
+ function Get-WpmPreviewAt {
1823
+ <#
1824
+ WHAT IS UNDER THAT POINT -- answered by the OS, as text. This is the confirmation step that makes
1825
+ an irreversible click reviewable without a picture: AutomationElement.FromPoint plus the
1826
+ ancestry proof the click path already uses (if the climb never meets the target root, the point
1827
+ belongs to another window and the answer is a refusal). No input queue entry, no focus change:
1828
+ the marker is drawn by the caller through overlay.ps1, which is a click-through request.
1829
+ #>
1830
+ param([IntPtr]$Hwnd, [int]$X, [int]$Y)
1831
+ $out = @{ ok = $true; outside = $false; atPoint = $false; name = ''
1832
+ controlType = ''; automationId = ''
1833
+ rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1834
+ reason = '' }
1835
+ try {
1836
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1837
+ if (-not $root) {
1838
+ return @{ ok = $false; outside = $false; atPoint = $false; name = ''; controlType = ''
1839
+ automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1840
+ reason = 'target window has no UI Automation element' }
1841
+ }
1842
+ $pt = New-Object System.Windows.Point([double]$X, [double]$Y)
1843
+ $hitEl = [System.Windows.Automation.AutomationElement]::FromPoint($pt)
1844
+ if (-not $hitEl) {
1845
+ $out.reason = 'nothing at that point is exposed to UI Automation'
1846
+ return $out
1847
+ }
1848
+ $out.atPoint = $true
1849
+
1850
+ $walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker
1851
+ $el = $hitEl
1852
+ $sawRoot = $false
1853
+ $hop = 0
1854
+ while ($el -and $hop -lt 24) {
1855
+ if ($el -eq $root) { $sawRoot = $true; break }
1856
+ try { $el = $walker.GetParent($el) } catch { $el = $null }
1857
+ $hop++
1858
+ }
1859
+ if (-not $sawRoot) {
1860
+ return @{ ok = $false; outside = $true; atPoint = $true; name = ''; controlType = ''
1861
+ automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1862
+ reason = 'the element under that point does not belong to the target window' }
1863
+ }
1864
+
1865
+ try { $out.controlType = ([string]$hitEl.Current.ControlType.ProgrammaticName) -replace '^ControlType\.', '' } catch { }
1866
+ try { $out.name = [string]$hitEl.Current.Name } catch { }
1867
+ try { $out.automationId = [string]$hitEl.Current.AutomationId } catch { }
1868
+ try {
1869
+ $b = $hitEl.Current.BoundingRectangle
1870
+ $out.rect = @{
1871
+ left = [int][Math]::Round($b.Left); top = [int][Math]::Round($b.Top)
1872
+ right = [int][Math]::Round($b.Right); bottom = [int][Math]::Round($b.Bottom)
1873
+ }
1874
+ } catch { }
1875
+ return $out
1876
+ } catch {
1877
+ return @{ ok = $false; outside = $false; atPoint = $false; name = ''; controlType = ''
1878
+ automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1879
+ reason = 'the point probe threw: ' + $_.Exception.Message }
1880
+ }
1881
+ }