dsh-windows-parallel-mcp 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/host-tools.js CHANGED
@@ -73,6 +73,21 @@ export const PARAMETERS = {
73
73
  + 'because a window message cannot address "the control called X".',
74
74
  },
75
75
  replace: { type: 'boolean', description: 'Replace the existing value instead of appending (type only).' },
76
+ // ---- 0.6.0: where the caret goes, and what the engine reads back afterwards ------------------
77
+ // The description names the syscall because the parameter is a syscall argument, and it names the
78
+ // measured exception because '-1 means the end' is a documentation sentence that WinForms EDIT does
79
+ // not honour (findings 8.2). A caller reading this should be able to predict the result exactly.
80
+ caretPosition: {
81
+ type: 'string',
82
+ enum: ['idle', 'start', 'end'],
83
+ description:
84
+ 'type only, message door: where the caret sits before the characters are sent. "idle" (default) touches nothing -- ' +
85
+ 'the caret is where the control left it, which for a never-focused field is position 0 (measured), so "idle" is not "start". ' +
86
+ '"start" is EM_SETSEL(0,0); "end" is EM_SETSEL(len,len) with len read from the control, because the documented -1 form is a no-op ' +
87
+ 'on WinForms EDIT. On a buffer containing newlines the numeric end can land inside the text, so the result reports the requested ' +
88
+ 'and the applied pair (caret=end asked=6 applied=4,4) and the readback decides. The UIA value channel replaces the whole value and ' +
89
+ 'has no caret to move -- it answers caretIgnored=value-pattern instead of pretending it honoured this.',
90
+ },
76
91
  settleMs: { type: 'number', description: 'How long to let the app commit its state before the effect is judged (0-2000, default 350).' },
77
92
  // ---- R3. Every one of these costs the owner something real, so each description says so: a caller
78
93
  // that asks for takeover has to know it moves the pointer and needs the HUD up.
package/lib/index.js CHANGED
@@ -378,6 +378,13 @@ export function apply(ctx, config = {}) {
378
378
  return {
379
379
  action: 'type', hwnd: args.hwnd, text: args.text,
380
380
  elementName: args.elementName ?? '', replace: args.replace === true, settleMs,
381
+ // Forwarded only when it is one of the three values the engine declares; anything else is
382
+ // dropped to the default HERE rather than passed on, because the engine's ValidateSet would
383
+ // turn a model's typo into `action_failed` -- and a schema the host already validates against
384
+ // (validateArguments, plus the registered enum) means a wrong value here did not come from a
385
+ // validated call. The drop is logged into the result by the engine's own caret= field, which
386
+ // always reports what was applied.
387
+ caretPosition: args.caretPosition === 'start' || args.caretPosition === 'end' ? args.caretPosition : 'idle',
381
388
  ...(typeof args.label === 'number' && args.label > 0
382
389
  ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
383
390
  : {}),
@@ -670,13 +677,19 @@ function format(action, r) {
670
677
  if (action === 'preview') return formatPreview(r);
671
678
 
672
679
  // WHO REPORTED THE SUCCESS. The engine sets `effect` when a channel call RETURNS without throwing;
673
- // this file never upgrades it, and the three values are not degrees of confidence in the app -- they
674
- // name who is speaking (README's table states the same three lines, keep them in step):
680
+ // this file never upgrades it, and the four values are not degrees of confidence in the app -- they
681
+ // name who is speaking (README's table states the same four lines, keep them in step):
675
682
  // unverified no channel reported success at all;
676
683
  // reported-by-send the window message was DELIVERED -- nothing here proves the target app
677
684
  // processed it;
678
- // reported-by-pattern the UIA pattern call RETURNED -- nothing here proves the interface changed.
679
- // Read as "who says it worked", never as "the application's state is confirmed".
685
+ // reported-by-pattern the UIA pattern call RETURNED -- nothing here proves the interface changed;
686
+ // readback-verified 0.6.0: the value was READ BACK after the settle window and equals the value
687
+ // predicted from measurements the CONTROL reported. This is the only value that
688
+ // is about the application rather than about the call, and the engine grants it
689
+ // only on an exact match -- a masked field reports readback=unavailable and an
690
+ // app that reformatted the input reports readbackMismatch=true, neither of which
691
+ // is an upgrade (findings 8.1/8.2).
692
+ // Read the first three as "who says it worked", never as "the application's state is confirmed".
680
693
  const bits = [
681
694
  `${action} ok`,
682
695
  `channel=${r.channel || '?'}`,
@@ -848,7 +861,7 @@ function formatScreenshot(r) {
848
861
  const identity = r.identity === true || r.identity === 'true';
849
862
  const dpiAware = r.dpiAware === true || r.dpiAware === 'true';
850
863
  const lines = [
851
- `screenshot ok: ${size.width ?? '?'}x${size.height ?? '?'} px (scale=${scale} identity=${identity}) frame=${r.frame || '?'} dpiAware=${dpiAware}`,
864
+ `screenshot ok: ${size.width ?? '?'}x${size.height ?? '?'} px (scale=${scale} identity=${identity}) frame=${r.frame || '?'} captureBackend=${r.captureBackend || '?'} dpiAware=${dpiAware}`,
852
865
  `file=${r.file || '?'}`,
853
866
  `shotId=${r.shotId || '?'}`,
854
867
  `screenRect=${rect.left ?? '?'},${rect.top ?? '?'},${rect.right ?? '?'},${rect.bottom ?? '?'} `
@@ -856,6 +869,12 @@ function formatScreenshot(r) {
856
869
  'mapping: screenX = screenRect.left + round(imageX / scale); screenY = screenRect.top + round(imageY / scale). '
857
870
  + `The ENGINE applies this when a click passes space:"image" with shotId=${r.shotId || '?'}; do not multiply it yourself.`,
858
871
  ];
872
+ // 0.6.0-B. The cheap path is BitBlt and the fallback is Graphics.CopyFromScreen; they are measured
873
+ // equivalent on a still scene (identical size, identical PNG bytes, 0 per-channel difference over
874
+ // 17388 sample points) and they are NOT the same call, so which one ran is part of the result rather
875
+ // than an implementation detail. A note appears only when the fast path was refused.
876
+ if (!r.captureBackend) lines.push('note: captureBackend was not reported by the engine -- this result predates 0.6.0 or the engine is out of step with this build.');
877
+ if (r.captureNote) lines.push(`note: ${r.captureNote} -- the picture came from Graphics.CopyFromScreen this time.`);
859
878
  if (identity) {
860
879
  lines.push('identity=true means the image was NOT resampled: image pixels and screen pixels differ only by the rect origin.');
861
880
  }
@@ -865,7 +884,7 @@ function formatScreenshot(r) {
865
884
  }
866
885
  return result('screenshot', true, '', lines.join('\n'), {
867
886
  shotId: r.shotId, file: r.file, screenRect: rect, imageSize: size,
868
- scale, identity, frame: r.frame, dpiAware,
887
+ scale, identity, frame: r.frame, captureBackend: r.captureBackend, dpiAware,
869
888
  });
870
889
  }
871
890
 
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "dsh-windows-parallel-mcp",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest",
7
7
  "registry": "https://registry.npmjs.org/"
8
8
  },
9
- "description": "Drive a Windows window quietly by default and visibly on request: one tool, eight actions (windows, status, click, type, focus, snapshot, screenshot, preview), a channel decision table that prefers the quiet door, a bounded self-reversing focus flash when only UI Automation can reach the control, an opt-in takeover tier (HUD mandatory, cursor always restored, keyboard injection only when asked and only for the foreground target), and a read surface that hands the model a numbered element frame plus screenshot coordinates as data so it never multiplies a scale factor. Windows PowerShell 5.1 sidecar, zero install dependencies, no mouse injection.",
9
+ "description": "Drive a Windows window quietly by default and visibly on request: one tool, eight actions (windows, status, click, type, focus, snapshot, screenshot, preview), a channel decision table that prefers the quiet door, a bounded self-reversing focus flash when only UI Automation can reach the control, an opt-in takeover tier (HUD mandatory, cursor always restored, keyboard injection only when asked and only for the foreground target), and a read surface that hands the model a numbered element frame plus screenshot coordinates as data so it never multiplies a scale factor. Since 0.6.0 a write is read back: effect=readback-verified is granted only when the value in the field matches a prediction built from the control's own measurements, caretPosition places the caret (start/end, with the applied selection reported), disabled and focus-moved targets are named in the result, and the screenshot says which path painted it (captureBackend=bitblt|gdiplus). Windows PowerShell 5.1 sidecar, zero install dependencies, no mouse injection.",
10
10
  "keywords": [
11
11
  "deepseek",
12
12
  "deepseek-harness",
@@ -178,7 +178,15 @@ 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'
182
190
  )
183
191
  $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
184
192
  $h = [IntPtr][int64]$Hwnd
@@ -301,6 +309,10 @@ function Invoke-WpmAction {
301
309
  $result.scale = [double]$shot.scale
302
310
  $result.identity = [bool]$shot.identity
303
311
  $result.frame = [string]$shot.frame
312
+ # WHICH CAPTURE PATH PRODUCED THE PICTURE. Reported on every screenshot, not only when the cheap
313
+ # path failed: a field that appears only in the exceptional case is how a silent substitution looks.
314
+ $result.captureBackend = [string]$shot.captureBackend
315
+ if ($shot.captureNote) { $result.captureNote = [string]$shot.captureNote }
304
316
  $result.dpiAware = [bool]$shot.dpiAware
305
317
  $result.bytes = [long]$shot.bytes
306
318
  $result.shotsKeep = [int]$shot.shotsKeep
@@ -353,6 +365,15 @@ function Invoke-WpmAction {
353
365
  return $result
354
366
  }
355
367
 
368
+ # ---- 0.6.0: a DISABLED target is a fact about the target, and Windows discards input to it -----
369
+ # Measured (findings 8.1): with EnableWindow(false) every message this engine sends still RETURNS --
370
+ # WM_SETTEXT and WM_CHAR both answer as if they worked, and the control simply does not take the click.
371
+ # This is deliberately not a new refusal code: 'disabled' is a state of the target, not an error in the
372
+ # call, and the caller may well want to know that the window is there but greyed out. What it does cost
373
+ # is the right to claim an effect: `effect` is pinned to 'unverified' for a disabled target, so a
374
+ # green-looking result cannot be produced by a window that was throwing our input away.
375
+ $targetDisabled = -not [WpmWin]::IsWindowEnabled($h)
376
+
356
377
  # ---- 0.5.0: image coordinates are converted by the ENGINE, before anything is probed ---------
357
378
  # Why here: a bogus shotId must cost zero target probing, and the converted point then flows through
358
379
  # the EXISTING click path unchanged -- including the point-ownership assertion and the proof window.
@@ -537,6 +558,13 @@ function Invoke-WpmAction {
537
558
  # NOT already doing it. Kept short (80ms): a few samples, no perceptible slowdown.
538
559
  $controlSamples = Get-WpmProofWindow -Ms 80
539
560
  $tAct = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
561
+ # 0.6.0 locals. Declared here rather than inside the dispatch branches so that a channel which never
562
+ # armed a readback (invoke/toggle/select, a refusal, an exception) is the ABSENCE of a plan and not a
563
+ # leftover value from the previous call -- this worker is long-lived, and a stale plan would grade
564
+ # today's action against yesterday's field.
565
+ $focusBeforeDoor = $null
566
+ $focusAfterDoor = $null
567
+ $readbackPlan = $null
540
568
 
541
569
  # ---- the takeover choreography (spec.md §3) -------------------------------------------------
542
570
  # Everything from here to the finally exists because R3 promises three things the quiet tier never
@@ -574,6 +602,11 @@ function Invoke-WpmAction {
574
602
  try {
575
603
  # THE CURSOR MOVE LIVES INSIDE THE SAME try THAT OWNS THE RESTORE (spec.md §6 G4): an exception in
576
604
  # the door call below still reaches the finally that puts the pointer back.
605
+ #
606
+ # 0.6.0: the focus table is re-read HERE, at the moment of sending, not reused from the one captured
607
+ # before the probe. See the focusMoved block after the settle window for why this is a warning and
608
+ # never a refusal.
609
+ $focusBeforeDoor = Get-WpmFocusEntry
577
610
  if ($takeover -and -not $abortedBeforeAct -and $Action -eq 'click' -and $X -ge 0 -and $Y -ge 0) {
578
611
  $cursorEntry = Set-WpmCursorTakeover -X $X -Y $Y
579
612
  $result.cursorMoved = if ($cursorEntry.applied) { 'true' } else { 'false' }
@@ -600,8 +633,26 @@ function Invoke-WpmAction {
600
633
  $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
601
634
  return $result
602
635
  }
603
- $r = [WpmWin]::MessageText($target, $Text, [bool]$Replace)
604
- $result.detail = "msg=$r child=$($target.ToInt64())"
636
+ if ([WpmWin]::IsWindowEnabled($target) -eq $false) { $targetDisabled = $true }
637
+ # THE PRE-READ. Taken BEFORE the write, because the expected post-write value is only computable
638
+ # from the value the control held plus the insertion point the CONTROL reports (its own EM_GETSEL
639
+ # answer) -- not from an assumption that a write appends. Measured: an unfocused WinForms TextBox
640
+ # inserts at 0, so 'abc' + 'XYZ' is 'XYZabc'; the model has to know both numbers or the
641
+ # comparison grades its own guess.
642
+ $preRead = Read-WpmControlText -Hwnd $target
643
+ $w = [WpmWin]::MessageTextAt($target, $Text, [bool]$Replace, $CaretPosition)
644
+ $mode = [string]$w[0]
645
+ $sentChars = [int]$w[1]
646
+ $selStart = [int]$w[2]; $selEnd = [int]$w[3]
647
+ $caretAskedAt = if ($w.Count -gt 4) { [int]$w[4] } else { -1 }
648
+ # Readback runs AFTER the settle window (the proof sampling is the settle), so an app that commits
649
+ # its value asynchronously is not judged against a half-written buffer (plan R2).
650
+ $readbackPlan = @{
651
+ kind = 'message'; hwnd = $target; mode = $mode
652
+ pre = $preRead; selStart = $selStart; selEnd = $selEnd; text = $Text; replace = [bool]$Replace
653
+ }
654
+ $caretNote = "caret=$CaretPosition asked=$(if ($caretAskedAt -ge 0) { $caretAskedAt } else { '(untouched)' }) applied=$selStart,$selEnd"
655
+ $result.detail = "msg=$mode|$sentChars child=$($target.ToInt64()) $caretNote" + $(if (-not $preRead.exposesText) { ' readbackPre=unavailable' } else { '' })
605
656
  $result.effect = 'reported-by-send'
606
657
  } elseif ($Action -eq 'click') {
607
658
  if ($X -lt 0 -or $Y -lt 0) {
@@ -675,17 +726,43 @@ function Invoke-WpmAction {
675
726
  $pat.Invoke()
676
727
  } elseif ($kind -eq 'value') {
677
728
  $pat = $el.GetCurrentPattern($pats.value)
729
+ # THE PRE-READ THROUGH THE SAME PATTERN that writes. The UIA `value` channel is a whole-value
730
+ # replace, so the expected after-value is computable exactly -- and the current value is read
731
+ # from the pattern, not from a window message, because this is the channel the write went through.
732
+ $preVal = ''
733
+ $preOk = $false
734
+ try { $preVal = [string]$pat.Current.Value; $preOk = $true } catch { $preOk = $false }
678
735
  $pat.SetValue($(if ($Replace) { $Text } else { [string]$pat.Current.Value + $Text }))
736
+ $readbackPlan = @{
737
+ kind = 'uia-value'; pat = $pat; mode = 'value'
738
+ expected = $(if ($Replace) { $Text } else { $preVal + $Text })
739
+ preOk = $preOk; pre = $preVal; text = $Text; replace = [bool]$Replace
740
+ }
679
741
  } elseif ($kind -eq 'toggle') {
680
742
  $pat = $el.GetCurrentPattern($pats.toggle); $pat.Toggle()
681
743
  } elseif ($kind -eq 'select') {
682
744
  $pat = $el.GetCurrentPattern($pats.select); $pat.Select()
683
745
  } elseif ($kind -eq 'legacy') {
684
- $pat = $el.GetCurrentPattern($pats.legacy); $pat.SetValue($Text)
746
+ $pat = $el.GetCurrentPattern($pats.legacy)
747
+ $preVal = ''; $preOk = $false
748
+ try { $preVal = [string]$pat.Current.Value; $preOk = $true } catch { $preOk = $false }
749
+ $pat.SetValue($Text)
750
+ $readbackPlan = @{
751
+ kind = 'uia-legacy'; pat = $pat; mode = 'legacy'
752
+ expected = $Text; preOk = $preOk; pre = $preVal; text = $Text; replace = $true
753
+ }
685
754
  }
686
755
  $result.detail = "uia=$kind"
756
+ # A caret request on this channel has no meaning -- `value` replaces the whole string, there is no
757
+ # insertion point to move. Saying so is the difference between honouring a parameter and quietly
758
+ # dropping it (the same discipline as `frame` and, in 0.6.0-B, `captureBackend`: a path that did
759
+ # not do what you asked says so in the result).
760
+ if ($CaretPosition -ne 'idle' -and $readbackPlan) {
761
+ $result.detail += " caretIgnored=$kind-pattern"
762
+ }
687
763
  $result.effect = 'reported-by-pattern'
688
764
  }
765
+ $focusAfterDoor = Get-WpmFocusEntry
689
766
  } catch {
690
767
  $result.refusal = 'action_failed'
691
768
  $result.reason = 'the channel call threw: ' + $_.Exception.Message
@@ -730,6 +807,84 @@ function Invoke-WpmAction {
730
807
  $result.proofControl = $controlSamples
731
808
  $result.proofSamples = Get-WpmProofWindow -Ms $SettleMs
732
809
 
810
+ # ---- 0.6.0 READBACK: the fourth `effect`, earned by reading the value back -------------------
811
+ # This runs AFTER the settle window on purpose (plan R2): an application that commits its text
812
+ # asynchronously must not be judged against a half-written buffer. The rule is narrow and it is the
813
+ # whole feature -- `readback-verified` is used ONLY when the value read back equals the value the
814
+ # model predicted from measurements the CONTROL reported. Anything else keeps the effect the write
815
+ # itself earned, and the reason travels in `detail`.
816
+ #
817
+ # A mismatch is NOT a failure. The app may legitimately reformat what it was given (case folding,
818
+ # trimming, a mask, a numeric parse), and `unreachable`/`action_failed` must not be repurposed to
819
+ # mean "the value is not what I expected" -- so the refusal set is unchanged by this block, by design.
820
+ if ($readbackPlan) {
821
+ $expected = $null
822
+ $expectedHow = ''
823
+ if ($readbackPlan.kind -eq 'message') {
824
+ $post = Read-WpmControlText -Hwnd $readbackPlan.hwnd
825
+ $pre = $readbackPlan.pre
826
+ if ($readbackPlan.mode -eq 'settext') {
827
+ $expected = [string]$readbackPlan.text; $expectedHow = 'settext-equals-text'
828
+ } elseif (-not $pre.exposesText -or $pre.truncated) {
829
+ $expected = $null; $expectedHow = $(if (-not $pre.exposesText) { 'pre-read-unavailable' } else { 'pre-read-truncated' })
830
+ } else {
831
+ $b = [string]$pre.text
832
+ $s = [int]$readbackPlan.selStart; $e = [int]$readbackPlan.selEnd
833
+ if ($s -lt 0) { $s = 0 }
834
+ if ($e -lt $s) { $e = $s }
835
+ if ($s -gt $b.Length) { $s = $b.Length }
836
+ if ($e -gt $b.Length) { $e = $b.Length }
837
+ $expected = $b.Substring(0, $s) + [string]$readbackPlan.text + $b.Substring($e)
838
+ $expectedHow = "insert-at-$s-$e"
839
+ }
840
+ $postRef = $post
841
+ } else {
842
+ $postVal = ''; $postOk = $false
843
+ try { $postVal = [string]$readbackPlan.pat.Current.Value; $postOk = $true } catch { $postOk = $false }
844
+ $expected = [string]$readbackPlan.expected; $expectedHow = 'pattern-current-value'
845
+ $postRef = @{ ok = $postOk; exposesText = $postOk; truncated = $false; text = $postVal; chars = $postVal.Length }
846
+ }
847
+
848
+ if (-not $postRef.exposesText) {
849
+ # Not "empty": the read produced nothing usable. Reporting readback=unavailable keeps the two
850
+ # apart, which is the difference between "this field hides its text" and "this field is empty".
851
+ $result.detail += ' readback=unavailable'
852
+ } elseif ($null -eq $expected) {
853
+ $result.detail += " readback=unmodelled($expectedHow)"
854
+ } else {
855
+ $shown = [string]$postRef.text
856
+ if ($shown.Length -gt 120) { $shown = $shown.Substring(0, 119) + [char]0x2026 }
857
+ $result.detail += " readback=$shown readbackLen=$([string]$postRef.text.Length)"
858
+ if ($postRef.text -eq $expected) {
859
+ $result.effect = 'readback-verified'
860
+ } else {
861
+ # The mismatch is carried as data because a caller that only reads `effect` must still be able
862
+ # to tell "nothing reported success" from "it reported success and the value says otherwise".
863
+ $result.detail += ' readbackMismatch=true'
864
+ }
865
+ }
866
+ }
867
+
868
+ # ---- 0.6.0 focus re-check at the moment of sending ------------------------------------------
869
+ # A WARNING, never a refusal. The desktop can move between the probe and the send, and on the
870
+ # bounded-flash tier the move is the channel working as documented. Refusing on a mismatch would
871
+ # kill correct writes to be safe about a fact the readback already judges better -- so the field
872
+ # says what was measured and lets the caller weigh it.
873
+ if ($focusBeforeDoor -and $focusAfterDoor) {
874
+ $moved = ($focusBeforeDoor.fgHwnd -ne $focusAfterDoor.fgHwnd) -or
875
+ ($focusBeforeDoor.focusHwnd -ne $focusAfterDoor.focusHwnd)
876
+ $result.detail += " focusMoved=$($moved.ToString().ToLower())"
877
+ }
878
+
879
+ # ---- 0.6.0 the disabled target, recorded last so it cannot be overridden ---------------------
880
+ # `effect` is pinned to 'unverified' here even if a readback matched: a write into a greyed-out
881
+ # window is not an effect the owner can rely on, and the one claim this field makes is that the
882
+ # channel's own report is not being dressed up as a verified state change.
883
+ if ($targetDisabled) {
884
+ $result.detail += ' disabled=true'
885
+ $result.effect = 'unverified'
886
+ }
887
+
733
888
  # Did the action actually take the owner's focus? Measured, not assumed -- the quiet tier is
734
889
  # expected to say no and the flash tier yes, and a run where both say the same thing is a broken
735
890
  # instrument rather than a good result.
@@ -63,7 +63,6 @@ public static class WpmWin
63
63
  [DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint tid, ref GUITHREADINFO gti);
64
64
 
65
65
  [DllImport("user32.dll")] public static extern IntPtr SendMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
66
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageStrW(IntPtr h, uint m, IntPtr w, string l);
67
66
  [DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
68
67
 
69
68
  [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
@@ -343,10 +342,104 @@ public static class WpmWin
343
342
  for (int i = 0; i < text.Length; i++) SendMessageW(child, 0x0102, (IntPtr)text[i], IntPtr.Zero);
344
343
  return "char|" + text.Length;
345
344
  }
346
- SendMessageStrW(child, 0x000C, IntPtr.Zero, text);
345
+ SendMessageString(child, 0x000C, IntPtr.Zero, text);
347
346
  return "settext|" + text.Length;
348
347
  }
349
348
 
349
+ // ---- 0.6.0: reading the value back, and putting the caret somewhere on purpose -------------
350
+ // WHY THESE PRIMITIVES DID NOT EXIST BEFORE. The message door only ever SENT; every claim about
351
+ // "the field now contains this" was a report of what SendMessage returned, which is a statement
352
+ // about delivery, not about the application's state. Measured on 2026-11-23 (findings 8.2) with an
353
+ // in-process oracle: on a plain Win32 EDIT that has never held focus, WM_CHAR is INERT -- every
354
+ // character is accepted and nothing changes -- while the shipped answer was `reported-by-send`.
355
+ // The read is what turns that from a false success into a visible one.
356
+ //
357
+ // ONE MORE THING THIS FIXED, found by running the syscall instead of trusting the import: the
358
+ // previous WM_SETTEXT binding was declared as `SendMessageStrW`, which user32.dll does not export
359
+ // (.tmp/_t-sendmessagestrw.ps1: EntryPointNotFoundException, first call, every call). So
360
+ // `type` with replace:true threw and surfaced as `action_failed` on EVERY target, and no test in
361
+ // the repo exercised it. The entry point is now pinned explicitly, because a marshaller resolves
362
+ // the name it is given and an alias that exists in nobody's header is not a name.
363
+ [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageW")]
364
+ public static extern IntPtr SendMessageString(IntPtr h, uint m, IntPtr w, string l);
365
+
366
+ [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageW")]
367
+ public static extern IntPtr SendMessageBuffer(IntPtr h, uint m, IntPtr w, [Out()] StringBuilder l);
368
+
369
+ // The hang-proof read. A plain SendMessageW(WM_GETTEXT) to a window whose thread is busy blocks
370
+ // this worker indefinitely, and a read is never worth wedging the sidecar for: with a budget the
371
+ // answer degrades to `unavailable`, which the engine reports instead of inventing.
372
+ [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageTimeoutW")]
373
+ public static extern IntPtr SendMessageTimeoutBuffer(IntPtr h, uint m, IntPtr w, [Out()] StringBuilder l,
374
+ uint flags, uint ms, out IntPtr res);
375
+
376
+ [DllImport("user32.dll")] public static extern bool IsWindowEnabled(IntPtr h);
377
+
378
+ public const uint WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E;
379
+ public const uint WM_CHAR = 0x0102, EM_SETSEL = 0x00B1, EM_GETSEL = 0x00B0;
380
+ public const uint SMTO_ABORTIFHUNG = 0x0002;
381
+
382
+ /// <summary>WM_GETTEXTLENGTH. A length the CONTROL reports, not a length we computed.</summary>
383
+ public static int TextLength(IntPtr h) { return (int)(long)SendMessageW(h, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero); }
384
+
385
+ /// <summary>{ok, chars, text} from WM_GETTEXT, sized from the control's own WM_GETTEXTLENGTH.
386
+ /// The buffer is deliberately one char LONGER than the reported length: the control writes a
387
+ /// terminating NUL into the buffer it is handed, and a measured truncation (a 1000-char buffer
388
+ /// against a 5000-char value came back as 999) has to stay visible rather than become the answer.</summary>
389
+ public static object[] ReadText(IntPtr h, uint ms)
390
+ {
391
+ int len = TextLength(h);
392
+ if (len < 0) len = 0;
393
+ if (len > 65536) len = 65536; // a capped read, reported as truncated downstream
394
+ var sb = new StringBuilder(len + 2);
395
+ IntPtr res;
396
+ IntPtr r = SendMessageTimeoutBuffer(h, WM_GETTEXT, (IntPtr)(len + 1), sb, SMTO_ABORTIFHUNG, ms, out res);
397
+ if (r == IntPtr.Zero) return new object[] { false, -1, "" };
398
+ int n = (int)(long)res;
399
+ string s = sb.ToString();
400
+ if (n >= 0 && n <= s.Length) s = s.Substring(0, n);
401
+ return new object[] { true, n, s };
402
+ }
403
+
404
+ /// <summary>{start, end} from EM_GETSEL -- the control's own answer about where a typed
405
+ /// character will land, which is what makes an expected-value model computable (findings 8.2).</summary>
406
+ public static int[] GetSel(IntPtr h)
407
+ {
408
+ long r = (long)SendMessageW(h, EM_GETSEL, IntPtr.Zero, IntPtr.Zero);
409
+ return new int[] { (int)(r & 0xFFFF), (int)((r >> 16) & 0xFFFF) };
410
+ }
411
+
412
+ /// <summary>EM_SETSEL. NOTE: -1 is NOT used for `end` -- measured on WinForms EDIT it leaves the
413
+ /// selection at 0,0 and the typed character goes to the FRONT (findings 8.2). The caller passes
414
+ /// the length it read from the control.</summary>
415
+ public static void SetSel(IntPtr h, int a, int b) { SendMessageW(h, EM_SETSEL, (IntPtr)a, (IntPtr)b); }
416
+
417
+ /// <summary>
418
+ /// Write text through the message door with an explicit caret intention, and report BOTH what was
419
+ /// asked for and what the control says its selection now is. The selection is read back rather than
420
+ /// echoed because the whole point is that the control, not the caller, decides where text goes:
421
+ /// EM_SETSEL(6,6) on a buffer whose WM_GETTEXTLENGTH is 6 came back as 4,4 on a value containing a
422
+ /// newline, and an engine that reported the requested pair would have been describing a wish.
423
+ /// mode: 'settext' (whole-value replace) | 'char' (per-character, inserted at the reported sel).
424
+ /// </summary>
425
+ public static object[] MessageTextAt(IntPtr child, string text, bool replace, string caret)
426
+ {
427
+ if (replace)
428
+ {
429
+ SendMessageString(child, WM_SETTEXT, IntPtr.Zero, text);
430
+ if (caret == "start") SetSel(child, 0, 0);
431
+ else if (caret == "end") { int l = TextLength(child); SetSel(child, l, l); }
432
+ int[] rs = GetSel(child);
433
+ return new object[] { "settext", text.Length, rs[0], rs[1] };
434
+ }
435
+ int askedStart = -1, askedEnd = -1;
436
+ if (caret == "start") { SetSel(child, 0, 0); askedStart = 0; askedEnd = 0; }
437
+ else if (caret == "end") { int l = TextLength(child); SetSel(child, l, l); askedStart = l; askedEnd = l; }
438
+ int[] sel = GetSel(child);
439
+ for (int i = 0; i < text.Length; i++) SendMessageW(child, WM_CHAR, (IntPtr)text[i], IntPtr.Zero);
440
+ return new object[] { "char", text.Length, sel[0], sel[1], askedStart, askedEnd };
441
+ }
442
+
350
443
  // ---- 0.5.0: the frame, the virtual screen, and the capture footprint ---------------------
351
444
  // THE FRAME COMES FROM DWM, NOT FROM GetWindowRect. Measured on this desktop (2026-11-23):
352
445
  // GetWindowRect returns -8,-8,1928,1040 while DwmGetWindowAttribute(EXTENDED_FRAME_BOUNDS)
@@ -383,6 +476,69 @@ public static class WpmWin
383
476
  return new int[] { GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN),
384
477
  GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN) };
385
478
  }
479
+
480
+ // ---- 0.6.0-B: the cheaper capture, with the SAME semantics as the one it replaces -----------
481
+ // WHY. Measured on this host (findings 8.4): the capture is not the bottleneck -- PNG encoding is
482
+ // (37-39ms of a ~70ms screenshot). But the capture half still costs 22-33ms through
483
+ // Graphics.CopyFromScreen and 16-21ms through a direct BitBlt, so the cheap primitive is taken and
484
+ // the encoder is left alone. JPEG (10ms, but it smears text), WIC (158ms, slower), and 24bpp
485
+ // (7% smaller) were all measured and all rejected.
486
+ //
487
+ // WHY THE SOURCE DC IS THE SCREEN AND NOT THE WINDOW. Get-WpmScreenshot has always captured the
488
+ // frame RECTANGLE OUT OF THE SCREEN, which is what makes its coordinates the same system a click
489
+ // uses and what makes an occluding window appear in the picture (honestly: the picture shows what a
490
+ // user would see). Capturing with GetWindowDC/PrintWindow would be a DIFFERENT product -- unoccluded,
491
+ // and no longer the screen the coordinates refer to. Equivalence was measured, not assumed: on a
492
+ // static scene the two paths give identical size, identical content, 0 max per-channel difference
493
+ // over 17388 sampled points, and byte-identical PNGs (findings 8.3). The one difference is reported:
494
+ // FromHbitmap yields Format32bppRgb where CopyFromScreen yields Format32bppArgb.
495
+ [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleDC(IntPtr dc);
496
+ [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr h);
497
+ [DllImport("user32.dll")] static extern int ReleaseDC(IntPtr h, IntPtr dc);
498
+ [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleBitmap(IntPtr dc, int w, int h);
499
+ [DllImport("gdi32.dll")] static extern IntPtr SelectObject(IntPtr dc, IntPtr obj);
500
+ [DllImport("gdi32.dll")] static extern bool BitBlt(IntPtr dc, int x, int y, int w, int h,
501
+ IntPtr srcDc, int srcX, int srcY, uint rop);
502
+ [DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr obj);
503
+ [DllImport("gdi32.dll")] static extern bool DeleteDC(IntPtr dc);
504
+ const uint SRCCOPY = 0x00CC0020;
505
+
506
+ /// <summary>
507
+ /// Capture a SCREEN rectangle into a new HBITMAP through BitBlt. Returns IntPtr.Zero with a named
508
+ /// reason on ANY failure -- the caller falls back to CopyFromScreen and reports which path it used.
509
+ /// Every GDI object created here is released on every path, including the partial ones: a leaked DC
510
+ /// in a long-lived worker is the kind of bug that shows up as "the app stopped painting" an hour in.
511
+ /// The returned handle is owned by the caller and must be passed to FreeHbitmap.
512
+ /// </summary>
513
+ public static IntPtr CaptureBitBlt(int x, int y, int w, int h, out string reason)
514
+ {
515
+ reason = "";
516
+ if (w <= 0 || h <= 0) { reason = "empty rectangle " + w + "x" + h; return IntPtr.Zero; }
517
+ IntPtr screen = GetDC(IntPtr.Zero);
518
+ if (screen == IntPtr.Zero) { reason = "GetDC(NULL) returned no screen DC"; return IntPtr.Zero; }
519
+ IntPtr mem = IntPtr.Zero, bmp = IntPtr.Zero, old = IntPtr.Zero;
520
+ try
521
+ {
522
+ mem = CreateCompatibleDC(screen);
523
+ if (mem == IntPtr.Zero) { reason = "CreateCompatibleDC failed"; return IntPtr.Zero; }
524
+ bmp = CreateCompatibleBitmap(screen, w, h);
525
+ if (bmp == IntPtr.Zero) { reason = "CreateCompatibleBitmap failed"; return IntPtr.Zero; }
526
+ old = SelectObject(mem, bmp);
527
+ if (!BitBlt(mem, 0, 0, w, h, screen, x, y, SRCCOPY)) { reason = "BitBlt refused"; DeleteObject(bmp); return IntPtr.Zero; }
528
+ return bmp;
529
+ }
530
+ finally
531
+ {
532
+ // `old` is restored before the memory DC goes away, and the screen DC is always released.
533
+ if (mem != IntPtr.Zero && old != IntPtr.Zero) SelectObject(mem, old);
534
+ if (mem != IntPtr.Zero) DeleteDC(mem);
535
+ ReleaseDC(IntPtr.Zero, screen);
536
+ }
537
+ }
538
+
539
+ /// <summary>Release an HBITMAP from CaptureBitBlt. Safe to call after FromHbitmap: that call copies
540
+ /// the bits into managed memory, so the native handle has nothing left to alias.</summary>
541
+ public static bool FreeHbitmap(IntPtr h) { return h != IntPtr.Zero && DeleteObject(h); }
386
542
  }
387
543
  '@
388
544
  }
@@ -861,6 +1017,42 @@ function Restore-WpmFocus {
861
1017
  return $res
862
1018
  }
863
1019
 
1020
+ # ==================================================================================================
1021
+ # 0.6.0 INPUT RELIABILITY: the read-back primitive, expressed as the fact it is and not as a verdict.
1022
+ # ==================================================================================================
1023
+
1024
+ function Read-WpmControlText {
1025
+ <#
1026
+ What the CONTROL says it holds, through WM_GETTEXT. Returns the control's own three numbers plus one
1027
+ derived flag, and the derivation is stated because it is the whole safety property of the feature:
1028
+
1029
+ exposesText = NOT (chars == 0 AND length > 0)
1030
+
1031
+ Measured 2026-11-23 on an ES_PASSWORD edit (findings 8.1): WM_GETTEXT returns an EMPTY string while
1032
+ WM_GETTEXTLENGTH returns the real length. That combination cannot mean "the field is empty" -- the
1033
+ control is reporting a length it refuses to spell out. Treating it as "empty, and therefore my write
1034
+ did not land" would be wrong twice over: it would report a mismatch that did not happen, and if the
1035
+ engine had tried to be cleverer and print what it read, a password field is exactly where printing a
1036
+ value stops being a diagnostic. So the read is reported as UNAVAILABLE, no text is carried anywhere,
1037
+ and the effect keeps the value the write itself earned.
1038
+ #>
1039
+ param([IntPtr]$Hwnd, [int]$TimeoutMs = 200)
1040
+ $length = -1
1041
+ try { $length = [WpmWin]::TextLength($Hwnd) } catch { }
1042
+ $r = [WpmWin]::ReadText($Hwnd, [uint32][Math]::Max(1, $TimeoutMs))
1043
+ $okRead = [bool]$r[0]
1044
+ $chars = [int]$r[1]
1045
+ $text = [string]$r[2]
1046
+ return @{
1047
+ ok = $okRead; chars = $chars; text = $text; length = $length
1048
+ exposesText = ($okRead -and -not ($chars -eq 0 -and $length -gt 0))
1049
+ truncated = ($okRead -and $length -gt 0 -and $chars -lt $length)
1050
+ reason = if (-not $okRead) { 'the timed read failed (target not answering within the budget)'
1051
+ } elseif ($chars -eq 0 -and $length -gt 0) { 'the control reports a length but no text (password-masked or equivalent)'
1052
+ } else { '' }
1053
+ }
1054
+ }
1055
+
864
1056
  # ==================================================================================================
865
1057
  # 0.5.0 READ PATHS: a frame the model can read, a picture whose coordinates are DATA, and a preview
866
1058
  # that answers in text. None of the three writes an input-queue entry or takes the focus.
@@ -1237,11 +1429,40 @@ function Get-WpmScreenshot {
1237
1429
 
1238
1430
  $bmp = $null
1239
1431
  $resized = $null
1432
+ $hbmp = [IntPtr]::Zero
1433
+ # THE PATH IS REPORTED, NEVER SWAPPED SILENTLY. Same discipline as `frame`: 'dwm' versus 'win32' is a
1434
+ # coordinate fact, and 'bitblt' versus 'gdiplus' is a content fact (a 32bppRgb surface instead of
1435
+ # 32bppArgb, and any difference in what an occluded window paints). A caller comparing two screenshots
1436
+ # has to be able to see that the producer changed, so the field is mandatory in the result.
1437
+ $captureBackend = 'gdiplus'
1438
+ $captureNote = ''
1240
1439
  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() }
1440
+ $capReason = ''
1441
+ try { $hbmp = [WpmWin]::CaptureBitBlt($frame.left, $frame.top, $w, $h, [ref]$capReason) }
1442
+ catch { $hbmp = [IntPtr]::Zero; $capReason = $_.Exception.Message }
1443
+ if ($hbmp -ne [IntPtr]::Zero) {
1444
+ try {
1445
+ $bmp = [System.Drawing.Image]::FromHbitmap($hbmp)
1446
+ $captureBackend = 'bitblt'
1447
+ } catch {
1448
+ # FromHbitmap can refuse (a format it cannot map). That is a capture failure, not a crash, and
1449
+ # the fallback below is the documented answer -- an exception here would turn a fast path into a
1450
+ # lost screenshot.
1451
+ $bmp = $null
1452
+ $capReason = 'FromHbitmap: ' + $_.Exception.Message
1453
+ } finally {
1454
+ [void][WpmWin]::FreeHbitmap($hbmp)
1455
+ $hbmp = [IntPtr]::Zero
1456
+ }
1457
+ }
1458
+ if (-not $bmp) {
1459
+ $captureNote = "bitblt-unavailable($capReason)"
1460
+ $bmp = New-Object System.Drawing.Bitmap($w, $h)
1461
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
1462
+ try { $g.CopyFromScreen($frame.left, $frame.top, 0, 0, (New-Object System.Drawing.Size($w, $h))) }
1463
+ finally { $g.Dispose() }
1464
+ $captureBackend = 'gdiplus'
1465
+ }
1245
1466
 
1246
1467
  $scale = 1.0
1247
1468
  $imgW = $w
@@ -1281,6 +1502,7 @@ function Get-WpmScreenshot {
1281
1502
  shotId = $shotId; file = $file; scale = $scale; identity = ($scale -eq 1.0)
1282
1503
  left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom
1283
1504
  imageWidth = [int]$imgW; imageHeight = [int]$imgH; frame = $frame.frame
1505
+ captureBackend = $captureBackend
1284
1506
  createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1285
1507
  }
1286
1508
  # Drop registry entries for shots the retention pass just removed.
@@ -1295,9 +1517,11 @@ function Get-WpmScreenshot {
1295
1517
  screenRect = @{ left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom }
1296
1518
  imageSize = @{ width = [int]$imgW; height = [int]$imgH }
1297
1519
  scale = $scale; identity = ($scale -eq 1.0); frame = $frame.frame
1520
+ captureBackend = $captureBackend; captureNote = $captureNote
1298
1521
  dpiAware = [bool]$script:WpmDpiAware; bytes = [long]$bytes; shotsKeep = $keepN
1299
1522
  capturedAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }
1300
1523
  } finally {
1524
+ if ($hbmp -ne [IntPtr]::Zero) { [void][WpmWin]::FreeHbitmap($hbmp) }
1301
1525
  if ($resized) { $resized.Dispose() }
1302
1526
  if ($bmp) { $bmp.Dispose() }
1303
1527
  }
@@ -141,10 +141,15 @@ while ($true) {
141
141
  Write-Response $id @{ id = $id; ok = $true; result = $r }
142
142
  }
143
143
  'type' {
144
+ # caretPosition is forwarded as given: the engine's ValidateSet is the single place that decides
145
+ # what values exist, and coercing an unknown value to 'idle' here would launder a caller bug into
146
+ # a silent behaviour change -- the write would go through at the wrong caret and look like a
147
+ # successful default. A bad value must fail loudly, at the one layer that owns the vocabulary.
144
148
  $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action type `
145
149
  -Text ([string](Get-Arg $req 'text' '')) -ElementName ([string](Get-Arg $req 'elementName' '')) `
146
150
  -Label ([int](Get-Arg $req 'label' 0)) `
147
151
  -SnapId ([string](Get-Arg $req 'snapId' '')) `
152
+ -CaretPosition ([string](Get-Arg $req 'caretPosition' 'idle')) `
148
153
  -Replace:([bool](Get-Arg $req 'replace' $false)) -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
149
154
  -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
150
155
  -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000)) `