dsh-windows-parallel-mcp 0.5.0 → 0.7.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.
@@ -178,7 +178,24 @@ function Invoke-WpmAction {
178
178
  [string]$Intent = '',
179
179
  [bool]$FullScreen = $false,
180
180
  [int]$MaxWidth = 0,
181
- [int]$ShotsKeep = 10
181
+ [int]$ShotsKeep = 10,
182
+ # ---- 0.6.0: where the caret should be when the message door types (type only) ----------------
183
+ # `idle` is the existing behaviour and stays the default: nothing is touched, so an upgrade cannot
184
+ # start moving carets on its own. `end` is implemented as EM_SETSEL(len,len) with len read from the
185
+ # control, NOT as the documented -1 -- measured on WinForms EDIT, EM_SETSEL(-1,-1) leaves the
186
+ # selection at 0,0 and the character lands at the FRONT (findings 8.2). The UIA `value` channel
187
+ # replaces the whole value and has no caret to place, so it reports caretIgnored rather than
188
+ # pretending the request was honoured.
189
+ [ValidateSet('idle', 'start', 'end')][string]$CaretPosition = 'idle',
190
+ # ---- 0.7.0 authorization, measured here because only this process can see the desktop -------
191
+ # `Policy` and `RequiredTier` come from the host (settings + tools.json). The IDLE CHECK cannot come
192
+ # from the host: last-input age is a GetLastInputInfo reading, and a host that wanted it before the
193
+ # worker call would have to make a worker call. So the ceiling is enforced twice (host pre-worker,
194
+ # engine here) and idle is enforced once, at the only place the number exists.
195
+ [string]$Policy = 'balanced',
196
+ [string]$RequiredTier = 'quiet',
197
+ [int]$PolicyIdleMs = 3000,
198
+ [switch]$ForceUserActive
182
199
  )
183
200
  $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
184
201
  $h = [IntPtr][int64]$Hwnd
@@ -301,6 +318,10 @@ function Invoke-WpmAction {
301
318
  $result.scale = [double]$shot.scale
302
319
  $result.identity = [bool]$shot.identity
303
320
  $result.frame = [string]$shot.frame
321
+ # WHICH CAPTURE PATH PRODUCED THE PICTURE. Reported on every screenshot, not only when the cheap
322
+ # path failed: a field that appears only in the exceptional case is how a silent substitution looks.
323
+ $result.captureBackend = [string]$shot.captureBackend
324
+ if ($shot.captureNote) { $result.captureNote = [string]$shot.captureNote }
304
325
  $result.dpiAware = [bool]$shot.dpiAware
305
326
  $result.bytes = [long]$shot.bytes
306
327
  $result.shotsKeep = [int]$shot.shotsKeep
@@ -353,6 +374,15 @@ function Invoke-WpmAction {
353
374
  return $result
354
375
  }
355
376
 
377
+ # ---- 0.6.0: a DISABLED target is a fact about the target, and Windows discards input to it -----
378
+ # Measured (findings 8.1): with EnableWindow(false) every message this engine sends still RETURNS --
379
+ # WM_SETTEXT and WM_CHAR both answer as if they worked, and the control simply does not take the click.
380
+ # This is deliberately not a new refusal code: 'disabled' is a state of the target, not an error in the
381
+ # call, and the caller may well want to know that the window is there but greyed out. What it does cost
382
+ # is the right to claim an effect: `effect` is pinned to 'unverified' for a disabled target, so a
383
+ # green-looking result cannot be produced by a window that was throwing our input away.
384
+ $targetDisabled = -not [WpmWin]::IsWindowEnabled($h)
385
+
356
386
  # ---- 0.5.0: image coordinates are converted by the ENGINE, before anything is probed ---------
357
387
  # Why here: a bogus shotId must cost zero target probing, and the converted point then flows through
358
388
  # the EXISTING click path unchanged -- including the point-ownership assertion and the proof window.
@@ -433,11 +463,32 @@ function Invoke-WpmAction {
433
463
  $facts.keyInjectAllowed = [bool]$KeyInject # the host gate already stripped the field when off
434
464
  $facts.hudReady = $false
435
465
  $facts.foregroundIsTarget = $false
466
+ # 0.7.0: the rung this call actually needs. An explicit takeover request outranks the action's declared
467
+ # minimum because moving the real cursor IS the higher permission; that escalation has to be visible to
468
+ # the policy and idle checks or `policy:'quiet'` would be bypassed by a single flag.
469
+ $facts.policy = $Policy
470
+ $facts.requiredTier = $(if ($Takeover -or $KeyInject) { 'takeover' } else { $RequiredTier })
471
+ $facts.forceUserActive = [bool]$ForceUserActive
472
+ $facts.policyIdleMs = $PolicyIdleMs
473
+ # Measured NOW, not carried from the earlier probe: an age read before the HUD came up would describe a
474
+ # desktop that no longer exists, and the whole point of this fact is "was the owner busy a moment ago".
475
+ $facts.lastInputAgeMs = [WpmWin]::LastInputAgeMs()
436
476
  $preFacts = $facts.Clone()
437
477
  $preFacts.takeoverRequested = $false
438
478
  $preFacts.keyInjectRequested = $false
479
+ # THE ESCALATION GOES BACK OUT TOO. `requiredTier` was raised to 'takeover' a few lines above because
480
+ # this call asks for the takeover tier; the pre-pass exists precisely to ask "what does the ACTION
481
+ # itself need", so leaving the escalated rung in place made a `keyInput:'inject'`-only call answer
482
+ # `user_active` (an idle refusal) instead of the `keyinject_unavailable` the arm asserts. A clone that
483
+ # clears the request flags must clear what those flags implied, or the pre-pass measures a different
484
+ # call than the one it claims to be checking.
485
+ $preFacts.requiredTier = $RequiredTier
439
486
  $pre = Get-WpmChannelDecision $preFacts
440
- if ($pre.channel -eq 'refuse' -and (@('paused', 'no_hwnd', 'elevated_target') -contains $pre.refusal)) {
487
+ # THE CHEAP DISQUALIFIERS RUN BEFORE ANY WINDOW IS CREATED. 0.7.0 adds policy_denied and user_active to
488
+ # this list rather than letting them be discovered later: a takeover request that the owner's settings
489
+ # exclude must not flash a HUD at them on its way to saying no -- the HUD is itself the disturbance the
490
+ # refusal exists to prevent.
491
+ if ($pre.channel -eq 'refuse' -and (@('paused', 'no_hwnd', 'elevated_target', 'policy_denied', 'user_active') -contains $pre.refusal)) {
441
492
  $result.refusal = $pre.refusal; $result.reason = $pre.reason
442
493
  $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
443
494
  return $result
@@ -537,6 +588,13 @@ function Invoke-WpmAction {
537
588
  # NOT already doing it. Kept short (80ms): a few samples, no perceptible slowdown.
538
589
  $controlSamples = Get-WpmProofWindow -Ms 80
539
590
  $tAct = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
591
+ # 0.6.0 locals. Declared here rather than inside the dispatch branches so that a channel which never
592
+ # armed a readback (invoke/toggle/select, a refusal, an exception) is the ABSENCE of a plan and not a
593
+ # leftover value from the previous call -- this worker is long-lived, and a stale plan would grade
594
+ # today's action against yesterday's field.
595
+ $focusBeforeDoor = $null
596
+ $focusAfterDoor = $null
597
+ $readbackPlan = $null
540
598
 
541
599
  # ---- the takeover choreography (spec.md §3) -------------------------------------------------
542
600
  # Everything from here to the finally exists because R3 promises three things the quiet tier never
@@ -574,6 +632,11 @@ function Invoke-WpmAction {
574
632
  try {
575
633
  # THE CURSOR MOVE LIVES INSIDE THE SAME try THAT OWNS THE RESTORE (spec.md §6 G4): an exception in
576
634
  # the door call below still reaches the finally that puts the pointer back.
635
+ #
636
+ # 0.6.0: the focus table is re-read HERE, at the moment of sending, not reused from the one captured
637
+ # before the probe. See the focusMoved block after the settle window for why this is a warning and
638
+ # never a refusal.
639
+ $focusBeforeDoor = Get-WpmFocusEntry
577
640
  if ($takeover -and -not $abortedBeforeAct -and $Action -eq 'click' -and $X -ge 0 -and $Y -ge 0) {
578
641
  $cursorEntry = Set-WpmCursorTakeover -X $X -Y $Y
579
642
  $result.cursorMoved = if ($cursorEntry.applied) { 'true' } else { 'false' }
@@ -600,8 +663,26 @@ function Invoke-WpmAction {
600
663
  $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
601
664
  return $result
602
665
  }
603
- $r = [WpmWin]::MessageText($target, $Text, [bool]$Replace)
604
- $result.detail = "msg=$r child=$($target.ToInt64())"
666
+ if ([WpmWin]::IsWindowEnabled($target) -eq $false) { $targetDisabled = $true }
667
+ # THE PRE-READ. Taken BEFORE the write, because the expected post-write value is only computable
668
+ # from the value the control held plus the insertion point the CONTROL reports (its own EM_GETSEL
669
+ # answer) -- not from an assumption that a write appends. Measured: an unfocused WinForms TextBox
670
+ # inserts at 0, so 'abc' + 'XYZ' is 'XYZabc'; the model has to know both numbers or the
671
+ # comparison grades its own guess.
672
+ $preRead = Read-WpmControlText -Hwnd $target
673
+ $w = [WpmWin]::MessageTextAt($target, $Text, [bool]$Replace, $CaretPosition)
674
+ $mode = [string]$w[0]
675
+ $sentChars = [int]$w[1]
676
+ $selStart = [int]$w[2]; $selEnd = [int]$w[3]
677
+ $caretAskedAt = if ($w.Count -gt 4) { [int]$w[4] } else { -1 }
678
+ # Readback runs AFTER the settle window (the proof sampling is the settle), so an app that commits
679
+ # its value asynchronously is not judged against a half-written buffer (plan R2).
680
+ $readbackPlan = @{
681
+ kind = 'message'; hwnd = $target; mode = $mode
682
+ pre = $preRead; selStart = $selStart; selEnd = $selEnd; text = $Text; replace = [bool]$Replace
683
+ }
684
+ $caretNote = "caret=$CaretPosition asked=$(if ($caretAskedAt -ge 0) { $caretAskedAt } else { '(untouched)' }) applied=$selStart,$selEnd"
685
+ $result.detail = "msg=$mode|$sentChars child=$($target.ToInt64()) $caretNote" + $(if (-not $preRead.exposesText) { ' readbackPre=unavailable' } else { '' })
605
686
  $result.effect = 'reported-by-send'
606
687
  } elseif ($Action -eq 'click') {
607
688
  if ($X -lt 0 -or $Y -lt 0) {
@@ -675,17 +756,43 @@ function Invoke-WpmAction {
675
756
  $pat.Invoke()
676
757
  } elseif ($kind -eq 'value') {
677
758
  $pat = $el.GetCurrentPattern($pats.value)
759
+ # THE PRE-READ THROUGH THE SAME PATTERN that writes. The UIA `value` channel is a whole-value
760
+ # replace, so the expected after-value is computable exactly -- and the current value is read
761
+ # from the pattern, not from a window message, because this is the channel the write went through.
762
+ $preVal = ''
763
+ $preOk = $false
764
+ try { $preVal = [string]$pat.Current.Value; $preOk = $true } catch { $preOk = $false }
678
765
  $pat.SetValue($(if ($Replace) { $Text } else { [string]$pat.Current.Value + $Text }))
766
+ $readbackPlan = @{
767
+ kind = 'uia-value'; pat = $pat; mode = 'value'
768
+ expected = $(if ($Replace) { $Text } else { $preVal + $Text })
769
+ preOk = $preOk; pre = $preVal; text = $Text; replace = [bool]$Replace
770
+ }
679
771
  } elseif ($kind -eq 'toggle') {
680
772
  $pat = $el.GetCurrentPattern($pats.toggle); $pat.Toggle()
681
773
  } elseif ($kind -eq 'select') {
682
774
  $pat = $el.GetCurrentPattern($pats.select); $pat.Select()
683
775
  } elseif ($kind -eq 'legacy') {
684
- $pat = $el.GetCurrentPattern($pats.legacy); $pat.SetValue($Text)
776
+ $pat = $el.GetCurrentPattern($pats.legacy)
777
+ $preVal = ''; $preOk = $false
778
+ try { $preVal = [string]$pat.Current.Value; $preOk = $true } catch { $preOk = $false }
779
+ $pat.SetValue($Text)
780
+ $readbackPlan = @{
781
+ kind = 'uia-legacy'; pat = $pat; mode = 'legacy'
782
+ expected = $Text; preOk = $preOk; pre = $preVal; text = $Text; replace = $true
783
+ }
685
784
  }
686
785
  $result.detail = "uia=$kind"
786
+ # A caret request on this channel has no meaning -- `value` replaces the whole string, there is no
787
+ # insertion point to move. Saying so is the difference between honouring a parameter and quietly
788
+ # dropping it (the same discipline as `frame` and, in 0.6.0-B, `captureBackend`: a path that did
789
+ # not do what you asked says so in the result).
790
+ if ($CaretPosition -ne 'idle' -and $readbackPlan) {
791
+ $result.detail += " caretIgnored=$kind-pattern"
792
+ }
687
793
  $result.effect = 'reported-by-pattern'
688
794
  }
795
+ $focusAfterDoor = Get-WpmFocusEntry
689
796
  } catch {
690
797
  $result.refusal = 'action_failed'
691
798
  $result.reason = 'the channel call threw: ' + $_.Exception.Message
@@ -730,6 +837,84 @@ function Invoke-WpmAction {
730
837
  $result.proofControl = $controlSamples
731
838
  $result.proofSamples = Get-WpmProofWindow -Ms $SettleMs
732
839
 
840
+ # ---- 0.6.0 READBACK: the fourth `effect`, earned by reading the value back -------------------
841
+ # This runs AFTER the settle window on purpose (plan R2): an application that commits its text
842
+ # asynchronously must not be judged against a half-written buffer. The rule is narrow and it is the
843
+ # whole feature -- `readback-verified` is used ONLY when the value read back equals the value the
844
+ # model predicted from measurements the CONTROL reported. Anything else keeps the effect the write
845
+ # itself earned, and the reason travels in `detail`.
846
+ #
847
+ # A mismatch is NOT a failure. The app may legitimately reformat what it was given (case folding,
848
+ # trimming, a mask, a numeric parse), and `unreachable`/`action_failed` must not be repurposed to
849
+ # mean "the value is not what I expected" -- so the refusal set is unchanged by this block, by design.
850
+ if ($readbackPlan) {
851
+ $expected = $null
852
+ $expectedHow = ''
853
+ if ($readbackPlan.kind -eq 'message') {
854
+ $post = Read-WpmControlText -Hwnd $readbackPlan.hwnd
855
+ $pre = $readbackPlan.pre
856
+ if ($readbackPlan.mode -eq 'settext') {
857
+ $expected = [string]$readbackPlan.text; $expectedHow = 'settext-equals-text'
858
+ } elseif (-not $pre.exposesText -or $pre.truncated) {
859
+ $expected = $null; $expectedHow = $(if (-not $pre.exposesText) { 'pre-read-unavailable' } else { 'pre-read-truncated' })
860
+ } else {
861
+ $b = [string]$pre.text
862
+ $s = [int]$readbackPlan.selStart; $e = [int]$readbackPlan.selEnd
863
+ if ($s -lt 0) { $s = 0 }
864
+ if ($e -lt $s) { $e = $s }
865
+ if ($s -gt $b.Length) { $s = $b.Length }
866
+ if ($e -gt $b.Length) { $e = $b.Length }
867
+ $expected = $b.Substring(0, $s) + [string]$readbackPlan.text + $b.Substring($e)
868
+ $expectedHow = "insert-at-$s-$e"
869
+ }
870
+ $postRef = $post
871
+ } else {
872
+ $postVal = ''; $postOk = $false
873
+ try { $postVal = [string]$readbackPlan.pat.Current.Value; $postOk = $true } catch { $postOk = $false }
874
+ $expected = [string]$readbackPlan.expected; $expectedHow = 'pattern-current-value'
875
+ $postRef = @{ ok = $postOk; exposesText = $postOk; truncated = $false; text = $postVal; chars = $postVal.Length }
876
+ }
877
+
878
+ if (-not $postRef.exposesText) {
879
+ # Not "empty": the read produced nothing usable. Reporting readback=unavailable keeps the two
880
+ # apart, which is the difference between "this field hides its text" and "this field is empty".
881
+ $result.detail += ' readback=unavailable'
882
+ } elseif ($null -eq $expected) {
883
+ $result.detail += " readback=unmodelled($expectedHow)"
884
+ } else {
885
+ $shown = [string]$postRef.text
886
+ if ($shown.Length -gt 120) { $shown = $shown.Substring(0, 119) + [char]0x2026 }
887
+ $result.detail += " readback=$shown readbackLen=$([string]$postRef.text.Length)"
888
+ if ($postRef.text -eq $expected) {
889
+ $result.effect = 'readback-verified'
890
+ } else {
891
+ # The mismatch is carried as data because a caller that only reads `effect` must still be able
892
+ # to tell "nothing reported success" from "it reported success and the value says otherwise".
893
+ $result.detail += ' readbackMismatch=true'
894
+ }
895
+ }
896
+ }
897
+
898
+ # ---- 0.6.0 focus re-check at the moment of sending ------------------------------------------
899
+ # A WARNING, never a refusal. The desktop can move between the probe and the send, and on the
900
+ # bounded-flash tier the move is the channel working as documented. Refusing on a mismatch would
901
+ # kill correct writes to be safe about a fact the readback already judges better -- so the field
902
+ # says what was measured and lets the caller weigh it.
903
+ if ($focusBeforeDoor -and $focusAfterDoor) {
904
+ $moved = ($focusBeforeDoor.fgHwnd -ne $focusAfterDoor.fgHwnd) -or
905
+ ($focusBeforeDoor.focusHwnd -ne $focusAfterDoor.focusHwnd)
906
+ $result.detail += " focusMoved=$($moved.ToString().ToLower())"
907
+ }
908
+
909
+ # ---- 0.6.0 the disabled target, recorded last so it cannot be overridden ---------------------
910
+ # `effect` is pinned to 'unverified' here even if a readback matched: a write into a greyed-out
911
+ # window is not an effect the owner can rely on, and the one claim this field makes is that the
912
+ # channel's own report is not being dressed up as a verified state change.
913
+ if ($targetDisabled) {
914
+ $result.detail += ' disabled=true'
915
+ $result.effect = 'unverified'
916
+ }
917
+
733
918
  # Did the action actually take the owner's focus? Measured, not assumed -- the quiet tier is
734
919
  # expected to say no and the flash tier yes, and a run where both say the same thing is a broken
735
920
  # instrument rather than a good result.
@@ -782,3 +967,220 @@ function Invoke-WpmAction {
782
967
  $result.fgNow = [WpmWin]::Fg()
783
968
  return $result
784
969
  }
970
+
971
+ # ==================================================================================================
972
+ # 0.7.0: the three desktop actions that are NOT door actions.
973
+ # ==================================================================================================
974
+
975
+ function Invoke-WpmDesktopAction {
976
+ <#
977
+ launch / clipboard / window live beside Invoke-WpmAction, not inside it, and that separation is the
978
+ point: a door action chooses a channel, costs a tier, takes and returns a focus, and is judged by a
979
+ proof window. A window move or a clipboard write does none of those things, and routing them through
980
+ the door table would either force them into a refusal code they do not deserve or make the table
981
+ answer for capabilities it never measured.
982
+
983
+ WHAT THEY STILL DO: every one of them is verified by reading the STATE back -- `IsIconic`, the rect,
984
+ the ex-style, the clipboard's own content -- because the rule this product has been bitten by is that
985
+ a syscall's return value describes the CALL. So `effect` uses the same four values and the same rule:
986
+ `readback-verified` only when the read agrees, `unverified` otherwise, and the disagreement or the
987
+ reason travels in `detail`. No refusal code was added for this batch either: `launch` with the gate
988
+ off, a window with no hwnd, and a clipboard holding an unexpected format are all answered by the host
989
+ gate or by the existing `no_hwnd` / `action_failed` vocabulary.
990
+ #>
991
+ param(
992
+ [Parameter(Mandatory)][ValidateSet('launch', 'clipboard', 'window')][string]$Action,
993
+ [string]$Hwnd = '',
994
+ [string]$Target = '',
995
+ [object]$Arguments = $null,
996
+ [int]$WaitMs = 3000,
997
+ [string]$Op = '',
998
+ [string]$Format = 'text',
999
+ [string]$Text = '',
1000
+ [string]$ShotId = '',
1001
+ [int]$X = 0,
1002
+ [int]$Y = 0,
1003
+ [int]$Width = 0,
1004
+ [int]$Height = 0,
1005
+ [int]$MaxChars = 65536,
1006
+ # ---- 0.7.0 authorization. The host gate runs first and costs zero worker requests; these are the
1007
+ # engine's own second line, checked against the same table in decide.ps1 so the two processes cannot
1008
+ # disagree about what the owner permitted.
1009
+ [string]$Policy = 'balanced',
1010
+ [int]$PolicyIdleMs = 3000,
1011
+ [switch]$ForceUserActive,
1012
+ [bool]$AppLaunchAllowed = $false,
1013
+ [string[]]$AppLaunchAllow = @()
1014
+ )
1015
+ $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1016
+ $result = @{ ok = $false; action = $Action; hwnd = $Hwnd; refusal = ''; reason = ''; detail = ''
1017
+ effect = 'unverified'; latencyMs = 0 }
1018
+
1019
+ if ($Action -eq 'launch') {
1020
+ # The engine re-runs the gate and the whitelist through the SAME table the host used. A permission
1021
+ # that lives in only one of the two processes is a permission that can be reached around by calling
1022
+ # the other, and `launch` is the one action where that distinction has consequences.
1023
+ $launchFacts = New-WpmFacts -Hwnd '' -Action launch -FactsMeasured $true `
1024
+ -Policy $Policy -RequiredTier 'takeover' -PolicyIdleMs $PolicyIdleMs `
1025
+ -ForceUserActive:([bool]$ForceUserActive) -LastInputAgeMs ([WpmWin]::LastInputAgeMs()) `
1026
+ -AppLaunchAllowed:$AppLaunchAllowed -AppLaunchAllow $AppLaunchAllow -LaunchTarget $Target
1027
+ $ld = Get-WpmChannelDecision $launchFacts
1028
+ if ($ld.channel -eq 'refuse') {
1029
+ $result.refusal = [string]$ld.refusal; $result.reason = [string]$ld.reason
1030
+ $result.detail = "launch gate: allowed=$AppLaunchAllowed whitelist=$(@($AppLaunchAllow).Count) name(s)"
1031
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1032
+ return $result
1033
+ }
1034
+ $argv = @()
1035
+ if ($Arguments -is [array]) { $argv = @($Arguments | ForEach-Object { [string]$_ }) }
1036
+ elseif ($Arguments -is [string] -and $Arguments) { $argv = @($Arguments) }
1037
+ $s = Start-WpmApp -Target $Target -Arguments $argv
1038
+ if (-not $s.ok) {
1039
+ $result.refusal = 'action_failed'; $result.reason = [string]$s.reason
1040
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1041
+ return $result
1042
+ }
1043
+ $result.pid = [int]$s.pid
1044
+ $result.processName = [string]$s.name
1045
+ $result.target = [string]$s.target
1046
+ # The window is waited for only when the caller asked to address one. hwnd=0 after a successful
1047
+ # launch is a REPORTED state ('window-not-yet'), never a failure -- see Wait-WpmAppWindow.
1048
+ if ($WaitMs -gt 0) {
1049
+ $w = Wait-WpmAppWindow -ProcessId ([int]$s.pid) -WaitMs $WaitMs
1050
+ $result.hwnd = [string]$w.hwnd
1051
+ $result.waitedMs = [int]$w.waitedMs
1052
+ if ($w.hwnd) {
1053
+ $result.ok = $true
1054
+ $result.effect = 'readback-verified'
1055
+ $result.detail = "launched pid=$($s.pid) hwnd=$($w.hwnd) title=$($w.title)"
1056
+ } elseif ($w.ContainsKey('detail')) {
1057
+ # ContainsKey on purpose: Wait-WpmAppWindow answers THREE different shapes -- window found, no
1058
+ # window yet (carries detail=window-not-yet and a note), and the process is gone (carries a
1059
+ # reason and no detail at all). Reading a key that a branch never set is a StrictMode throw, and a
1060
+ # throw inside the handler for a started-but-windowless process would report `action_failed` on
1061
+ # a program that is running fine -- the exact overstatement this engine exists to avoid.
1062
+ $result.ok = $true
1063
+ $result.detail = "launched pid=$($s.pid) " + [string]$w.detail + " waitedMs=$($w.waitedMs)"
1064
+ if ($w.ContainsKey('note')) { $result.note = [string]$w.note }
1065
+ } else {
1066
+ $result.refusal = 'action_failed'
1067
+ $result.reason = [string]$w.reason
1068
+ $result.detail = "launched pid=$($s.pid) but no window could be observed"
1069
+ }
1070
+ } else {
1071
+ $result.ok = $true
1072
+ $result.detail = "launched pid=$($s.pid) window=not-asked (waitMs=0)"
1073
+ }
1074
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1075
+ return $result
1076
+ }
1077
+
1078
+ if ($Action -eq 'clipboard') {
1079
+ if ($Op -eq 'read') {
1080
+ $c = Get-WpmClipboard -Format $Format -MaxChars $MaxChars
1081
+ if (-not $c.ok) {
1082
+ $result.refusal = 'action_failed'; $result.reason = [string]$c.reason
1083
+ # ContainsKey before reading: these failure paths return DIFFERENT key sets by design (a format
1084
+ # miss carries the names it found, an exception does not), and under Set-StrictMode 2.0 reading a
1085
+ # key that is simply absent throws -- turning a documented refusal into a crash inside the
1086
+ # refusal handler, which is the failure mode the first run of this branch produced.
1087
+ if ($c.ContainsKey('formats') -and $c.formats) { $result.detail = 'formats=' + ($c.formats -join ',') }
1088
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1089
+ return $result
1090
+ }
1091
+ $result.ok = $true
1092
+ $result.clipFormat = [string]$c.format
1093
+ if ($c.format -eq 'text') {
1094
+ # The CONTENT is deliberately not put into `detail`: the result text is written into a model's
1095
+ # context and an audit line, and the clipboard is exactly the place where that can carry a token
1096
+ # (R8). Length and the truncation flag are enough to decide what to do next.
1097
+ $result.chars = [int]$c.chars
1098
+ $result.truncated = [bool]$c.truncated
1099
+ $result.effect = 'readback-verified'
1100
+ $result.detail = "clipboard=read format=text chars=$($c.chars)" + $(if ($c.truncated) { " truncated=$($MaxChars)" } else { '' })
1101
+ } else {
1102
+ $result.file = [string]$c.file
1103
+ $result.clipId = [string]$c.clipId
1104
+ $result.imageSize = "$($c.width)x$($c.height)"
1105
+ $result.effect = 'readback-verified'
1106
+ $result.detail = "clipboard=read format=image file=$($c.file) size=$($c.width)x$($c.height)"
1107
+ }
1108
+ } elseif ($Op -eq 'write') {
1109
+ $c = Set-WpmClipboard -Format $Format -Text $Text -ShotId $ShotId
1110
+ if (-not $c.ok) {
1111
+ $result.refusal = $(if ($c.ContainsKey('stale') -and $c.stale) { 'stale_ref' } else { 'action_failed' })
1112
+ $result.reason = [string]$c.reason
1113
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1114
+ return $result
1115
+ }
1116
+ $result.ok = $true
1117
+ $result.clipFormat = [string]$c.format
1118
+ if ($c.format -eq 'text') {
1119
+ $result.chars = [int]$c.chars
1120
+ # The read-back is a LENGTH comparison, and the value itself is not echoed: same reason as above.
1121
+ $result.readbackChars = [int]$c.readbackChars
1122
+ $result.effect = $(if ($c.readbackMatches) { 'readback-verified' } else { 'unverified' })
1123
+ $result.detail = "clipboard=write format=text chars=$($c.chars) readbackChars=$($c.readbackChars)" +
1124
+ $(if ($c.readbackMatches) { '' } else { ' readbackMismatch=true' })
1125
+ } else {
1126
+ $result.readbackSize = "$($c.readbackWidth)x$($c.readbackHeight)"
1127
+ # The image read-back is a SIZE comparison against the shot that was pushed in: the pixels
1128
+ # themselves cannot be hashed (two reads of a live screen differ, findings 5.1) and the shot's own
1129
+ # dimensions are the fact the caller can act on.
1130
+ $dimsMatch = ($c.readbackWidth -eq $c.width) -and ($c.readbackHeight -eq $c.height)
1131
+ $result.effect = $(if ($dimsMatch) { 'readback-verified' } else { 'unverified' })
1132
+ $result.detail = "clipboard=write format=image shotId=$($c.shotId) asked=$($c.width)x$($c.height) readback=$($c.readbackWidth)x$($c.readbackHeight)" +
1133
+ $(if ($dimsMatch) { '' } else { ' readbackMismatch=true' })
1134
+ }
1135
+ } else {
1136
+ $result.refusal = 'action_failed'; $result.reason = "clipboard needs op='read' or op='write'"
1137
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1138
+ return $result
1139
+ }
1140
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1141
+ return $result
1142
+ }
1143
+
1144
+ # ---- window ------------------------------------------------------------------
1145
+ if (-not $Hwnd) {
1146
+ $result.refusal = 'no_hwnd'; $result.reason = 'window acts on one named window; there is no "all windows" op'
1147
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1148
+ return $result
1149
+ }
1150
+ $fgBeforeOp = [WpmWin]::Fg()
1151
+ $w = Invoke-WpmWindowOp -Hwnd ([IntPtr][int64]$Hwnd) -Op $Op -X $X -Y $Y -Width $Width -Height $Height
1152
+ $fgAfterOp = [WpmWin]::Fg()
1153
+ # Only the 'hwnd is not a live window' branch carries a refusal code; the others answer ok/false with a
1154
+ # reason. Under StrictMode an unguarded read of a key that branch never sets would throw inside the
1155
+ # handler, so presence is tested rather than assumed.
1156
+ if ($w.ContainsKey('refusal') -and $w.refusal) { $result.refusal = [string]$w.refusal }
1157
+ $result.ok = [bool]$w.ok
1158
+ $result.reason = [string]$w.reason
1159
+ $bits = @("window=$Op")
1160
+ foreach ($k in @('iconic', 'called', 'asked', 'size', 'rect', 'before', 'topmost', 'exStyle', 'activated')) {
1161
+ if ($w.ContainsKey($k)) {
1162
+ # Lower-cased deliberately: every other boolean this engine puts into `detail` reads
1163
+ # disabled=true / focusMoved=false / verified=true, and a PowerShell `True` in the same sentence is
1164
+ # how a field ends up being parsed two ways by two consumers.
1165
+ $val = $w[$k]
1166
+ if ($val -is [bool]) { $val = $val.ToString().ToLower() }
1167
+ $bits += "$k=$val"
1168
+ }
1169
+ }
1170
+ $bits += $(if ($w.ok) { 'verified=true' } else { 'verified=false' })
1171
+ # DID THE OWNER LOSE THE FOREGROUND TO THIS CALL -- measured on both sides of it, because
1172
+ # `restore` activates by definition and a window op that quietly took the focus while reporting only a
1173
+ # size change is the failure shape this product keeps meeting. Saying it is not the same as refusing
1174
+ # it: the caller asked for the window to come back, and coming back is what restoring means.
1175
+ $fgTaken = ($fgBeforeOp -ne $fgAfterOp) -and ($fgAfterOp -eq $Hwnd)
1176
+ $bits += "foregroundTaken=$($fgTaken.ToString().ToLower())"
1177
+ if ($fgTaken) {
1178
+ $bits += "foregroundBefore=$fgBeforeOp foregroundAfter=$fgAfterOp"
1179
+ }
1180
+ $result.detail = ($bits -join ' ')
1181
+ $result.foregroundTaken = $fgTaken
1182
+ # The window's own answer is the read-back, so the effect follows it directly.
1183
+ $result.effect = $(if ($w.ok) { 'readback-verified' } else { 'unverified' })
1184
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1185
+ return $result
1186
+ }