dsh-windows-parallel-mcp 0.1.0 → 0.1.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.
@@ -1,313 +1,363 @@
1
- # engine.ps1 -- the only place where a decision becomes a syscall.
2
- #
3
- # One entry point, Invoke-WpmAction, and it always returns a result object rather than throwing on
4
- # a refusal: 'refused' is a normal outcome of this product, not an error path, and R3.2 requires
5
- # the reason to survive to the caller. Every result carries which channel ran, which tier it cost,
6
- # whether the owner's focus was taken and given back, and how long the whole thing took.
7
- #
8
- # ORDER OF OPERATIONS IS THE SAFETY DESIGN:
9
- # 1. measure the target's doors (facts; a target with no facts is refused)
10
- # 2. decide (pure table; pause/elevation/integrity first)
11
- # 3. if the tier costs a flash: capture the focus table BEFORE touching anything
12
- # 4. act through the cheapest available door
13
- # 5. if a flash was taken: restore, once, through the restore table
14
- # Nothing in step 4 can run for a target whose step 2 said refuse, and nothing in step 5 can pull
15
- # the focus from a window the owner chose.
16
-
17
- Set-StrictMode -Version 2.0
18
- $script:WpmEngineRoot = $PSScriptRoot
19
- . (Join-Path $PSScriptRoot 'decide.ps1')
20
- . (Join-Path $PSScriptRoot 'win.ps1')
21
-
22
- # THE PAUSE FLAG LIVES IN [WpmCtl], a static holder -- not in a script variable. The global hotkey
23
- # (Ctrl+Alt+Q, overlay.ps1) flips it from the overlay thread while actions read it on the main
24
- # thread; two copies across threads is the bug pattern this repo keeps meeting, and a script-scope
25
- # variable is exactly that second copy. $script:WpmPauseReason stays here because it is only ever
26
- # set through Set-WpmPaused, which runs on the main thread.
27
- $script:WpmPauseReason = ''
28
-
29
- function Set-WpmPaused([bool]$On, [string]$Reason = 'owner') {
30
- [WpmCtl]::Paused = $On
31
- $script:WpmPauseReason = if ($On) { $Reason } else { '' }
32
- }
33
-
34
- function Get-WpmStatus {
35
- $entry = Get-WpmFocusEntry
36
- return @{
37
- paused = [bool][WpmCtl]::Paused
38
- pauseReason = $script:WpmPauseReason
39
- foreground = $entry.fgHwnd
40
- foregroundPid = $entry.fgPid
41
- focusControl = $entry.focusHwnd
42
- lastInputAgeMs = $entry.lastInputAgeMs
43
- # The control board travels with status: whether the owner's overlay/hotkey surface is up, and
44
- # whether the hotkey actually registered. A silent 'overlay off' would make the README's
45
- # Ctrl+Alt+Q promise untrue with no way to notice.
46
- overlayRunning = [bool][WpmCtl]::OverlayOn
47
- hotkeyRegistered = [bool][WpmCtl]::HotkeyOk
48
- hotkeyLabel = [string][WpmCtl]::HotkeyLabel
49
- overlayReason = [string][WpmCtl]::Reason
50
- dpiAware = [bool]$script:WpmDpiAware
51
- stance = 'no physical injection; no forged-Alt foreground trick'
52
- }
53
- }
54
-
55
- function Get-WpmWindowList {
56
- # Read-only enumeration for the model to choose a target by hwnd. Only visible, titled, non-cloaked
57
- # windows are listed: a list padded with invisible helper windows makes target selection guesswork.
58
- $acc = @()
59
- $cb = [WpmWin+EnumProc] {
60
- param([IntPtr]$h, [IntPtr]$l)
61
- if (-not [WpmWin]::IsWindowVisible($h)) { return $true }
62
- $t = [WpmWin]::Txt($h)
63
- if (-not $t) { return $true }
64
- if ([WpmWin]::IsIconic($h)) { return $true }
65
- $r = New-Object 'WpmWin+RECT'
66
- [void][WpmWin]::GetWindowRect($h, [ref]$r)
67
- $script:WpmEnumAcc += [pscustomobject]@{
68
- hwnd = $h.ToInt64().ToString()
69
- title = $t
70
- cls = [WpmWin]::Cls($h)
71
- pid = [WpmWin]::PidOf($h)
72
- rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)"
73
- }
74
- return $true
75
- }
76
- $script:WpmEnumAcc = @()
77
- [void][WpmWin]::EnumWindows($cb, [IntPtr]::Zero)
78
- $out = $script:WpmEnumAcc
79
- $script:WpmEnumAcc = $null
80
- return $out
81
- }
82
-
83
- function Resolve-WpmChildAtPoint([IntPtr]$Hwnd, [int]$X, [int]$Y) {
84
- # Which child HWND actually sits under a screen point. Uses ChildWindowFromPointEx (the same
85
- # approach the competitor uses) instead of trusting a fixed child index: index order is not a
86
- # contract, and clicking the wrong child is indistinguishable from clicking the right one until
87
- # the app does something else.
88
- $p = New-Object 'WpmWin+POINT'
89
- $p.X = $X; $p.Y = $Y
90
- $hit = [WpmWin]::WindowFromPoint($p)
91
- if ($hit -eq [IntPtr]::Zero) { return [IntPtr]::Zero }
92
- $root = [WpmWin]::Root($hit)
93
- if ($root -ne $Hwnd) {
94
- # The point belongs to some other top-level window; acting there would be acting on a window
95
- # the caller did not name.
96
- return [IntPtr]::Zero
97
- }
98
- return $hit
99
- }
100
-
101
- function Invoke-WpmAction {
102
- param(
103
- [Parameter(Mandatory)][string]$Hwnd,
104
- [Parameter(Mandatory)][ValidateSet('click', 'type', 'focus', 'status')][string]$Action,
105
- [int]$X = -1,
106
- [int]$Y = -1,
107
- [string]$Text = '',
108
- [string]$ElementName = '',
109
- [switch]$Replace,
110
- [int]$SettleMs = 350
111
- )
112
- $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
113
- $h = [IntPtr][int64]$Hwnd
114
- $result = @{
115
- ok = $false; action = $Action; hwnd = $Hwnd; channel = ''; tier = ''
116
- refusal = ''; reason = ''; detail = ''; latencyMs = 0
117
- focusTaken = 'false'; restoreOutcome = ''; restoreSetFg = ''; restoreJoined = ''
118
- effect = 'unverified'
119
- }
120
-
121
- # A QUERY IS NOT AN ACTION, and this branch is early on purpose. It used to sit inside the action
122
- # chain, where 'status' fell through to the UIA branch and INVOKED the pattern it found -- a call
123
- # whose entire purpose is to report state would click a control. It is also placed before the
124
- # target check because a query has no target: 'what holds the focus' is answerable whatever the
125
- # caller passed, and refusing it for an unreachable window would be a query lying about why it
126
- # is empty. (Found by reading the branch order while writing the refusal cases, not by a failing
127
- # run -- the assertion in test/refusals-test.ps1 pins the fixed behaviour, it did not catch it.)
128
- if ($Action -eq 'status') {
129
- $st = Get-WpmStatus
130
- $result.ok = $true
131
- $result.channel = 'none'; $result.tier = 'none'
132
- $result.detail = 'status: query only, no action taken'
133
- $result.foreground = $st.foreground
134
- $result.foregroundPid = $st.foregroundPid
135
- $result.focusControl = $st.focusControl
136
- $result.lastInputAgeMs = $st.lastInputAgeMs
137
- $result.paused = $st.paused
138
- $result.stance = $st.stance
139
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
140
- return $result
141
- }
142
-
143
- if (-not [WpmWin]::IsWindow($h)) {
144
- $result.refusal = 'no_hwnd'; $result.reason = 'the hwnd does not identify a live window'
145
- return $result
146
- }
147
-
148
- $probe = Get-WpmFacts -Hwnd $h -Action $Action -ElementName $ElementName
149
- $facts = $probe.facts
150
- $facts.paused = [bool][WpmCtl]::Paused
151
- if ($ElementName) {
152
- # A named control cannot be addressed through a window message: the message tiers take
153
- # coordinates or a child HWND, and "the Save button" is neither. Suppressing the door here is
154
- # what makes 'click the named button' honest -- claiming the quiet tier while actually having
155
- # to raise the window would report the cheap tier for the expensive action.
156
- $facts.messageDoor = $false
157
- }
158
- $decision = Get-WpmChannelDecision $facts
159
-
160
- $result.channel = $decision.channel; $result.tier = $decision.tier
161
- $result.family = $probe.family; $result.cls = $probe.cls
162
- if ($decision.channel -eq 'refuse') {
163
- $result.refusal = $decision.refusal; $result.reason = $decision.reason
164
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
165
- return $result
166
- }
167
-
168
- # Capture the focus table BEFORE the action when the tier may cost a flash. For the quiet tier it
169
- # is still captured, because 'the quiet channel did not take focus' is a claim that needs a
170
- # before-value to be falsifiable.
171
- $entry = Get-WpmFocusEntry
172
- $raisedHwnd = ''
173
- $tAct = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
174
-
175
- try {
176
- if ($decision.channel -eq 'message') {
177
- if ($Action -eq 'type') {
178
- # The door kind is decided ONCE, in the probe (win.ps1), and consumed here by kind.
179
- # This path used to re-match class names with its own copy of the pattern -- and that copy
180
- # carried the same 'Edit' vs 'WindowsForms10.EDIT.*' bug, so a fix in one place would have
181
- # silently left the other broken. One matcher, one truth.
182
- $target = $null
183
- foreach ($d in $probe.doorHandles) {
184
- if ($d.kind -eq 'text') { $target = [IntPtr]$d.hwnd; break }
185
- }
186
- if (-not $target) {
187
- $result.refusal = 'unreachable'; $result.reason = 'no editable child window for the message tier'
188
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
189
- return $result
190
- }
191
- $r = [WpmWin]::MessageText($target, $Text, [bool]$Replace)
192
- $result.detail = "msg=$r child=$($target.ToInt64())"
193
- $result.effect = 'reported-by-send'
194
- } elseif ($Action -eq 'click') {
195
- if ($X -lt 0 -or $Y -lt 0) {
196
- $result.refusal = 'unreachable'; $result.reason = 'click needs screen coordinates'
197
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
198
- return $result
199
- }
200
- $child = Resolve-WpmChildAtPoint $h $X $Y
201
- if ($child -eq [IntPtr]::Zero) {
202
- $result.refusal = 'unreachable'; $result.reason = 'no child window of the target sits under that point'
203
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
204
- return $result
205
- }
206
- $r = [WpmWin]::MessageClick($child, $X, $Y)
207
- $result.detail = "msg=$r child=$($child.ToInt64())"
208
- $result.effect = 'reported-by-send'
209
- }
210
- } elseif ($Action -eq 'focus') {
211
- # Focusing a control is a real operation an agent needs (type into a field, then read it).
212
- # It is also the one action that MUST change keyboard focus, so it is the honest way to
213
- # exercise the bounded-flash path: an Invoke can complete without activating anything, but
214
- # SetFocus cannot -- it transfers focus by definition.
215
- if ($decision.channel -ne 'uia') {
216
- $result.refusal = 'unreachable'; $result.reason = 'focus requires a UIA element; the message tier cannot set keyboard focus'
217
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
218
- return $result
219
- }
220
- $el = $probe.uiaElement
221
- if (-not $el) {
222
- $result.refusal = 'unreachable'; $result.reason = 'no element to focus'
223
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
224
- return $result
225
- }
226
- $el.SetFocus()
227
- $result.detail = 'uia=SetFocus'
228
- $result.effect = 'reported-by-pattern'
229
- } elseif ($decision.channel -eq 'uia') {
230
- $el = $probe.uiaElement
231
- if (-not $el) {
232
- $result.refusal = 'unreachable'; $result.reason = 'pattern was reported but no element could be re-obtained'
233
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
234
- return $result
235
- }
236
- $pats = Get-WpmUiaCached
237
- $kind = $facts.patternKind
238
- if ($kind -eq 'invoke') {
239
- $pat = $el.GetCurrentPattern($pats.invoke)
240
- $pat.Invoke()
241
- } elseif ($kind -eq 'value') {
242
- $pat = $el.GetCurrentPattern($pats.value)
243
- $pat.SetValue($(if ($Replace) { $Text } else { [string]$pat.Current.Value + $Text }))
244
- } elseif ($kind -eq 'toggle') {
245
- $pat = $el.GetCurrentPattern($pats.toggle); $pat.Toggle()
246
- } elseif ($kind -eq 'select') {
247
- $pat = $el.GetCurrentPattern($pats.select); $pat.Select()
248
- } elseif ($kind -eq 'legacy') {
249
- $pat = $el.GetCurrentPattern($pats.legacy); $pat.SetValue($Text)
250
- }
251
- $result.detail = "uia=$kind"
252
- $result.effect = 'reported-by-pattern'
253
- }
254
- } catch {
255
- $result.refusal = 'action_failed'
256
- $result.reason = 'the channel call threw: ' + $_.Exception.Message
257
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
258
- }
259
-
260
- Start-Sleep -Milliseconds $SettleMs
261
-
262
- # Did the action actually take the owner's focus? Measured, not assumed -- the quiet tier is
263
- # expected to say no and the flash tier yes, and a run where both say the same thing is a broken
264
- # instrument rather than a good result.
265
- #
266
- # WHICH window now holds the foreground matters, and the first version got it wrong: it recorded
267
- # whatever held the foreground as "the window we raised". When an action causes the TARGET APP to
268
- # open a dialog, that dialog is what comes forward -- so it looked like our own raised window and
269
- # was promptly restored away, shutting the dialog's focus the agent had just asked for. Only the
270
- # target itself counts as ours; anything else is the app's own window or a third party's, and it
271
- # is classified, never reversed.
272
- $nowFg = [WpmWin]::Fg()
273
- $targetStr = $h.ToInt64().ToString()
274
- $raisedHwnd = ''
275
- $raisedElsewhere = ''
276
- if ($nowFg -ne $entry.fgHwnd) {
277
- $result.focusTaken = 'true'
278
- if ($nowFg -eq $targetStr) { $raisedHwnd = $nowFg } else { $raisedElsewhere = $nowFg }
279
- }
280
- $result.raisedOurs = ($raisedHwnd -ne '').ToString().ToLower()
281
- if ($raisedElsewhere) { $result.raisedElsewhere = $raisedElsewhere }
282
-
283
- if ($decision.needsRestore) {
284
- $res = Restore-WpmFocus -Entry $entry -RaisedHwnd $raisedHwnd -RaisedElsewhere $raisedElsewhere `
285
- -TargetPid ($probe.pid.ToString())
286
- $result.restoreOutcome = $res.outcome
287
- $result.restoreReason = $res.reason
288
- $result.restoreSetFg = $res.setFg
289
- $result.restoreJoined = $res.joined
290
- $result.fgAfterRestore = $res.fgAfter
291
- # A restore the table authorised but the OS refused is a named failure, not a success with a
292
- # caveat: the owner is left in a window they did not choose, so the caller must surface it.
293
- # The span the owner actually pays: from the moment the action was issued to the moment the
294
- # focus was back. Reported separately from end-to-end latency because latency includes the
295
- # door probe and the settle wait, and a 'budget' quoted from latency would overstate the
296
- # disturbance by an order of magnitude.
297
- # Only meaningful when focus was actually taken: reporting a 'flash span' for an action that
298
- # never disturbed the owner would put a scary number next to a non-event.
299
- if ($result.focusTaken -eq 'true') {
300
- $result.flashMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $tAct
301
- }
302
- if ($res.outcome -eq 'restore' -and $res.setFg -ne 'true') {
303
- $result.refusal = 'restore_failed'
304
- $result.reason = 'the OS refused to return the foreground; the owner is still in the wrong window'
305
- }
306
- }
307
-
308
- $result.ok = ($result.refusal -eq '')
309
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
310
- $result.fgBefore = $entry.fgHwnd
311
- $result.fgNow = [WpmWin]::Fg()
312
- return $result
313
- }
1
+ # engine.ps1 -- the only place where a decision becomes a syscall.
2
+ #
3
+ # One entry point, Invoke-WpmAction, and it always returns a result object rather than throwing on
4
+ # a refusal: 'refused' is a normal outcome of this product, not an error path, and R3.2 requires
5
+ # the reason to survive to the caller. Every result carries which channel ran, which tier it cost,
6
+ # whether the owner's focus was taken and given back, and how long the whole thing took.
7
+ #
8
+ # ORDER OF OPERATIONS IS THE SAFETY DESIGN:
9
+ # 1. measure the target's doors (facts; a target with no facts is refused)
10
+ # 2. decide (pure table; pause/elevation/integrity first)
11
+ # 3. if the tier costs a flash: capture the focus table BEFORE touching anything
12
+ # 4. act through the cheapest available door
13
+ # 5. if a flash was taken: restore, once, through the restore table
14
+ # Nothing in step 4 can run for a target whose step 2 said refuse, and nothing in step 5 can pull
15
+ # the focus from a window the owner chose.
16
+
17
+ Set-StrictMode -Version 2.0
18
+ $script:WpmEngineRoot = $PSScriptRoot
19
+ . (Join-Path $PSScriptRoot 'decide.ps1')
20
+ . (Join-Path $PSScriptRoot 'win.ps1')
21
+
22
+ # THE PAUSE FLAG LIVES IN [WpmCtl], a static holder -- not in a script variable. The global hotkey
23
+ # (Ctrl+Alt+Q, overlay.ps1) flips it from the overlay thread while actions read it on the main
24
+ # thread; two copies across threads is the bug pattern this repo keeps meeting, and a script-scope
25
+ # variable is exactly that second copy. $script:WpmPauseReason stays here because it is only ever
26
+ # set through Set-WpmPaused, which runs on the main thread.
27
+ $script:WpmPauseReason = ''
28
+
29
+ function Set-WpmPaused([bool]$On, [string]$Reason = 'owner') {
30
+ [WpmCtl]::Paused = $On
31
+ $script:WpmPauseReason = if ($On) { $Reason } else { '' }
32
+ }
33
+
34
+ function Get-WpmStatus {
35
+ $entry = Get-WpmFocusEntry
36
+ return @{
37
+ paused = [bool][WpmCtl]::Paused
38
+ pauseReason = $script:WpmPauseReason
39
+ foreground = $entry.fgHwnd
40
+ foregroundPid = $entry.fgPid
41
+ focusControl = $entry.focusHwnd
42
+ lastInputAgeMs = $entry.lastInputAgeMs
43
+ # The control board travels with status: whether the owner's overlay/hotkey surface is up, and
44
+ # whether the hotkey actually registered. A silent 'overlay off' would make the README's
45
+ # Ctrl+Alt+Q promise untrue with no way to notice.
46
+ overlayRunning = [bool][WpmCtl]::OverlayOn
47
+ overlayHwnd = [string][WpmCtl]::OverlayHwnd
48
+ hotkeyRegistered = [bool][WpmCtl]::HotkeyOk
49
+ hotkeyLabel = [string][WpmCtl]::HotkeyLabel
50
+ overlayReason = [string][WpmCtl]::Reason
51
+ dpiAware = [bool]$script:WpmDpiAware
52
+ stance = 'no physical injection; no forged-Alt foreground trick'
53
+ }
54
+ }
55
+
56
+ function Get-WpmWindowList {
57
+ # Read-only enumeration for the model to choose a target by hwnd. Only visible, titled, non-cloaked
58
+ # windows are listed: a list padded with invisible helper windows makes target selection guesswork.
59
+ $acc = @()
60
+ $cb = [WpmWin+EnumProc] {
61
+ param([IntPtr]$h, [IntPtr]$l)
62
+ if (-not [WpmWin]::IsWindowVisible($h)) { return $true }
63
+ $t = [WpmWin]::Txt($h)
64
+ if (-not $t) { return $true }
65
+ if ([WpmWin]::IsIconic($h)) { return $true }
66
+ $r = New-Object 'WpmWin+RECT'
67
+ [void][WpmWin]::GetWindowRect($h, [ref]$r)
68
+ $script:WpmEnumAcc += [pscustomobject]@{
69
+ hwnd = $h.ToInt64().ToString()
70
+ title = $t
71
+ cls = [WpmWin]::Cls($h)
72
+ pid = [WpmWin]::PidOf($h)
73
+ rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)"
74
+ }
75
+ return $true
76
+ }
77
+ $script:WpmEnumAcc = @()
78
+ [void][WpmWin]::EnumWindows($cb, [IntPtr]::Zero)
79
+ $out = $script:WpmEnumAcc
80
+ $script:WpmEnumAcc = $null
81
+ return $out
82
+ }
83
+
84
+ function Resolve-WpmChildAtPoint([IntPtr]$Hwnd, [int]$X, [int]$Y) {
85
+ # Which child HWND actually sits under a screen point. Uses ChildWindowFromPointEx (the same
86
+ # approach the competitor uses) instead of trusting a fixed child index: index order is not a
87
+ # contract, and clicking the wrong child is indistinguishable from clicking the right one until
88
+ # the app does something else.
89
+ $p = New-Object 'WpmWin+POINT'
90
+ $p.X = $X; $p.Y = $Y
91
+ $hit = [WpmWin]::WindowFromPoint($p)
92
+ if ($hit -eq [IntPtr]::Zero) { return [IntPtr]::Zero }
93
+ $root = [WpmWin]::Root($hit)
94
+ if ($root -ne $Hwnd) {
95
+ # The point belongs to some other top-level window; acting there would be acting on a window
96
+ # the caller did not name.
97
+ return [IntPtr]::Zero
98
+ }
99
+ return $hit
100
+ }
101
+
102
+ function Get-WpmProofWindow {
103
+ <#
104
+ Sample cursor / foreground / focused-control / last-PHYSICAL-input-age for a fixed window.
105
+ Four read-only syscalls per sample, no process, so it costs nothing the engine would not already
106
+ pay while parked in a wait. Attribution is arithmetic and lives in lib/proof-window.mjs; this
107
+ only produces the raw samples. If a read throws (secure desktop, transient) we stop early and
108
+ return what we have -- the caller then reports 'insufficient' rather than inventing a verdict.
109
+ Returns an array; the leading comma keeps it an array even when there is exactly one element.
110
+ #>
111
+ param([int]$Ms, [int]$EveryMs = 15)
112
+ $samples = @()
113
+ $base = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
114
+ $deadline = $base + $Ms
115
+ $next = $base
116
+ while ($true) {
117
+ $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
118
+ if ($now -ge $deadline) { break }
119
+ if ($now -lt $next) { Start-Sleep -Milliseconds ([Math]::Max(1, [int]($next - $now))); continue }
120
+ try {
121
+ $s = [WpmWin]::Sample()
122
+ $samples += (@{ ts = $now; cx = [int]$s[0]; cy = [int]$s[1]; fg = [string]$s[2]; focus = [string]$s[3]; inputAgeMs = [long]$s[4] })
123
+ } catch { break }
124
+ $next = $now + $EveryMs
125
+ }
126
+ try {
127
+ $tEnd = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
128
+ $s2 = [WpmWin]::Sample()
129
+ $samples += (@{ ts = $tEnd; cx = [int]$s2[0]; cy = [int]$s2[1]; fg = [string]$s2[2]; focus = [string]$s2[3]; inputAgeMs = [long]$s2[4] })
130
+ } catch { }
131
+ return ,$samples
132
+ }
133
+
134
+ function Invoke-WpmAction {
135
+ param(
136
+ [Parameter(Mandatory)][string]$Hwnd,
137
+ [Parameter(Mandatory)][ValidateSet('click', 'type', 'focus', 'status')][string]$Action,
138
+ [int]$X = -1,
139
+ [int]$Y = -1,
140
+ [string]$Text = '',
141
+ [string]$ElementName = '',
142
+ [switch]$Replace,
143
+ [int]$SettleMs = 350
144
+ )
145
+ $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
146
+ $h = [IntPtr][int64]$Hwnd
147
+ $result = @{
148
+ ok = $false; action = $Action; hwnd = $Hwnd; channel = ''; tier = ''
149
+ refusal = ''; reason = ''; detail = ''; latencyMs = 0
150
+ focusTaken = 'false'; restoreOutcome = ''; restoreSetFg = ''; restoreJoined = ''
151
+ effect = 'unverified'; proofSamples = @()
152
+ }
153
+
154
+ # A QUERY IS NOT AN ACTION, and this branch is early on purpose. It used to sit inside the action
155
+ # chain, where 'status' fell through to the UIA branch and INVOKED the pattern it found -- a call
156
+ # whose entire purpose is to report state would click a control. It is also placed before the
157
+ # target check because a query has no target: 'what holds the focus' is answerable whatever the
158
+ # caller passed, and refusing it for an unreachable window would be a query lying about why it
159
+ # is empty. (Found by reading the branch order while writing the refusal cases, not by a failing
160
+ # run -- the assertion in test/refusals-test.ps1 pins the fixed behaviour, it did not catch it.)
161
+ if ($Action -eq 'status') {
162
+ $st = Get-WpmStatus
163
+ $result.ok = $true
164
+ $result.channel = 'none'; $result.tier = 'none'
165
+ $result.detail = 'status: query only, no action taken'
166
+ $result.foreground = $st.foreground
167
+ $result.foregroundPid = $st.foregroundPid
168
+ $result.focusControl = $st.focusControl
169
+ $result.lastInputAgeMs = $st.lastInputAgeMs
170
+ $result.paused = $st.paused
171
+ $result.stance = $st.stance
172
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
173
+ return $result
174
+ }
175
+
176
+ if (-not [WpmWin]::IsWindow($h)) {
177
+ $result.refusal = 'no_hwnd'; $result.reason = 'the hwnd does not identify a live window'
178
+ return $result
179
+ }
180
+
181
+ $probe = Get-WpmFacts -Hwnd $h -Action $Action -ElementName $ElementName
182
+ $facts = $probe.facts
183
+ $facts.paused = [bool][WpmCtl]::Paused
184
+ if ($ElementName) {
185
+ # A named control cannot be addressed through a window message: the message tiers take
186
+ # coordinates or a child HWND, and "the Save button" is neither. Suppressing the door here is
187
+ # what makes 'click the named button' honest -- claiming the quiet tier while actually having
188
+ # to raise the window would report the cheap tier for the expensive action.
189
+ $facts.messageDoor = $false
190
+ }
191
+ $decision = Get-WpmChannelDecision $facts
192
+
193
+ $result.channel = $decision.channel; $result.tier = $decision.tier
194
+ $result.family = $probe.family; $result.cls = $probe.cls
195
+ if ($decision.channel -eq 'refuse') {
196
+ $result.refusal = $decision.refusal; $result.reason = $decision.reason
197
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
198
+ return $result
199
+ }
200
+
201
+ # Capture the focus table BEFORE the action when the tier may cost a flash. For the quiet tier it
202
+ # is still captured, because 'the quiet channel did not take focus' is a claim that needs a
203
+ # before-value to be falsifiable.
204
+ $entry = Get-WpmFocusEntry
205
+ $raisedHwnd = ''
206
+ # THE PRE-ACTION CONTROL WINDOW. Sampled here, immediately BEFORE the door call, so that during it,
207
+ # by construction, WE have done nothing. WHY A CONTROL IS REQUIRED AND NOT JUST A THRESHOLD:
208
+ # "unexplained motion" from GetLastInputInfo proves no PHYSICAL input happened in the gap -- it
209
+ # cannot tell our action apart from some background app nudging the cursor or stealing focus. A
210
+ # hardcoded threshold is the vacuous-control trap this repo wrote down once (P0 task_5(f): "the
211
+ # reset control passed vacuously"), and three real clicks proved it: a clean click measured isolated
212
+ # 3.16px and 7.07px cursor jumps. So the judgment is STRUCTURAL, decided in lib/proof-window.mjs
213
+ # using BOTH windows: sustained multi-gap cursor motion fails (no ambient correction drags across
214
+ # gaps), an isolated single jump is inconclusive (a position delta cannot name its cause), and a
215
+ # foreground/focus switch is blamed on us (fail) only when the control window shows the desktop was
216
+ # NOT already doing it. Kept short (80ms): a few samples, no perceptible slowdown.
217
+ $controlSamples = Get-WpmProofWindow -Ms 80
218
+ $tAct = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
219
+
220
+ try {
221
+ if ($decision.channel -eq 'message') {
222
+ if ($Action -eq 'type') {
223
+ # The door kind is decided ONCE, in the probe (win.ps1), and consumed here by kind.
224
+ # This path used to re-match class names with its own copy of the pattern -- and that copy
225
+ # carried the same 'Edit' vs 'WindowsForms10.EDIT.*' bug, so a fix in one place would have
226
+ # silently left the other broken. One matcher, one truth.
227
+ $target = $null
228
+ foreach ($d in $probe.doorHandles) {
229
+ if ($d.kind -eq 'text') { $target = [IntPtr]$d.hwnd; break }
230
+ }
231
+ if (-not $target) {
232
+ $result.refusal = 'unreachable'; $result.reason = 'no editable child window for the message tier'
233
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
234
+ return $result
235
+ }
236
+ $r = [WpmWin]::MessageText($target, $Text, [bool]$Replace)
237
+ $result.detail = "msg=$r child=$($target.ToInt64())"
238
+ $result.effect = 'reported-by-send'
239
+ } elseif ($Action -eq 'click') {
240
+ if ($X -lt 0 -or $Y -lt 0) {
241
+ $result.refusal = 'unreachable'; $result.reason = 'click needs screen coordinates'
242
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
243
+ return $result
244
+ }
245
+ $child = Resolve-WpmChildAtPoint $h $X $Y
246
+ if ($child -eq [IntPtr]::Zero) {
247
+ $result.refusal = 'unreachable'; $result.reason = 'no child window of the target sits under that point'
248
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
249
+ return $result
250
+ }
251
+ $r = [WpmWin]::MessageClick($child, $X, $Y)
252
+ $result.detail = "msg=$r child=$($child.ToInt64())"
253
+ $result.effect = 'reported-by-send'
254
+ }
255
+ } elseif ($Action -eq 'focus') {
256
+ # Focusing a control is a real operation an agent needs (type into a field, then read it).
257
+ # It is also the one action that MUST change keyboard focus, so it is the honest way to
258
+ # exercise the bounded-flash path: an Invoke can complete without activating anything, but
259
+ # SetFocus cannot -- it transfers focus by definition.
260
+ if ($decision.channel -ne 'uia') {
261
+ $result.refusal = 'unreachable'; $result.reason = 'focus requires a UIA element; the message tier cannot set keyboard focus'
262
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
263
+ return $result
264
+ }
265
+ $el = $probe.uiaElement
266
+ if (-not $el) {
267
+ $result.refusal = 'unreachable'; $result.reason = 'no element to focus'
268
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
269
+ return $result
270
+ }
271
+ $el.SetFocus()
272
+ $result.detail = 'uia=SetFocus'
273
+ $result.effect = 'reported-by-pattern'
274
+ } elseif ($decision.channel -eq 'uia') {
275
+ $el = $probe.uiaElement
276
+ if (-not $el) {
277
+ $result.refusal = 'unreachable'; $result.reason = 'pattern was reported but no element could be re-obtained'
278
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
279
+ return $result
280
+ }
281
+ $pats = Get-WpmUiaCached
282
+ $kind = $facts.patternKind
283
+ if ($kind -eq 'invoke') {
284
+ $pat = $el.GetCurrentPattern($pats.invoke)
285
+ $pat.Invoke()
286
+ } elseif ($kind -eq 'value') {
287
+ $pat = $el.GetCurrentPattern($pats.value)
288
+ $pat.SetValue($(if ($Replace) { $Text } else { [string]$pat.Current.Value + $Text }))
289
+ } elseif ($kind -eq 'toggle') {
290
+ $pat = $el.GetCurrentPattern($pats.toggle); $pat.Toggle()
291
+ } elseif ($kind -eq 'select') {
292
+ $pat = $el.GetCurrentPattern($pats.select); $pat.Select()
293
+ } elseif ($kind -eq 'legacy') {
294
+ $pat = $el.GetCurrentPattern($pats.legacy); $pat.SetValue($Text)
295
+ }
296
+ $result.detail = "uia=$kind"
297
+ $result.effect = 'reported-by-pattern'
298
+ }
299
+ } catch {
300
+ $result.refusal = 'action_failed'
301
+ $result.reason = 'the channel call threw: ' + $_.Exception.Message
302
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
303
+ }
304
+
305
+ # THE ACTION WINDOW. Sampled DURING the settle sleep the engine already performed, so collecting
306
+ # proof costs no extra delay. This is the window the claim is made about; it is judged against the
307
+ # pre-action control captured above (proof-window decides how, from both). Attribution is arithmetic
308
+ # and lives in lib/proof-window.mjs -- the engine only produces samples.
309
+ $result.proofControl = $controlSamples
310
+ $result.proofSamples = Get-WpmProofWindow -Ms $SettleMs
311
+
312
+ # Did the action actually take the owner's focus? Measured, not assumed -- the quiet tier is
313
+ # expected to say no and the flash tier yes, and a run where both say the same thing is a broken
314
+ # instrument rather than a good result.
315
+ #
316
+ # WHICH window now holds the foreground matters, and the first version got it wrong: it recorded
317
+ # whatever held the foreground as "the window we raised". When an action causes the TARGET APP to
318
+ # open a dialog, that dialog is what comes forward -- so it looked like our own raised window and
319
+ # was promptly restored away, shutting the dialog's focus the agent had just asked for. Only the
320
+ # target itself counts as ours; anything else is the app's own window or a third party's, and it
321
+ # is classified, never reversed.
322
+ $nowFg = [WpmWin]::Fg()
323
+ $targetStr = $h.ToInt64().ToString()
324
+ $raisedHwnd = ''
325
+ $raisedElsewhere = ''
326
+ if ($nowFg -ne $entry.fgHwnd) {
327
+ $result.focusTaken = 'true'
328
+ if ($nowFg -eq $targetStr) { $raisedHwnd = $nowFg } else { $raisedElsewhere = $nowFg }
329
+ }
330
+ $result.raisedOurs = ($raisedHwnd -ne '').ToString().ToLower()
331
+ if ($raisedElsewhere) { $result.raisedElsewhere = $raisedElsewhere }
332
+
333
+ if ($decision.needsRestore) {
334
+ $res = Restore-WpmFocus -Entry $entry -RaisedHwnd $raisedHwnd -RaisedElsewhere $raisedElsewhere `
335
+ -TargetPid ($probe.pid.ToString())
336
+ $result.restoreOutcome = $res.outcome
337
+ $result.restoreReason = $res.reason
338
+ $result.restoreSetFg = $res.setFg
339
+ $result.restoreJoined = $res.joined
340
+ $result.fgAfterRestore = $res.fgAfter
341
+ # A restore the table authorised but the OS refused is a named failure, not a success with a
342
+ # caveat: the owner is left in a window they did not choose, so the caller must surface it.
343
+ # The span the owner actually pays: from the moment the action was issued to the moment the
344
+ # focus was back. Reported separately from end-to-end latency because latency includes the
345
+ # door probe and the settle wait, and a 'budget' quoted from latency would overstate the
346
+ # disturbance by an order of magnitude.
347
+ # Only meaningful when focus was actually taken: reporting a 'flash span' for an action that
348
+ # never disturbed the owner would put a scary number next to a non-event.
349
+ if ($result.focusTaken -eq 'true') {
350
+ $result.flashMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $tAct
351
+ }
352
+ if ($res.outcome -eq 'restore' -and $res.setFg -ne 'true') {
353
+ $result.refusal = 'restore_failed'
354
+ $result.reason = 'the OS refused to return the foreground; the owner is still in the wrong window'
355
+ }
356
+ }
357
+
358
+ $result.ok = ($result.refusal -eq '')
359
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
360
+ $result.fgBefore = $entry.fgHwnd
361
+ $result.fgNow = [WpmWin]::Fg()
362
+ return $result
363
+ }