dsh-windows-parallel-mcp 0.4.0 → 0.5.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.
@@ -346,6 +346,43 @@ public static class WpmWin
346
346
  SendMessageStrW(child, 0x000C, IntPtr.Zero, text);
347
347
  return "settext|" + text.Length;
348
348
  }
349
+
350
+ // ---- 0.5.0: the frame, the virtual screen, and the capture footprint ---------------------
351
+ // THE FRAME COMES FROM DWM, NOT FROM GetWindowRect. Measured on this desktop (2026-11-23):
352
+ // GetWindowRect returns -8,-8,1928,1040 while DwmGetWindowAttribute(EXTENDED_FRAME_BOUNDS)
353
+ // returns 0,0,1920,1032 -- four 8px differences that are the invisible resize shadow. The UIA
354
+ // tree MIXES the two spaces (the ROOT element reports the shadow-inclusive rect, its children the
355
+ // real one), so any arithmetic that mixes them is 8px wrong and looks right. `screenRect` is
356
+ // therefore DWM-only, and the fallback is REPORTED as frame='win32' rather than hidden: an 8px
357
+ // offset with no field to explain it is the failure mode this whole change is written against.
358
+ [DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int attr, out RECT r, int size);
359
+ [DllImport("user32.dll")] static extern int GetSystemMetrics(int i);
360
+
361
+ /// <summary>{hr, left, top, right, bottom}. hr==0 means the DWM answer is usable.</summary>
362
+ public static long[] DwmFrame(IntPtr h)
363
+ {
364
+ RECT r;
365
+ int hr = DwmGetWindowAttribute(h, 9 /* DWMWA_EXTENDED_FRAME_BOUNDS */, out r, Marshal.SizeOf(typeof(RECT)));
366
+ if (hr != 0) return new long[] { hr, 0, 0, 0, 0 };
367
+ return new long[] { 0, r.Left, r.Top, r.Right, r.Bottom };
368
+ }
369
+
370
+ /// <summary>{ok, left, top, right, bottom} from GetWindowRect -- the documented FALLBACK only.</summary>
371
+ public static long[] WinRect(IntPtr h)
372
+ {
373
+ RECT r;
374
+ if (!GetWindowRect(h, out r)) return new long[] { 0, 0, 0, 0, 0 };
375
+ return new long[] { 1, r.Left, r.Top, r.Right, r.Bottom };
376
+ }
377
+
378
+ /// <summary>{x, y, width, height} of the virtual screen (all monitors, physical pixels).</summary>
379
+ public static int[] VirtualScreen()
380
+ {
381
+ const int SM_XVIRTUALSCREEN = 76, SM_YVIRTUALSCREEN = 77;
382
+ const int SM_CXVIRTUALSCREEN = 78, SM_CYVIRTUALSCREEN = 79;
383
+ return new int[] { GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN),
384
+ GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN) };
385
+ }
349
386
  }
350
387
  '@
351
388
  }
@@ -405,6 +442,14 @@ public static class WpmCtl {
405
442
  $script:WpmDpiAware = [WpmWin]::EnsureDpiAware()
406
443
 
407
444
  $script:WpmUia = $null
445
+ # ---- 0.5.0 state. Deliberately IN-PROCESS and BOUNDED: a label is only meaningful in the frame that
446
+ # printed it, so this holds at most two snapshots (the newest for label references, the previous as a
447
+ # sinceSnapId diff base) and at most shotsKeep screenshots. A worker restart empties both, which is
448
+ # exactly what makes a stale id a real, reportable condition instead of an unbounded cache.
449
+ $script:WpmSnapshots = @()
450
+ $script:WpmShots = @{}
451
+ $script:WpmSnapSeq = 0
452
+ $script:WpmShotSeq = 0
408
453
  function Get-WpmUiaCached {
409
454
  # Each pattern type is resolved independently and a missing one is simply absent from the table.
410
455
  # The first version built the table in one literal, and on this runtime
@@ -697,7 +742,20 @@ function Get-WpmFacts {
697
742
  # They get different refusal codes (decide.ps1), so this measurement runs only when the probe
698
743
  # actually ran -- never to decorate a target whose message door already decided the route.
699
744
  $uiaTreeEmpty = $false
700
- if (-not $hasPattern -and ($pointResolved -or $scanProbed)) {
745
+ # THE DIAGNOSIS ONLY APPLIES TO A WINDOW THAT HAS NO OTHER DOOR. This condition used to be just
746
+ # "the probe ran and found no pattern", which mislabels a whole class of target: name an element on a
747
+ # WinForms window and `engine.ps1` suppresses its message door (a window message cannot address "the
748
+ # control called X"), the UIA scan then finds nothing drivable, and the engine reported
749
+ # `uia_tree_empty` -- "the application has accessibility switched off, relaunch it with
750
+ # --force-renderer-accessibility". That advice is not merely useless for WinForms, it is WRONG about
751
+ # the cause: the window demonstrably has a real door, we shut it ourselves. Measured 2026-11-23: the
752
+ # WinForms positive control walks to three Panes carrying the controls' own names and automation ids
753
+ # through the MSAA bridge (content=0, so `Test-WpmUiaTreeHasContent` says "no content"), while the
754
+ # genuine a11y-off sample (uTools) and a bare desktop shell have the same shape -- so the tree alone
755
+ # cannot separate them. The door CAN: a target we measured a door on must not be diagnosed as
756
+ # accessibilty-off, whatever its tree looks like. Doors present => the honest code is `unreachable`
757
+ # ("nothing addressable at that name"), which points at a next step that exists.
758
+ if (-not $hasPattern -and ($pointResolved -or $scanProbed) -and ($doorKinds.Count -eq 0)) {
701
759
  $uiaTreeEmpty = -not (Test-WpmUiaTreeHasContent $Hwnd)
702
760
  }
703
761
 
@@ -802,3 +860,532 @@ function Restore-WpmFocus {
802
860
  }
803
861
  return $res
804
862
  }
863
+
864
+ # ==================================================================================================
865
+ # 0.5.0 READ PATHS: a frame the model can read, a picture whose coordinates are DATA, and a preview
866
+ # that answers in text. None of the three writes an input-queue entry or takes the focus.
867
+ # ==================================================================================================
868
+
869
+ function Get-WpmDataDir {
870
+ # The same base the takeover latch uses (takeover.ps1 Get-WpmTakeoverLatchPath) and the host half
871
+ # (lib/index.js abortLatchPath). One directory to open when something has to be inspected by hand.
872
+ $base = $env:LOCALAPPDATA
873
+ if (-not $base) { $base = [System.IO.Path]::GetTempPath() }
874
+ return (Join-Path $base 'wpm')
875
+ }
876
+
877
+ function Get-WpmShotsDir {
878
+ $d = Join-Path (Get-WpmDataDir) 'shots'
879
+ if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
880
+ return $d
881
+ }
882
+
883
+ function Get-WpmFrameRect {
884
+ <#
885
+ ONE frame rule, and the caller cannot silently get the wrong one.
886
+ Returns @{ ok; frame='dwm'|'win32'|'none'; hr; left; top; right; bottom }.
887
+ DWM(9 EXTENDED_FRAME_BOUNDS) is the ONLY source that agrees with the UIA children's coordinate
888
+ space; GetWindowRect is the documented fallback for RDP/Basic-theme hosts where the DWM call
889
+ returns a non-zero hr. Which one was used is a RETURNED FIELD, never a silent substitution.
890
+ #>
891
+ param([IntPtr]$Hwnd)
892
+ $d = [WpmWin]::DwmFrame($Hwnd)
893
+ if ($d[0] -eq 0 -and $d[3] -gt $d[1] -and $d[4] -gt $d[2]) {
894
+ return @{ ok = $true; frame = 'dwm'; hr = 0
895
+ left = [int]$d[1]; top = [int]$d[2]; right = [int]$d[3]; bottom = [int]$d[4] }
896
+ }
897
+ $w = [WpmWin]::WinRect($Hwnd)
898
+ if ($w[0] -eq 1 -and $w[3] -gt $w[1] -and $w[4] -gt $w[2]) {
899
+ return @{ ok = $true; frame = 'win32'; hr = [int]$d[0]
900
+ left = [int]$w[1]; top = [int]$w[2]; right = [int]$w[3]; bottom = [int]$w[4] }
901
+ }
902
+ return @{ ok = $false; frame = 'none'; hr = [int]$d[0]; left = 0; top = 0; right = 0; bottom = 0 }
903
+ }
904
+
905
+ function Test-WpmFrameInsideRoot {
906
+ <#
907
+ The DECIDABLE frame check. "Every element rect is inside screenRect" was measured to be FALSE on
908
+ real windows -- Chromium/Electron trees report virtualized content far outside the viewport
909
+ (overhangs of 3px, 18px, 287px and 2720px measured here on 2026-11-23), so that rule refuses
910
+ ordinary windows. What holds is narrower and still worth asserting: the frame we CAPTURED must lie
911
+ inside the window's own rect as the accessibility tree reports it (the ROOT element's
912
+ BoundingRectangle, which measures equal to GetWindowRect -- the shadow space). Measured insets on 8
913
+ real windows: exactly 0,0,0,0 (borderless) or 8,8,8,8 (shadowed). A frame that pokes OUTSIDE the
914
+ root means the frame came from somewhere else, and refusing there is what keeps a wrong frame from
915
+ ever becoming a label.
916
+ #>
917
+ param([hashtable]$Frame, [hashtable]$RootRect, [int]$Tolerance = 2)
918
+ $insetL = [int]$Frame.left - [int]$RootRect.left
919
+ $insetT = [int]$Frame.top - [int]$RootRect.top
920
+ $insetR = [int]$RootRect.right - [int]$Frame.right
921
+ $insetB = [int]$RootRect.bottom - [int]$Frame.bottom
922
+ $ok = ($insetL -ge -$Tolerance) -and ($insetT -ge -$Tolerance) -and
923
+ ($insetR -ge -$Tolerance) -and ($insetB -ge -$Tolerance)
924
+ return @{ ok = $ok; insetLeft = $insetL; insetTop = $insetT; insetRight = $insetR; insetBottom = $insetB }
925
+ }
926
+
927
+ function Get-WpmSnapshotTree {
928
+ <#
929
+ Walk the tree ONCE (FindAll(Descendants) + IsOffscreen), number what is visible, and hand back a
930
+ frame the model can answer with. Measured: 816 descendants / 71 visible / 291ms on an Electron
931
+ window, so TreeWalker (one cross-process COM round trip per node) is the wrong tool here and the
932
+ 300-element cap is deliberately loose.
933
+
934
+ '0 element(s)' is a REAL answer on this desktop (Clash, Everything measured 0) and is reported as
935
+ such; it deliberately does NOT reuse uia_tree_empty, whose meaning is "UI Automation is switched
936
+ off in the application" and whose next step is relaunching the app.
937
+
938
+ `interactableOnly` (default on) is the zero-cost first pass at a huge tree. `sinceSnapId` returns
939
+ added/removed/changed instead of re-describing an unchanged table -- the measured cost of a
940
+ multi-step flow is repeating the parts that did not move.
941
+ #>
942
+ param(
943
+ [IntPtr]$Hwnd,
944
+ [int]$MaxElements = 300,
945
+ [bool]$InteractableOnly = $true,
946
+ [string]$Intent = '',
947
+ [string]$SinceSnapId = ''
948
+ )
949
+ $cap = [Math]::Max(1, [Math]::Min(5000, $MaxElements))
950
+
951
+ # The diff base is resolved BEFORE the walk: an unknown sinceSnapId is a stale reference, not an
952
+ # empty diff. Returning "no changes" for an id we never issued would be the most comfortable lie here.
953
+ $base = $null
954
+ if ($SinceSnapId) {
955
+ foreach ($s in @($script:WpmSnapshots)) {
956
+ if ($s -and $s.snapId -eq $SinceSnapId) { $base = $s; break }
957
+ }
958
+ if (-not $base) {
959
+ return @{ ok = $false; stale = $true
960
+ 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" }
961
+ }
962
+ }
963
+
964
+ $frame = Get-WpmFrameRect $Hwnd
965
+ if (-not $frame.ok) {
966
+ return @{ ok = $false; stale = $false; frameCheck = 'unknown'
967
+ reason = "no usable window frame: DwmGetWindowAttribute hr=$($frame.hr) and GetWindowRect both failed, so there is no rectangle to measure elements against" }
968
+ }
969
+
970
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
971
+
972
+ # ---- THE DECIDABLE SELF-CHECK ------------------------------------------------------------------
973
+ # The obvious invariant -- "every element rect is contained in screenRect" -- was MEASURED to be
974
+ # false on real windows and is therefore NOT used: Chromium/Electron trees legitimately report
975
+ # virtualized content far outside the viewport (overhangs measured 3px, 18px, 287px and 2720px on
976
+ # this desktop, 2026-11-23), and a rule that refuses those snapshots refuses whole classes of
977
+ # ordinary windows. What IS decidable and cheap is the relationship the two coordinate sources
978
+ # state about the window itself: the ROOT element's rect (the tree's own claim, which measures equal
979
+ # to GetWindowRect -- shadow space) must CONTAIN the frame we captured. Measured on 8 real windows:
980
+ # it holds with insets of exactly 0px (borderless) or 8px/8px/8px/8px (shadowed), and a frame that
981
+ # pokes outside the root means the frame came from somewhere else. The inset is REPORTED as data so
982
+ # the shadow is visible instead of merely survived.
983
+ $frameCheck = 'unknown'
984
+ $insetL = 0; $insetT = 0; $insetR = 0; $insetB = 0
985
+ try {
986
+ $rb = $root.Current.BoundingRectangle
987
+ $rootRect = @{
988
+ left = [int][Math]::Round($rb.Left); top = [int][Math]::Round($rb.Top)
989
+ right = [int][Math]::Round($rb.Right); bottom = [int][Math]::Round($rb.Bottom)
990
+ }
991
+ $inside = Test-WpmFrameInsideRoot -Frame $frame -RootRect $rootRect
992
+ $insetL = [int]$inside.insetLeft; $insetT = [int]$inside.insetTop
993
+ $insetR = [int]$inside.insetRight; $insetB = [int]$inside.insetBottom
994
+ $frameCheck = if ($inside.ok) { 'pass' } else { 'fail' }
995
+ if ($frameCheck -eq 'fail') {
996
+ return @{ ok = $false; stale = $false; frame = $frame.frame; frameCheck = 'fail'
997
+ 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" }
998
+ }
999
+ } catch {
1000
+ # An unreadable root rect cannot certify anything, and it must not be turned into a failure: the
1001
+ # snapshot itself may still be useful, so the check reports 'unknown' rather than 'pass'.
1002
+ $frameCheck = 'unknown'
1003
+ }
1004
+
1005
+ $all = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,
1006
+ [System.Windows.Automation.Condition]::TrueCondition)
1007
+ $total = $all.Count
1008
+ $pats = Get-WpmUiaCached
1009
+ $order = @('invoke', 'value', 'toggle', 'select', 'legacy')
1010
+ $rows = @()
1011
+ $truncated = $false
1012
+ $outsideFrame = 0
1013
+
1014
+ for ($i = 0; $i -lt $total; $i++) {
1015
+ $el = $all[$i]
1016
+ $off = $false
1017
+ try { $off = [bool]$el.Current.IsOffscreen } catch { continue }
1018
+ if ($off) { continue }
1019
+
1020
+ $ct = ''; $nm = ''; $aid = ''
1021
+ try { $ct = ([string]$el.Current.ControlType.ProgrammaticName) -replace '^ControlType\.', '' } catch { continue }
1022
+ try { $nm = [string]$el.Current.Name } catch { }
1023
+ try { $aid = [string]$el.Current.AutomationId } catch { }
1024
+
1025
+ # Sub-element rects are in the DWM/real space (measured); the ROOT element is the one that reports
1026
+ # the shadow-inclusive rect, and FindAll(Descendants) never returns the root -- so nothing here
1027
+ # mixes the two spaces.
1028
+ $rc = @{ left = 0; top = 0; right = 0; bottom = 0 }
1029
+ try {
1030
+ $b = $el.Current.BoundingRectangle
1031
+ $rc = @{
1032
+ left = [int][Math]::Round($b.Left); top = [int][Math]::Round($b.Top)
1033
+ right = [int][Math]::Round($b.Right); bottom = [int][Math]::Round($b.Bottom)
1034
+ }
1035
+ } catch { }
1036
+
1037
+ # A label exists to be POINTED AT inside the capture. An element with no overlap with the frame
1038
+ # cannot be clicked within it (the point-ownership assertion would refuse), so handing out a
1039
+ # number for it would hand out a trap. It is excluded and COUNTED, never silently dropped.
1040
+ $overlaps = ($rc.right -gt $frame.left) -and ($rc.left -lt $frame.right) -and
1041
+ ($rc.bottom -gt $frame.top) -and ($rc.top -lt $frame.bottom)
1042
+ if (-not $overlaps) { $outsideFrame++; continue }
1043
+
1044
+ $kinds = @()
1045
+ foreach ($k in $order) {
1046
+ if (-not $pats.ContainsKey($k)) { continue }
1047
+ $obj = $null
1048
+ try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
1049
+ if ($obj) { $kinds += $k }
1050
+ }
1051
+ if ($InteractableOnly -and $kinds.Count -eq 0) { continue }
1052
+
1053
+ if ($rows.Count -ge $cap) { $truncated = $true; break }
1054
+
1055
+ $rid = ''
1056
+ try { $rid = (@($el.GetRuntimeId()) -join '.') } catch { $rid = '' }
1057
+
1058
+ $rows += @{
1059
+ label = ($rows.Count + 1)
1060
+ controlType = $ct
1061
+ name = $nm
1062
+ automationId = $aid
1063
+ runtimeId = $rid
1064
+ rect = $rc
1065
+ patterns = @($kinds)
1066
+ }
1067
+ }
1068
+
1069
+ # ---- the delta, by UIA RuntimeId (measured stable across queries, 71/71) --------------------
1070
+ $delta = $null
1071
+ if ($base) {
1072
+ $oldByRid = @{}
1073
+ foreach ($r in @($base.elements)) { if ($r.runtimeId) { $oldByRid[$r.runtimeId] = $r } }
1074
+ $newByRid = @{}
1075
+ foreach ($r in $rows) { if ($r.runtimeId) { $newByRid[$r.runtimeId] = $r } }
1076
+ $added = @(); $removed = @(); $changed = @(); $same = 0
1077
+ foreach ($r in $rows) {
1078
+ if (-not $r.runtimeId) { continue }
1079
+ if (-not $oldByRid.ContainsKey($r.runtimeId)) { $added += $r; continue }
1080
+ $o = $oldByRid[$r.runtimeId]
1081
+ $why = @()
1082
+ if ([string]$o.name -ne [string]$r.name) { $why += 'name' }
1083
+ if ([string]$o.controlType -ne [string]$r.controlType) { $why += 'controlType' }
1084
+ if ([string]$o.automationId -ne [string]$r.automationId) { $why += 'automationId' }
1085
+ if (([int]$o.rect.left -ne [int]$r.rect.left) -or ([int]$o.rect.top -ne [int]$r.rect.top) -or
1086
+ ([int]$o.rect.right -ne [int]$r.rect.right) -or ([int]$o.rect.bottom -ne [int]$r.rect.bottom)) { $why += 'rect' }
1087
+ if ((@($o.patterns) -join ',') -ne (@($r.patterns) -join ',')) { $why += 'patterns' }
1088
+ if ($why.Count -gt 0) {
1089
+ $changed += @{ label = $r.label; controlType = $r.controlType; name = $r.name
1090
+ automationId = $r.automationId; rect = $r.rect; patterns = @($r.patterns); changed = $why }
1091
+ } else { $same++ }
1092
+ }
1093
+ foreach ($o in @($base.elements)) {
1094
+ if (-not $o.runtimeId) { continue }
1095
+ if (-not $newByRid.ContainsKey($o.runtimeId)) {
1096
+ $removed += @{ label = $o.label; controlType = $o.controlType; name = $o.name
1097
+ automationId = $o.automationId; rect = $o.rect; patterns = @($o.patterns) }
1098
+ }
1099
+ }
1100
+ $delta = @{ sinceSnapId = $base.snapId; added = @($added); removed = @($removed)
1101
+ changed = @($changed); unchanged = $same }
1102
+ }
1103
+
1104
+ $script:WpmSnapSeq = $script:WpmSnapSeq + 1
1105
+ $snapId = 'snap-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + '-' + $script:WpmSnapSeq
1106
+ $entry = @{
1107
+ snapId = $snapId
1108
+ hwnd = $Hwnd.ToInt64().ToString()
1109
+ frame = $frame.frame
1110
+ frameCheck = $frameCheck
1111
+ frameInset = @{ left = $insetL; top = $insetT; right = $insetR; bottom = $insetB }
1112
+ intent = $Intent
1113
+ createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1114
+ total = $total
1115
+ count = $rows.Count
1116
+ outsideFrame = $outsideFrame
1117
+ truncated = $truncated
1118
+ elements = @($rows)
1119
+ }
1120
+ # Newest first. Capacity 2, for one reason each: [0] resolves LABEL references, [1] is the only
1121
+ # valid sinceSnapId. Dropping the older one is what makes a superseded snapId a reportable
1122
+ # stale_ref instead of a silent success against a frame the caller can no longer see.
1123
+ $prev = @($script:WpmSnapshots)
1124
+ $script:WpmSnapshots = @($entry) + @($prev | Select-Object -First 1)
1125
+
1126
+ # The intent travels WITH the frame as a file too, so a deciding subagent (or a human reading the
1127
+ # directory afterwards) gets "what this frame was for" without the conversation around it. One file,
1128
+ # overwritten each snapshot: bounded by construction.
1129
+ try {
1130
+ $dataDir = Get-WpmDataDir
1131
+ if (-not (Test-Path -LiteralPath $dataDir)) { New-Item -ItemType Directory -Force -Path $dataDir | Out-Null }
1132
+ $payload = $entry | ConvertTo-Json -Depth 8 -Compress
1133
+ [System.IO.File]::WriteAllText((Join-Path $dataDir 'last-snapshot.json'), $payload,
1134
+ (New-Object System.Text.UTF8Encoding($false)))
1135
+ } catch { }
1136
+
1137
+ return @{ ok = $true; stale = $false; snapId = $snapId; frame = $frame.frame; frameCheck = $frameCheck
1138
+ frameInset = @{ left = $insetL; top = $insetT; right = $insetR; bottom = $insetB }
1139
+ intent = $Intent; total = $total; count = $rows.Count; outsideFrame = $outsideFrame
1140
+ truncated = $truncated; elements = @($rows); delta = $delta }
1141
+ }
1142
+
1143
+ function Resolve-WpmSnapshotLabel {
1144
+ <#
1145
+ Resolve a snapshot LABEL back to the ELEMENT (by UIA RuntimeId), so a labelled action keeps the
1146
+ silent UIA-pattern path and never degrades into a coordinate click. Every failure to resolve is a
1147
+ stale reference, not a guess: the frame the caller read is gone.
1148
+ #>
1149
+ param([IntPtr]$Hwnd, [int]$Label, [string]$SnapId)
1150
+ $snap = $null
1151
+ $all = @($script:WpmSnapshots)
1152
+ if ($all.Count -gt 0) { $snap = $all[0] }
1153
+ if (-not $snap) {
1154
+ return @{ ok = $false; stale = $true; reason = 'no snapshot has been taken by this worker; take one and act on its labels' }
1155
+ }
1156
+ if ($SnapId -and $SnapId -ne $snap.snapId) {
1157
+ return @{ ok = $false; stale = $true
1158
+ reason = "snapId '$SnapId' was superseded by '$($snap.snapId)'; a label only means something inside the frame that printed it, so take a new snapshot" }
1159
+ }
1160
+ if ([string]$snap.hwnd -ne $Hwnd.ToInt64().ToString()) {
1161
+ return @{ ok = $false; stale = $true
1162
+ reason = "the newest snapshot is of hwnd=$($snap.hwnd), not this target; take a snapshot of this window" }
1163
+ }
1164
+ $row = $null
1165
+ foreach ($r in @($snap.elements)) { if ([int]$r.label -eq $Label) { $row = $r; break } }
1166
+ if (-not $row) {
1167
+ return @{ ok = $false; stale = $true
1168
+ reason = "label $Label is not in snapshot $($snap.snapId) (it printed $($snap.count) element(s))" }
1169
+ }
1170
+ if (-not $row.runtimeId) {
1171
+ return @{ ok = $false; stale = $true
1172
+ reason = "label $Label carried no stable runtime id, so it cannot be re-found; take a new snapshot" }
1173
+ }
1174
+ $el = $null
1175
+ try {
1176
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1177
+ $found = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants,
1178
+ [System.Windows.Automation.Condition]::TrueCondition)
1179
+ for ($i = 0; $i -lt $found.Count; $i++) {
1180
+ $cand = $found[$i]
1181
+ $rid = ''
1182
+ try { $rid = (@($cand.GetRuntimeId()) -join '.') } catch { continue }
1183
+ if ($rid -eq $row.runtimeId) { $el = $cand; break }
1184
+ }
1185
+ } catch {
1186
+ return @{ ok = $false; stale = $true; reason = 'the tree could not be re-walked: ' + $_.Exception.Message }
1187
+ }
1188
+ if (-not $el) {
1189
+ return @{ ok = $false; stale = $true
1190
+ reason = "the element behind label $Label is no longer in the tree; take a new snapshot" }
1191
+ }
1192
+ $pats = Get-WpmUiaCached
1193
+ $kind = 'none'
1194
+ foreach ($k in @('invoke', 'value', 'toggle', 'select', 'legacy')) {
1195
+ if (-not $pats.ContainsKey($k)) { continue }
1196
+ $obj = $null
1197
+ try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
1198
+ if ($obj) { $kind = $k; break }
1199
+ }
1200
+ if ($kind -eq 'none') {
1201
+ return @{ ok = $false; stale = $true
1202
+ reason = "the element behind label $Label no longer exposes a usable UIA pattern; take a new snapshot" }
1203
+ }
1204
+ return @{ ok = $true; stale = $false; element = $el; patternKind = $kind; row = $row; snapId = $snap.snapId }
1205
+ }
1206
+
1207
+ function Get-WpmScreenshot {
1208
+ <#
1209
+ CopyFromScreen over the DWM frame (or the virtual screen on explicit request) and return the
1210
+ MAPPING as data. Why the picture is not returned inline: a plugin cannot mint an inline image
1211
+ block without the host's attachment service (measured: ImageBlock needs an ImageAttachmentRef from
1212
+ an app.asar-only package), so the file is written and the caller reads it. What this action is
1213
+ really for is the second half: `scale`/`identity`/`screenRect` let a caller hand IMAGE coordinates
1214
+ back to click space:'image' and never multiply anything itself.
1215
+
1216
+ scale = imagePixels / screenPixels. identity is true only when scale==1.0. Nothing is resampled
1217
+ unless maxWidth asked for it, because a resized image IS a different coordinate system.
1218
+ #>
1219
+ param([IntPtr]$Hwnd, [bool]$FullScreen = $false, [int]$MaxWidth = 0, [int]$Keep = 10)
1220
+ Add-Type -AssemblyName System.Drawing
1221
+
1222
+ if ($FullScreen) {
1223
+ $vs = [WpmWin]::VirtualScreen()
1224
+ $frame = @{ ok = $true; frame = 'dwm'; hr = 0
1225
+ left = [int]$vs[0]; top = [int]$vs[1]; right = ([int]$vs[0] + [int]$vs[2]); bottom = ([int]$vs[1] + [int]$vs[3]) }
1226
+ } else {
1227
+ $frame = Get-WpmFrameRect $Hwnd
1228
+ if (-not $frame.ok) {
1229
+ return @{ ok = $false
1230
+ reason = "no usable window frame: DwmGetWindowAttribute hr=$($frame.hr) and GetWindowRect both failed" }
1231
+ }
1232
+ }
1233
+
1234
+ $w = $frame.right - $frame.left
1235
+ $h = $frame.bottom - $frame.top
1236
+ if ($w -le 0 -or $h -le 0) { return @{ ok = $false; reason = "the captured rectangle is empty ($($w)x$($h))" } }
1237
+
1238
+ $bmp = $null
1239
+ $resized = $null
1240
+ try {
1241
+ $bmp = New-Object System.Drawing.Bitmap($w, $h)
1242
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
1243
+ try { $g.CopyFromScreen($frame.left, $frame.top, 0, 0, (New-Object System.Drawing.Size($w, $h))) }
1244
+ finally { $g.Dispose() }
1245
+
1246
+ $scale = 1.0
1247
+ $imgW = $w
1248
+ $imgH = $h
1249
+ $out = $bmp
1250
+ $cap = [Math]::Max(0, [Math]::Min(7680, $MaxWidth))
1251
+ if ($cap -gt 0 -and $w -gt $cap) {
1252
+ $imgW = $cap
1253
+ $imgH = [int][Math]::Max(1, [Math]::Round($h * ($cap / [double]$w)))
1254
+ $resized = New-Object System.Drawing.Bitmap($imgW, $imgH)
1255
+ $g2 = [System.Drawing.Graphics]::FromImage($resized)
1256
+ try {
1257
+ $g2.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
1258
+ $g2.DrawImage($bmp, 0, 0, $imgW, $imgH)
1259
+ } finally { $g2.Dispose() }
1260
+ $out = $resized
1261
+ $scale = [Math]::Round($imgW / [double]$w, 6)
1262
+ }
1263
+
1264
+ $dir = Get-WpmShotsDir
1265
+ $script:WpmShotSeq = $script:WpmShotSeq + 1
1266
+ $shotId = 'shot-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + '-' + $script:WpmShotSeq
1267
+ $file = Join-Path $dir ($shotId + '.png')
1268
+ $out.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
1269
+ $bytes = (Get-Item -LiteralPath $file).Length
1270
+ $keepN = [Math]::Max(1, [Math]::Min(200, $Keep))
1271
+
1272
+ # Retention: newest `shotsKeep` survive, older PNGs in THIS directory are deleted. The registry is
1273
+ # pruned against the same list, so a shotId that was cleaned up resolves to stale_ref rather than
1274
+ # to a file that is no longer there.
1275
+ $files = @(Get-ChildItem -LiteralPath $dir -Filter '*.png' -File -ErrorAction SilentlyContinue |
1276
+ Sort-Object LastWriteTimeUtc -Descending)
1277
+ for ($i = $keepN; $i -lt $files.Count; $i++) {
1278
+ try { Remove-Item -LiteralPath $files[$i].FullName -Force } catch { }
1279
+ }
1280
+ $script:WpmShots[$shotId] = @{
1281
+ shotId = $shotId; file = $file; scale = $scale; identity = ($scale -eq 1.0)
1282
+ left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom
1283
+ imageWidth = [int]$imgW; imageHeight = [int]$imgH; frame = $frame.frame
1284
+ createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1285
+ }
1286
+ # Drop registry entries for shots the retention pass just removed.
1287
+ $live = @{}
1288
+ for ($i = 0; $i -lt [Math]::Min($keepN, $files.Count); $i++) { $live[$files[$i].BaseName] = $true }
1289
+ foreach ($key in @($script:WpmShots.Keys)) {
1290
+ if (-not $live.ContainsKey($key)) { $script:WpmShots.Remove($key) }
1291
+ }
1292
+
1293
+ return @{ ok = $true
1294
+ shotId = $shotId; file = $file
1295
+ screenRect = @{ left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom }
1296
+ imageSize = @{ width = [int]$imgW; height = [int]$imgH }
1297
+ scale = $scale; identity = ($scale -eq 1.0); frame = $frame.frame
1298
+ dpiAware = [bool]$script:WpmDpiAware; bytes = [long]$bytes; shotsKeep = $keepN
1299
+ capturedAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }
1300
+ } finally {
1301
+ if ($resized) { $resized.Dispose() }
1302
+ if ($bmp) { $bmp.Dispose() }
1303
+ }
1304
+ }
1305
+
1306
+ function Convert-WpmImagePoint {
1307
+ <#
1308
+ THE MULTIPLICATION THE MODEL MUST NOT DO. space:'image' + shotId -> a screen point, using the
1309
+ scale the screenshot itself reported. screenX = screenRect.left + round(imageX / scale), which is
1310
+ the inverse of scale = imagePixels/screenPixels; a shot that was never issued, or one the
1311
+ retention policy already deleted, answers ok=false so the caller can report stale_ref instead of
1312
+ reinterpreting image pixels as screen pixels.
1313
+ #>
1314
+ param([string]$ShotId, [int]$X, [int]$Y)
1315
+ if (-not $ShotId) { return @{ ok = $false; stale = $true; reason = 'space="image" needs a shotId: image coordinates only exist relative to a capture' } }
1316
+ if (-not $script:WpmShots.ContainsKey($ShotId)) {
1317
+ return @{ ok = $false; stale = $true
1318
+ reason = "shotId '$ShotId' is not a screenshot this worker still holds (the retention policy keeps the newest shotsKeep); take a new screenshot" }
1319
+ }
1320
+ $shot = $script:WpmShots[$ShotId]
1321
+ $scale = [double]$shot.scale
1322
+ if ($scale -le 0) { return @{ ok = $false; stale = $true; reason = "shotId '$ShotId' has a non-positive scale ($scale)" } }
1323
+ if ($X -lt 0 -or $Y -lt 0 -or $X -ge [int]$shot.imageWidth -or $Y -ge [int]$shot.imageHeight) {
1324
+ return @{ ok = $false; stale = $false
1325
+ reason = "image point ($X,$Y) is outside the captured image ($($shot.imageWidth)x$($shot.imageHeight)); an image coordinate must address a pixel that exists" }
1326
+ }
1327
+ $sx = [int]$shot.left + [int][Math]::Round($X / $scale)
1328
+ $sy = [int]$shot.top + [int][Math]::Round($Y / $scale)
1329
+ return @{ ok = $true; stale = $false; x = $sx; y = $sy; scale = $scale; shotId = $ShotId }
1330
+ }
1331
+
1332
+ function Get-WpmPreviewAt {
1333
+ <#
1334
+ WHAT IS UNDER THAT POINT -- answered by the OS, as text. This is the confirmation step that makes
1335
+ an irreversible click reviewable without a picture: AutomationElement.FromPoint plus the
1336
+ ancestry proof the click path already uses (if the climb never meets the target root, the point
1337
+ belongs to another window and the answer is a refusal). No input queue entry, no focus change:
1338
+ the marker is drawn by the caller through overlay.ps1, which is a click-through request.
1339
+ #>
1340
+ param([IntPtr]$Hwnd, [int]$X, [int]$Y)
1341
+ $out = @{ ok = $true; outside = $false; atPoint = $false; name = ''
1342
+ controlType = ''; automationId = ''
1343
+ rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1344
+ reason = '' }
1345
+ try {
1346
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
1347
+ if (-not $root) {
1348
+ return @{ ok = $false; outside = $false; atPoint = $false; name = ''; controlType = ''
1349
+ automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1350
+ reason = 'target window has no UI Automation element' }
1351
+ }
1352
+ $pt = New-Object System.Windows.Point([double]$X, [double]$Y)
1353
+ $hitEl = [System.Windows.Automation.AutomationElement]::FromPoint($pt)
1354
+ if (-not $hitEl) {
1355
+ $out.reason = 'nothing at that point is exposed to UI Automation'
1356
+ return $out
1357
+ }
1358
+ $out.atPoint = $true
1359
+
1360
+ $walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker
1361
+ $el = $hitEl
1362
+ $sawRoot = $false
1363
+ $hop = 0
1364
+ while ($el -and $hop -lt 24) {
1365
+ if ($el -eq $root) { $sawRoot = $true; break }
1366
+ try { $el = $walker.GetParent($el) } catch { $el = $null }
1367
+ $hop++
1368
+ }
1369
+ if (-not $sawRoot) {
1370
+ return @{ ok = $false; outside = $true; atPoint = $true; name = ''; controlType = ''
1371
+ automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1372
+ reason = 'the element under that point does not belong to the target window' }
1373
+ }
1374
+
1375
+ try { $out.controlType = ([string]$hitEl.Current.ControlType.ProgrammaticName) -replace '^ControlType\.', '' } catch { }
1376
+ try { $out.name = [string]$hitEl.Current.Name } catch { }
1377
+ try { $out.automationId = [string]$hitEl.Current.AutomationId } catch { }
1378
+ try {
1379
+ $b = $hitEl.Current.BoundingRectangle
1380
+ $out.rect = @{
1381
+ left = [int][Math]::Round($b.Left); top = [int][Math]::Round($b.Top)
1382
+ right = [int][Math]::Round($b.Right); bottom = [int][Math]::Round($b.Bottom)
1383
+ }
1384
+ } catch { }
1385
+ return $out
1386
+ } catch {
1387
+ return @{ ok = $false; outside = $false; atPoint = $false; name = ''; controlType = ''
1388
+ automationId = ''; rect = @{ left = 0; top = 0; right = 0; bottom = 0 }
1389
+ reason = 'the point probe threw: ' + $_.Exception.Message }
1390
+ }
1391
+ }
@@ -129,6 +129,10 @@ while ($true) {
129
129
  $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action click `
130
130
  -X ([int](Get-Arg $req 'x' -1)) -Y ([int](Get-Arg $req 'y' -1)) `
131
131
  -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
132
+ -Space ([string](Get-Arg $req 'space' 'screen')) `
133
+ -ShotId ([string](Get-Arg $req 'shotId' '')) `
134
+ -Label ([int](Get-Arg $req 'label' 0)) `
135
+ -SnapId ([string](Get-Arg $req 'snapId' '')) `
132
136
  -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
133
137
  -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000)) `
134
138
  -KeyInject:([bool](([string](Get-Arg $req 'keyInput' 'none')) -eq 'inject')) `
@@ -139,6 +143,8 @@ while ($true) {
139
143
  'type' {
140
144
  $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action type `
141
145
  -Text ([string](Get-Arg $req 'text' '')) -ElementName ([string](Get-Arg $req 'elementName' '')) `
146
+ -Label ([int](Get-Arg $req 'label' 0)) `
147
+ -SnapId ([string](Get-Arg $req 'snapId' '')) `
142
148
  -Replace:([bool](Get-Arg $req 'replace' $false)) -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
143
149
  -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
144
150
  -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000)) `
@@ -149,11 +155,39 @@ while ($true) {
149
155
  }
150
156
  'focus' {
151
157
  $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action focus `
152
- -ElementName ([string](Get-Arg $req 'elementName' '')) -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
158
+ -ElementName ([string](Get-Arg $req 'elementName' '')) `
159
+ -Label ([int](Get-Arg $req 'label' 0)) `
160
+ -SnapId ([string](Get-Arg $req 'snapId' '')) `
161
+ -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
153
162
  -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
154
163
  -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000))
155
164
  Write-Response $id @{ id = $id; ok = $true; result = $r }
156
165
  }
166
+ 'snapshot' {
167
+ # Read path (0.5.0). The cap comes from the host settings (snapshotMaxElements), which sends it
168
+ # as maxElements; interactableOnly defaults ON because the whole point of the frame is to be
169
+ # small enough for a decision, not to be an exhaustive dump.
170
+ $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action snapshot `
171
+ -MaxElements ([int](Get-Arg $req 'maxElements' 300)) `
172
+ -InteractableOnly ([bool](Get-Arg $req 'interactableOnly' $true)) `
173
+ -SinceSnapId ([string](Get-Arg $req 'sinceSnapId' '')) `
174
+ -Intent ([string](Get-Arg $req 'intent' ''))
175
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
176
+ }
177
+ 'screenshot' {
178
+ $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action screenshot `
179
+ -FullScreen ([bool](Get-Arg $req 'fullScreen' $false)) `
180
+ -MaxWidth ([int](Get-Arg $req 'maxWidth' 0)) `
181
+ -ShotsKeep ([int](Get-Arg $req 'shotsKeep' 10))
182
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
183
+ }
184
+ 'preview' {
185
+ # Silent by construction: the marker is a click-through request and nothing is serialised into
186
+ # any input queue. No proof window is produced -- there is no action to prove.
187
+ $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action preview `
188
+ -X ([int](Get-Arg $req 'x' -1)) -Y ([int](Get-Arg $req 'y' -1))
189
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
190
+ }
157
191
  'hud' {
158
192
  # Product surface for tests and for the owner: start/stop the HUD on its own, so its window
159
193
  # properties can be measured without an action in flight (test/hud-test.ps1).