dsh-windows-parallel-mcp 0.4.1 → 0.6.0

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.
@@ -63,7 +63,6 @@ public static class WpmWin
63
63
  [DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint tid, ref GUITHREADINFO gti);
64
64
 
65
65
  [DllImport("user32.dll")] public static extern IntPtr SendMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
66
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageStrW(IntPtr h, uint m, IntPtr w, string l);
67
66
  [DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
68
67
 
69
68
  [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
@@ -343,9 +342,203 @@ public static class WpmWin
343
342
  for (int i = 0; i < text.Length; i++) SendMessageW(child, 0x0102, (IntPtr)text[i], IntPtr.Zero);
344
343
  return "char|" + text.Length;
345
344
  }
346
- SendMessageStrW(child, 0x000C, IntPtr.Zero, text);
345
+ SendMessageString(child, 0x000C, IntPtr.Zero, text);
347
346
  return "settext|" + text.Length;
348
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); }
349
542
  }
350
543
  '@
351
544
  }
@@ -405,6 +598,14 @@ public static class WpmCtl {
405
598
  $script:WpmDpiAware = [WpmWin]::EnsureDpiAware()
406
599
 
407
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
408
609
  function Get-WpmUiaCached {
409
610
  # Each pattern type is resolved independently and a missing one is simply absent from the table.
410
611
  # The first version built the table in one literal, and on this runtime
@@ -697,7 +898,20 @@ function Get-WpmFacts {
697
898
  # They get different refusal codes (decide.ps1), so this measurement runs only when the probe
698
899
  # actually ran -- never to decorate a target whose message door already decided the route.
699
900
  $uiaTreeEmpty = $false
700
- if (-not $hasPattern -and ($pointResolved -or $scanProbed)) {
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)) {
701
915
  $uiaTreeEmpty = -not (Test-WpmUiaTreeHasContent $Hwnd)
702
916
  }
703
917
 
@@ -802,3 +1016,600 @@ function Restore-WpmFocus {
802
1016
  }
803
1017
  return $res
804
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.5.0 READ PATHS: a frame the model can read, a picture whose coordinates are DATA, and a preview
1058
+ # that answers in text. None of the three writes an input-queue entry or takes the focus.
1059
+ # ==================================================================================================
1060
+
1061
+ function Get-WpmDataDir {
1062
+ # The same base the takeover latch uses (takeover.ps1 Get-WpmTakeoverLatchPath) and the host half
1063
+ # (lib/index.js abortLatchPath). One directory to open when something has to be inspected by hand.
1064
+ $base = $env:LOCALAPPDATA
1065
+ if (-not $base) { $base = [System.IO.Path]::GetTempPath() }
1066
+ return (Join-Path $base 'wpm')
1067
+ }
1068
+
1069
+ function Get-WpmShotsDir {
1070
+ $d = Join-Path (Get-WpmDataDir) 'shots'
1071
+ if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
1072
+ return $d
1073
+ }
1074
+
1075
+ function Get-WpmFrameRect {
1076
+ <#
1077
+ ONE frame rule, and the caller cannot silently get the wrong one.
1078
+ Returns @{ ok; frame='dwm'|'win32'|'none'; hr; left; top; right; bottom }.
1079
+ DWM(9 EXTENDED_FRAME_BOUNDS) is the ONLY source that agrees with the UIA children's coordinate
1080
+ space; GetWindowRect is the documented fallback for RDP/Basic-theme hosts where the DWM call
1081
+ returns a non-zero hr. Which one was used is a RETURNED FIELD, never a silent substitution.
1082
+ #>
1083
+ param([IntPtr]$Hwnd)
1084
+ $d = [WpmWin]::DwmFrame($Hwnd)
1085
+ if ($d[0] -eq 0 -and $d[3] -gt $d[1] -and $d[4] -gt $d[2]) {
1086
+ return @{ ok = $true; frame = 'dwm'; hr = 0
1087
+ left = [int]$d[1]; top = [int]$d[2]; right = [int]$d[3]; bottom = [int]$d[4] }
1088
+ }
1089
+ $w = [WpmWin]::WinRect($Hwnd)
1090
+ if ($w[0] -eq 1 -and $w[3] -gt $w[1] -and $w[4] -gt $w[2]) {
1091
+ return @{ ok = $true; frame = 'win32'; hr = [int]$d[0]
1092
+ left = [int]$w[1]; top = [int]$w[2]; right = [int]$w[3]; bottom = [int]$w[4] }
1093
+ }
1094
+ return @{ ok = $false; frame = 'none'; hr = [int]$d[0]; left = 0; top = 0; right = 0; bottom = 0 }
1095
+ }
1096
+
1097
+ function Test-WpmFrameInsideRoot {
1098
+ <#
1099
+ The DECIDABLE frame check. "Every element rect is inside screenRect" was measured to be FALSE on
1100
+ real windows -- Chromium/Electron trees report virtualized content far outside the viewport
1101
+ (overhangs of 3px, 18px, 287px and 2720px measured here on 2026-11-23), so that rule refuses
1102
+ ordinary windows. What holds is narrower and still worth asserting: the frame we CAPTURED must lie
1103
+ inside the window's own rect as the accessibility tree reports it (the ROOT element's
1104
+ BoundingRectangle, which measures equal to GetWindowRect -- the shadow space). Measured insets on 8
1105
+ real windows: exactly 0,0,0,0 (borderless) or 8,8,8,8 (shadowed). A frame that pokes OUTSIDE the
1106
+ root means the frame came from somewhere else, and refusing there is what keeps a wrong frame from
1107
+ ever becoming a label.
1108
+ #>
1109
+ param([hashtable]$Frame, [hashtable]$RootRect, [int]$Tolerance = 2)
1110
+ $insetL = [int]$Frame.left - [int]$RootRect.left
1111
+ $insetT = [int]$Frame.top - [int]$RootRect.top
1112
+ $insetR = [int]$RootRect.right - [int]$Frame.right
1113
+ $insetB = [int]$RootRect.bottom - [int]$Frame.bottom
1114
+ $ok = ($insetL -ge -$Tolerance) -and ($insetT -ge -$Tolerance) -and
1115
+ ($insetR -ge -$Tolerance) -and ($insetB -ge -$Tolerance)
1116
+ return @{ ok = $ok; insetLeft = $insetL; insetTop = $insetT; insetRight = $insetR; insetBottom = $insetB }
1117
+ }
1118
+
1119
+ function Get-WpmSnapshotTree {
1120
+ <#
1121
+ Walk the tree ONCE (FindAll(Descendants) + IsOffscreen), number what is visible, and hand back a
1122
+ frame the model can answer with. Measured: 816 descendants / 71 visible / 291ms on an Electron
1123
+ window, so TreeWalker (one cross-process COM round trip per node) is the wrong tool here and the
1124
+ 300-element cap is deliberately loose.
1125
+
1126
+ '0 element(s)' is a REAL answer on this desktop (Clash, Everything measured 0) and is reported as
1127
+ such; it deliberately does NOT reuse uia_tree_empty, whose meaning is "UI Automation is switched
1128
+ off in the application" and whose next step is relaunching the app.
1129
+
1130
+ `interactableOnly` (default on) is the zero-cost first pass at a huge tree. `sinceSnapId` returns
1131
+ added/removed/changed instead of re-describing an unchanged table -- the measured cost of a
1132
+ multi-step flow is repeating the parts that did not move.
1133
+ #>
1134
+ param(
1135
+ [IntPtr]$Hwnd,
1136
+ [int]$MaxElements = 300,
1137
+ [bool]$InteractableOnly = $true,
1138
+ [string]$Intent = '',
1139
+ [string]$SinceSnapId = ''
1140
+ )
1141
+ $cap = [Math]::Max(1, [Math]::Min(5000, $MaxElements))
1142
+
1143
+ # The diff base is resolved BEFORE the walk: an unknown sinceSnapId is a stale reference, not an
1144
+ # empty diff. Returning "no changes" for an id we never issued would be the most comfortable lie here.
1145
+ $base = $null
1146
+ if ($SinceSnapId) {
1147
+ foreach ($s in @($script:WpmSnapshots)) {
1148
+ if ($s -and $s.snapId -eq $SinceSnapId) { $base = $s; break }
1149
+ }
1150
+ if (-not $base) {
1151
+ return @{ ok = $false; stale = $true
1152
+ 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" }
1153
+ }
1154
+ }
1155
+
1156
+ $frame = Get-WpmFrameRect $Hwnd
1157
+ if (-not $frame.ok) {
1158
+ return @{ ok = $false; stale = $false; frameCheck = 'unknown'
1159
+ reason = "no usable window frame: DwmGetWindowAttribute hr=$($frame.hr) and GetWindowRect both failed, so there is no rectangle to measure elements against" }
1160
+ }
1161
+
1162
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1163
+
1164
+ # ---- THE DECIDABLE SELF-CHECK ------------------------------------------------------------------
1165
+ # The obvious invariant -- "every element rect is contained in screenRect" -- was MEASURED to be
1166
+ # false on real windows and is therefore NOT used: Chromium/Electron trees legitimately report
1167
+ # virtualized content far outside the viewport (overhangs measured 3px, 18px, 287px and 2720px on
1168
+ # this desktop, 2026-11-23), and a rule that refuses those snapshots refuses whole classes of
1169
+ # ordinary windows. What IS decidable and cheap is the relationship the two coordinate sources
1170
+ # state about the window itself: the ROOT element's rect (the tree's own claim, which measures equal
1171
+ # to GetWindowRect -- shadow space) must CONTAIN the frame we captured. Measured on 8 real windows:
1172
+ # it holds with insets of exactly 0px (borderless) or 8px/8px/8px/8px (shadowed), and a frame that
1173
+ # pokes outside the root means the frame came from somewhere else. The inset is REPORTED as data so
1174
+ # the shadow is visible instead of merely survived.
1175
+ $frameCheck = 'unknown'
1176
+ $insetL = 0; $insetT = 0; $insetR = 0; $insetB = 0
1177
+ try {
1178
+ $rb = $root.Current.BoundingRectangle
1179
+ $rootRect = @{
1180
+ left = [int][Math]::Round($rb.Left); top = [int][Math]::Round($rb.Top)
1181
+ right = [int][Math]::Round($rb.Right); bottom = [int][Math]::Round($rb.Bottom)
1182
+ }
1183
+ $inside = Test-WpmFrameInsideRoot -Frame $frame -RootRect $rootRect
1184
+ $insetL = [int]$inside.insetLeft; $insetT = [int]$inside.insetTop
1185
+ $insetR = [int]$inside.insetRight; $insetB = [int]$inside.insetBottom
1186
+ $frameCheck = if ($inside.ok) { 'pass' } else { 'fail' }
1187
+ if ($frameCheck -eq 'fail') {
1188
+ return @{ ok = $false; stale = $false; frame = $frame.frame; frameCheck = 'fail'
1189
+ 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" }
1190
+ }
1191
+ } catch {
1192
+ # An unreadable root rect cannot certify anything, and it must not be turned into a failure: the
1193
+ # snapshot itself may still be useful, so the check reports 'unknown' rather than 'pass'.
1194
+ $frameCheck = 'unknown'
1195
+ }
1196
+
1197
+ $all = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,
1198
+ [System.Windows.Automation.Condition]::TrueCondition)
1199
+ $total = $all.Count
1200
+ $pats = Get-WpmUiaCached
1201
+ $order = @('invoke', 'value', 'toggle', 'select', 'legacy')
1202
+ $rows = @()
1203
+ $truncated = $false
1204
+ $outsideFrame = 0
1205
+
1206
+ for ($i = 0; $i -lt $total; $i++) {
1207
+ $el = $all[$i]
1208
+ $off = $false
1209
+ try { $off = [bool]$el.Current.IsOffscreen } catch { continue }
1210
+ if ($off) { continue }
1211
+
1212
+ $ct = ''; $nm = ''; $aid = ''
1213
+ try { $ct = ([string]$el.Current.ControlType.ProgrammaticName) -replace '^ControlType\.', '' } catch { continue }
1214
+ try { $nm = [string]$el.Current.Name } catch { }
1215
+ try { $aid = [string]$el.Current.AutomationId } catch { }
1216
+
1217
+ # Sub-element rects are in the DWM/real space (measured); the ROOT element is the one that reports
1218
+ # the shadow-inclusive rect, and FindAll(Descendants) never returns the root -- so nothing here
1219
+ # mixes the two spaces.
1220
+ $rc = @{ left = 0; top = 0; right = 0; bottom = 0 }
1221
+ try {
1222
+ $b = $el.Current.BoundingRectangle
1223
+ $rc = @{
1224
+ left = [int][Math]::Round($b.Left); top = [int][Math]::Round($b.Top)
1225
+ right = [int][Math]::Round($b.Right); bottom = [int][Math]::Round($b.Bottom)
1226
+ }
1227
+ } catch { }
1228
+
1229
+ # A label exists to be POINTED AT inside the capture. An element with no overlap with the frame
1230
+ # cannot be clicked within it (the point-ownership assertion would refuse), so handing out a
1231
+ # number for it would hand out a trap. It is excluded and COUNTED, never silently dropped.
1232
+ $overlaps = ($rc.right -gt $frame.left) -and ($rc.left -lt $frame.right) -and
1233
+ ($rc.bottom -gt $frame.top) -and ($rc.top -lt $frame.bottom)
1234
+ if (-not $overlaps) { $outsideFrame++; continue }
1235
+
1236
+ $kinds = @()
1237
+ foreach ($k in $order) {
1238
+ if (-not $pats.ContainsKey($k)) { continue }
1239
+ $obj = $null
1240
+ try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
1241
+ if ($obj) { $kinds += $k }
1242
+ }
1243
+ if ($InteractableOnly -and $kinds.Count -eq 0) { continue }
1244
+
1245
+ if ($rows.Count -ge $cap) { $truncated = $true; break }
1246
+
1247
+ $rid = ''
1248
+ try { $rid = (@($el.GetRuntimeId()) -join '.') } catch { $rid = '' }
1249
+
1250
+ $rows += @{
1251
+ label = ($rows.Count + 1)
1252
+ controlType = $ct
1253
+ name = $nm
1254
+ automationId = $aid
1255
+ runtimeId = $rid
1256
+ rect = $rc
1257
+ patterns = @($kinds)
1258
+ }
1259
+ }
1260
+
1261
+ # ---- the delta, by UIA RuntimeId (measured stable across queries, 71/71) --------------------
1262
+ $delta = $null
1263
+ if ($base) {
1264
+ $oldByRid = @{}
1265
+ foreach ($r in @($base.elements)) { if ($r.runtimeId) { $oldByRid[$r.runtimeId] = $r } }
1266
+ $newByRid = @{}
1267
+ foreach ($r in $rows) { if ($r.runtimeId) { $newByRid[$r.runtimeId] = $r } }
1268
+ $added = @(); $removed = @(); $changed = @(); $same = 0
1269
+ foreach ($r in $rows) {
1270
+ if (-not $r.runtimeId) { continue }
1271
+ if (-not $oldByRid.ContainsKey($r.runtimeId)) { $added += $r; continue }
1272
+ $o = $oldByRid[$r.runtimeId]
1273
+ $why = @()
1274
+ if ([string]$o.name -ne [string]$r.name) { $why += 'name' }
1275
+ if ([string]$o.controlType -ne [string]$r.controlType) { $why += 'controlType' }
1276
+ if ([string]$o.automationId -ne [string]$r.automationId) { $why += 'automationId' }
1277
+ if (([int]$o.rect.left -ne [int]$r.rect.left) -or ([int]$o.rect.top -ne [int]$r.rect.top) -or
1278
+ ([int]$o.rect.right -ne [int]$r.rect.right) -or ([int]$o.rect.bottom -ne [int]$r.rect.bottom)) { $why += 'rect' }
1279
+ if ((@($o.patterns) -join ',') -ne (@($r.patterns) -join ',')) { $why += 'patterns' }
1280
+ if ($why.Count -gt 0) {
1281
+ $changed += @{ label = $r.label; controlType = $r.controlType; name = $r.name
1282
+ automationId = $r.automationId; rect = $r.rect; patterns = @($r.patterns); changed = $why }
1283
+ } else { $same++ }
1284
+ }
1285
+ foreach ($o in @($base.elements)) {
1286
+ if (-not $o.runtimeId) { continue }
1287
+ if (-not $newByRid.ContainsKey($o.runtimeId)) {
1288
+ $removed += @{ label = $o.label; controlType = $o.controlType; name = $o.name
1289
+ automationId = $o.automationId; rect = $o.rect; patterns = @($o.patterns) }
1290
+ }
1291
+ }
1292
+ $delta = @{ sinceSnapId = $base.snapId; added = @($added); removed = @($removed)
1293
+ changed = @($changed); unchanged = $same }
1294
+ }
1295
+
1296
+ $script:WpmSnapSeq = $script:WpmSnapSeq + 1
1297
+ $snapId = 'snap-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + '-' + $script:WpmSnapSeq
1298
+ $entry = @{
1299
+ snapId = $snapId
1300
+ hwnd = $Hwnd.ToInt64().ToString()
1301
+ frame = $frame.frame
1302
+ frameCheck = $frameCheck
1303
+ frameInset = @{ left = $insetL; top = $insetT; right = $insetR; bottom = $insetB }
1304
+ intent = $Intent
1305
+ createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1306
+ total = $total
1307
+ count = $rows.Count
1308
+ outsideFrame = $outsideFrame
1309
+ truncated = $truncated
1310
+ elements = @($rows)
1311
+ }
1312
+ # Newest first. Capacity 2, for one reason each: [0] resolves LABEL references, [1] is the only
1313
+ # valid sinceSnapId. Dropping the older one is what makes a superseded snapId a reportable
1314
+ # stale_ref instead of a silent success against a frame the caller can no longer see.
1315
+ $prev = @($script:WpmSnapshots)
1316
+ $script:WpmSnapshots = @($entry) + @($prev | Select-Object -First 1)
1317
+
1318
+ # The intent travels WITH the frame as a file too, so a deciding subagent (or a human reading the
1319
+ # directory afterwards) gets "what this frame was for" without the conversation around it. One file,
1320
+ # overwritten each snapshot: bounded by construction.
1321
+ try {
1322
+ $dataDir = Get-WpmDataDir
1323
+ if (-not (Test-Path -LiteralPath $dataDir)) { New-Item -ItemType Directory -Force -Path $dataDir | Out-Null }
1324
+ $payload = $entry | ConvertTo-Json -Depth 8 -Compress
1325
+ [System.IO.File]::WriteAllText((Join-Path $dataDir 'last-snapshot.json'), $payload,
1326
+ (New-Object System.Text.UTF8Encoding($false)))
1327
+ } catch { }
1328
+
1329
+ return @{ ok = $true; stale = $false; snapId = $snapId; frame = $frame.frame; frameCheck = $frameCheck
1330
+ frameInset = @{ left = $insetL; top = $insetT; right = $insetR; bottom = $insetB }
1331
+ intent = $Intent; total = $total; count = $rows.Count; outsideFrame = $outsideFrame
1332
+ truncated = $truncated; elements = @($rows); delta = $delta }
1333
+ }
1334
+
1335
+ function Resolve-WpmSnapshotLabel {
1336
+ <#
1337
+ Resolve a snapshot LABEL back to the ELEMENT (by UIA RuntimeId), so a labelled action keeps the
1338
+ silent UIA-pattern path and never degrades into a coordinate click. Every failure to resolve is a
1339
+ stale reference, not a guess: the frame the caller read is gone.
1340
+ #>
1341
+ param([IntPtr]$Hwnd, [int]$Label, [string]$SnapId)
1342
+ $snap = $null
1343
+ $all = @($script:WpmSnapshots)
1344
+ if ($all.Count -gt 0) { $snap = $all[0] }
1345
+ if (-not $snap) {
1346
+ return @{ ok = $false; stale = $true; reason = 'no snapshot has been taken by this worker; take one and act on its labels' }
1347
+ }
1348
+ if ($SnapId -and $SnapId -ne $snap.snapId) {
1349
+ return @{ ok = $false; stale = $true
1350
+ reason = "snapId '$SnapId' was superseded by '$($snap.snapId)'; a label only means something inside the frame that printed it, so take a new snapshot" }
1351
+ }
1352
+ if ([string]$snap.hwnd -ne $Hwnd.ToInt64().ToString()) {
1353
+ return @{ ok = $false; stale = $true
1354
+ reason = "the newest snapshot is of hwnd=$($snap.hwnd), not this target; take a snapshot of this window" }
1355
+ }
1356
+ $row = $null
1357
+ foreach ($r in @($snap.elements)) { if ([int]$r.label -eq $Label) { $row = $r; break } }
1358
+ if (-not $row) {
1359
+ return @{ ok = $false; stale = $true
1360
+ reason = "label $Label is not in snapshot $($snap.snapId) (it printed $($snap.count) element(s))" }
1361
+ }
1362
+ if (-not $row.runtimeId) {
1363
+ return @{ ok = $false; stale = $true
1364
+ reason = "label $Label carried no stable runtime id, so it cannot be re-found; take a new snapshot" }
1365
+ }
1366
+ $el = $null
1367
+ try {
1368
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1369
+ $found = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,
1370
+ [System.Windows.Automation.Condition]::TrueCondition)
1371
+ for ($i = 0; $i -lt $found.Count; $i++) {
1372
+ $cand = $found[$i]
1373
+ $rid = ''
1374
+ try { $rid = (@($cand.GetRuntimeId()) -join '.') } catch { continue }
1375
+ if ($rid -eq $row.runtimeId) { $el = $cand; break }
1376
+ }
1377
+ } catch {
1378
+ return @{ ok = $false; stale = $true; reason = 'the tree could not be re-walked: ' + $_.Exception.Message }
1379
+ }
1380
+ if (-not $el) {
1381
+ return @{ ok = $false; stale = $true
1382
+ reason = "the element behind label $Label is no longer in the tree; take a new snapshot" }
1383
+ }
1384
+ $pats = Get-WpmUiaCached
1385
+ $kind = 'none'
1386
+ foreach ($k in @('invoke', 'value', 'toggle', 'select', 'legacy')) {
1387
+ if (-not $pats.ContainsKey($k)) { continue }
1388
+ $obj = $null
1389
+ try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
1390
+ if ($obj) { $kind = $k; break }
1391
+ }
1392
+ if ($kind -eq 'none') {
1393
+ return @{ ok = $false; stale = $true
1394
+ reason = "the element behind label $Label no longer exposes a usable UIA pattern; take a new snapshot" }
1395
+ }
1396
+ return @{ ok = $true; stale = $false; element = $el; patternKind = $kind; row = $row; snapId = $snap.snapId }
1397
+ }
1398
+
1399
+ function Get-WpmScreenshot {
1400
+ <#
1401
+ CopyFromScreen over the DWM frame (or the virtual screen on explicit request) and return the
1402
+ MAPPING as data. Why the picture is not returned inline: a plugin cannot mint an inline image
1403
+ block without the host's attachment service (measured: ImageBlock needs an ImageAttachmentRef from
1404
+ an app.asar-only package), so the file is written and the caller reads it. What this action is
1405
+ really for is the second half: `scale`/`identity`/`screenRect` let a caller hand IMAGE coordinates
1406
+ back to click space:'image' and never multiply anything itself.
1407
+
1408
+ scale = imagePixels / screenPixels. identity is true only when scale==1.0. Nothing is resampled
1409
+ unless maxWidth asked for it, because a resized image IS a different coordinate system.
1410
+ #>
1411
+ param([IntPtr]$Hwnd, [bool]$FullScreen = $false, [int]$MaxWidth = 0, [int]$Keep = 10)
1412
+ Add-Type -AssemblyName System.Drawing
1413
+
1414
+ if ($FullScreen) {
1415
+ $vs = [WpmWin]::VirtualScreen()
1416
+ $frame = @{ ok = $true; frame = 'dwm'; hr = 0
1417
+ left = [int]$vs[0]; top = [int]$vs[1]; right = ([int]$vs[0] + [int]$vs[2]); bottom = ([int]$vs[1] + [int]$vs[3]) }
1418
+ } else {
1419
+ $frame = Get-WpmFrameRect $Hwnd
1420
+ if (-not $frame.ok) {
1421
+ return @{ ok = $false
1422
+ reason = "no usable window frame: DwmGetWindowAttribute hr=$($frame.hr) and GetWindowRect both failed" }
1423
+ }
1424
+ }
1425
+
1426
+ $w = $frame.right - $frame.left
1427
+ $h = $frame.bottom - $frame.top
1428
+ if ($w -le 0 -or $h -le 0) { return @{ ok = $false; reason = "the captured rectangle is empty ($($w)x$($h))" } }
1429
+
1430
+ $bmp = $null
1431
+ $resized = $null
1432
+ $hbmp = [IntPtr]::Zero
1433
+ # THE PATH IS REPORTED, NEVER SWAPPED SILENTLY. Same discipline as `frame`: 'dwm' versus 'win32' is a
1434
+ # coordinate fact, and 'bitblt' versus 'gdiplus' is a content fact (a 32bppRgb surface instead of
1435
+ # 32bppArgb, and any difference in what an occluded window paints). A caller comparing two screenshots
1436
+ # has to be able to see that the producer changed, so the field is mandatory in the result.
1437
+ $captureBackend = 'gdiplus'
1438
+ $captureNote = ''
1439
+ try {
1440
+ $capReason = ''
1441
+ try { $hbmp = [WpmWin]::CaptureBitBlt($frame.left, $frame.top, $w, $h, [ref]$capReason) }
1442
+ catch { $hbmp = [IntPtr]::Zero; $capReason = $_.Exception.Message }
1443
+ if ($hbmp -ne [IntPtr]::Zero) {
1444
+ try {
1445
+ $bmp = [System.Drawing.Image]::FromHbitmap($hbmp)
1446
+ $captureBackend = 'bitblt'
1447
+ } catch {
1448
+ # FromHbitmap can refuse (a format it cannot map). That is a capture failure, not a crash, and
1449
+ # the fallback below is the documented answer -- an exception here would turn a fast path into a
1450
+ # lost screenshot.
1451
+ $bmp = $null
1452
+ $capReason = 'FromHbitmap: ' + $_.Exception.Message
1453
+ } finally {
1454
+ [void][WpmWin]::FreeHbitmap($hbmp)
1455
+ $hbmp = [IntPtr]::Zero
1456
+ }
1457
+ }
1458
+ if (-not $bmp) {
1459
+ $captureNote = "bitblt-unavailable($capReason)"
1460
+ $bmp = New-Object System.Drawing.Bitmap($w, $h)
1461
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
1462
+ try { $g.CopyFromScreen($frame.left, $frame.top, 0, 0, (New-Object System.Drawing.Size($w, $h))) }
1463
+ finally { $g.Dispose() }
1464
+ $captureBackend = 'gdiplus'
1465
+ }
1466
+
1467
+ $scale = 1.0
1468
+ $imgW = $w
1469
+ $imgH = $h
1470
+ $out = $bmp
1471
+ $cap = [Math]::Max(0, [Math]::Min(7680, $MaxWidth))
1472
+ if ($cap -gt 0 -and $w -gt $cap) {
1473
+ $imgW = $cap
1474
+ $imgH = [int][Math]::Max(1, [Math]::Round($h * ($cap / [double]$w)))
1475
+ $resized = New-Object System.Drawing.Bitmap($imgW, $imgH)
1476
+ $g2 = [System.Drawing.Graphics]::FromImage($resized)
1477
+ try {
1478
+ $g2.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
1479
+ $g2.DrawImage($bmp, 0, 0, $imgW, $imgH)
1480
+ } finally { $g2.Dispose() }
1481
+ $out = $resized
1482
+ $scale = [Math]::Round($imgW / [double]$w, 6)
1483
+ }
1484
+
1485
+ $dir = Get-WpmShotsDir
1486
+ $script:WpmShotSeq = $script:WpmShotSeq + 1
1487
+ $shotId = 'shot-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + '-' + $script:WpmShotSeq
1488
+ $file = Join-Path $dir ($shotId + '.png')
1489
+ $out.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
1490
+ $bytes = (Get-Item -LiteralPath $file).Length
1491
+ $keepN = [Math]::Max(1, [Math]::Min(200, $Keep))
1492
+
1493
+ # Retention: newest `shotsKeep` survive, older PNGs in THIS directory are deleted. The registry is
1494
+ # pruned against the same list, so a shotId that was cleaned up resolves to stale_ref rather than
1495
+ # to a file that is no longer there.
1496
+ $files = @(Get-ChildItem -LiteralPath $dir -Filter '*.png' -File -ErrorAction SilentlyContinue |
1497
+ Sort-Object LastWriteTimeUtc -Descending)
1498
+ for ($i = $keepN; $i -lt $files.Count; $i++) {
1499
+ try { Remove-Item -LiteralPath $files[$i].FullName -Force } catch { }
1500
+ }
1501
+ $script:WpmShots[$shotId] = @{
1502
+ shotId = $shotId; file = $file; scale = $scale; identity = ($scale -eq 1.0)
1503
+ left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom
1504
+ imageWidth = [int]$imgW; imageHeight = [int]$imgH; frame = $frame.frame
1505
+ captureBackend = $captureBackend
1506
+ createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1507
+ }
1508
+ # Drop registry entries for shots the retention pass just removed.
1509
+ $live = @{}
1510
+ for ($i = 0; $i -lt [Math]::Min($keepN, $files.Count); $i++) { $live[$files[$i].BaseName] = $true }
1511
+ foreach ($key in @($script:WpmShots.Keys)) {
1512
+ if (-not $live.ContainsKey($key)) { $script:WpmShots.Remove($key) }
1513
+ }
1514
+
1515
+ return @{ ok = $true
1516
+ shotId = $shotId; file = $file
1517
+ screenRect = @{ left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom }
1518
+ imageSize = @{ width = [int]$imgW; height = [int]$imgH }
1519
+ scale = $scale; identity = ($scale -eq 1.0); frame = $frame.frame
1520
+ captureBackend = $captureBackend; captureNote = $captureNote
1521
+ dpiAware = [bool]$script:WpmDpiAware; bytes = [long]$bytes; shotsKeep = $keepN
1522
+ capturedAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }
1523
+ } finally {
1524
+ if ($hbmp -ne [IntPtr]::Zero) { [void][WpmWin]::FreeHbitmap($hbmp) }
1525
+ if ($resized) { $resized.Dispose() }
1526
+ if ($bmp) { $bmp.Dispose() }
1527
+ }
1528
+ }
1529
+
1530
+ function Convert-WpmImagePoint {
1531
+ <#
1532
+ THE MULTIPLICATION THE MODEL MUST NOT DO. space:'image' + shotId -> a screen point, using the
1533
+ scale the screenshot itself reported. screenX = screenRect.left + round(imageX / scale), which is
1534
+ the inverse of scale = imagePixels/screenPixels; a shot that was never issued, or one the
1535
+ retention policy already deleted, answers ok=false so the caller can report stale_ref instead of
1536
+ reinterpreting image pixels as screen pixels.
1537
+ #>
1538
+ param([string]$ShotId, [int]$X, [int]$Y)
1539
+ if (-not $ShotId) { return @{ ok = $false; stale = $true; reason = 'space="image" needs a shotId: image coordinates only exist relative to a capture' } }
1540
+ if (-not $script:WpmShots.ContainsKey($ShotId)) {
1541
+ return @{ ok = $false; stale = $true
1542
+ reason = "shotId '$ShotId' is not a screenshot this worker still holds (the retention policy keeps the newest shotsKeep); take a new screenshot" }
1543
+ }
1544
+ $shot = $script:WpmShots[$ShotId]
1545
+ $scale = [double]$shot.scale
1546
+ if ($scale -le 0) { return @{ ok = $false; stale = $true; reason = "shotId '$ShotId' has a non-positive scale ($scale)" } }
1547
+ if ($X -lt 0 -or $Y -lt 0 -or $X -ge [int]$shot.imageWidth -or $Y -ge [int]$shot.imageHeight) {
1548
+ return @{ ok = $false; stale = $false
1549
+ reason = "image point ($X,$Y) is outside the captured image ($($shot.imageWidth)x$($shot.imageHeight)); an image coordinate must address a pixel that exists" }
1550
+ }
1551
+ $sx = [int]$shot.left + [int][Math]::Round($X / $scale)
1552
+ $sy = [int]$shot.top + [int][Math]::Round($Y / $scale)
1553
+ return @{ ok = $true; stale = $false; x = $sx; y = $sy; scale = $scale; shotId = $ShotId }
1554
+ }
1555
+
1556
+ function Get-WpmPreviewAt {
1557
+ <#
1558
+ WHAT IS UNDER THAT POINT -- answered by the OS, as text. This is the confirmation step that makes
1559
+ an irreversible click reviewable without a picture: AutomationElement.FromPoint plus the
1560
+ ancestry proof the click path already uses (if the climb never meets the target root, the point
1561
+ belongs to another window and the answer is a refusal). No input queue entry, no focus change:
1562
+ the marker is drawn by the caller through overlay.ps1, which is a click-through request.
1563
+ #>
1564
+ param([IntPtr]$Hwnd, [int]$X, [int]$Y)
1565
+ $out = @{ ok = $true; outside = $false; atPoint = $false; name = ''
1566
+ controlType = ''; automationId = ''
1567
+ rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1568
+ reason = '' }
1569
+ try {
1570
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1571
+ if (-not $root) {
1572
+ return @{ ok = $false; outside = $false; atPoint = $false; name = ''; controlType = ''
1573
+ automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1574
+ reason = 'target window has no UI Automation element' }
1575
+ }
1576
+ $pt = New-Object System.Windows.Point([double]$X, [double]$Y)
1577
+ $hitEl = [System.Windows.Automation.AutomationElement]::FromPoint($pt)
1578
+ if (-not $hitEl) {
1579
+ $out.reason = 'nothing at that point is exposed to UI Automation'
1580
+ return $out
1581
+ }
1582
+ $out.atPoint = $true
1583
+
1584
+ $walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker
1585
+ $el = $hitEl
1586
+ $sawRoot = $false
1587
+ $hop = 0
1588
+ while ($el -and $hop -lt 24) {
1589
+ if ($el -eq $root) { $sawRoot = $true; break }
1590
+ try { $el = $walker.GetParent($el) } catch { $el = $null }
1591
+ $hop++
1592
+ }
1593
+ if (-not $sawRoot) {
1594
+ return @{ ok = $false; outside = $true; atPoint = $true; name = ''; controlType = ''
1595
+ automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1596
+ reason = 'the element under that point does not belong to the target window' }
1597
+ }
1598
+
1599
+ try { $out.controlType = ([string]$hitEl.Current.ControlType.ProgrammaticName) -replace '^ControlType\.', '' } catch { }
1600
+ try { $out.name = [string]$hitEl.Current.Name } catch { }
1601
+ try { $out.automationId = [string]$hitEl.Current.AutomationId } catch { }
1602
+ try {
1603
+ $b = $hitEl.Current.BoundingRectangle
1604
+ $out.rect = @{
1605
+ left = [int][Math]::Round($b.Left); top = [int][Math]::Round($b.Top)
1606
+ right = [int][Math]::Round($b.Right); bottom = [int][Math]::Round($b.Bottom)
1607
+ }
1608
+ } catch { }
1609
+ return $out
1610
+ } catch {
1611
+ return @{ ok = $false; outside = $false; atPoint = $false; name = ''; controlType = ''
1612
+ automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1613
+ reason = 'the point probe threw: ' + $_.Exception.Message }
1614
+ }
1615
+ }