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.
@@ -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,308 @@ 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
+
1056
+ # ==================================================================================================
1057
+ # 0.7.0 DESKTOP CAPABILITIES: launch, clipboard, window. Three actions the product could not do
1058
+ # before, and none of them is a door: they take no target's message queue, choose no channel, and
1059
+ # produce no proof window -- so they live BESIDE Invoke-WpmAction rather than inside it. The door
1060
+ # discipline (point ownership, the restore table, the proof window) is not widened by any of this.
1061
+ # ==================================================================================================
1062
+
1063
+ function Start-WpmApp {
1064
+ <#
1065
+ Launch a program. The HOST half is what decides whether this may run at all (appLaunchAllowed and
1066
+ the exact-name whitelist, lib/index.js); by the time this function is reached the decision is made,
1067
+ and this file reports only what the OS did.
1068
+
1069
+ Why the return is a pid and NOT a window handle: measured, `Process.Start` returns while the app is
1070
+ still loading and MainWindowHandle is 0 (1348 ms cold for notepad). A launch that claimed a window it
1071
+ does not have yet would send every follow-up action to hwnd=0, so the window is waited for
1072
+ separately, by Wait-WpmAppWindow, and reported honestly when it has not appeared.
1073
+ #>
1074
+ param([string]$Target, [string[]]$Arguments = @(), [string]$WorkingDirectory = '')
1075
+ if (-not $Target) { return @{ ok = $false; reason = 'launch needs a target: an executable path or a resolvable program name' } }
1076
+ try {
1077
+ $psi = New-Object System.Diagnostics.ProcessStartInfo
1078
+ $psi.FileName = $Target
1079
+ $psi.UseShellExecute = $true # the documented way a shell start resolves .exe/app paths
1080
+ if ($Arguments -and $Arguments.Count -gt 0) {
1081
+ $psi.Arguments = ($Arguments -join ' ')
1082
+ # The arguments are joined into one command line here. That is what the OS takes; the AUDIT logs
1083
+ # them as given, because R1 in the plan says the whitelist cannot make parameters safe, only the
1084
+ # record can make a bad one reviewable.
1085
+ }
1086
+ if ($WorkingDirectory) { $psi.WorkingDirectory = $WorkingDirectory }
1087
+ $p = [System.Diagnostics.Process]::Start($psi)
1088
+ if (-not $p) { return @{ ok = $false; reason = 'the OS started nothing for this target' } }
1089
+ return @{ ok = $true; pid = [int]$p.Id; name = [string]$p.ProcessName;
1090
+ fileName = [string]$p.MainModule.FileName; target = $Target }
1091
+ } catch {
1092
+ # Access denied, missing file, bad working directory. Reported as a failure of THIS action, with the
1093
+ # OS's own sentence attached -- not folded into an engine refusal code it does not own.
1094
+ return @{ ok = $false; reason = 'start failed: ' + $_.Exception.Message }
1095
+ }
1096
+ }
1097
+
1098
+ function Wait-WpmAppWindow {
1099
+ <#
1100
+ Poll for the process's first real top-level window, up to `WaitMs`. Two answers, both honest:
1101
+ found -> { ok=true; hwnd=...; waitedMs }
1102
+ not yet -> { ok=true; hwnd=''; detail='window-not-yet'; waitedMs } -- NOT a failure. The program
1103
+ did start; pretending otherwise would make a slow launch look like a dead one, and
1104
+ pretending the window exists would send the next action to nothing.
1105
+ #>
1106
+ param([int]$ProcessId, [int]$WaitMs = 3000)
1107
+ $budget = [Math]::Max(0, [Math]::Min(30000, $WaitMs))
1108
+ $at = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1109
+ $deadline = $at + $budget
1110
+ while ($true) {
1111
+ $p = $null
1112
+ try { $p = Get-Process -Id $ProcessId -ErrorAction Stop } catch { $p = $null }
1113
+ if (-not $p) {
1114
+ return @{ ok = $false; hwnd = ''; reason = "process $ProcessId is gone"; waitedMs = [int]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $at) }
1115
+ }
1116
+ $h = [long]$p.MainWindowHandle
1117
+ # Refresh: MainWindowHandle is cached on the Process object, and the whole reason this loop exists
1118
+ # is that the first read is 0.
1119
+ if ($h -le 0) { try { $p.Refresh() } catch { }; $h = [long]$p.MainWindowHandle }
1120
+ if ($h -gt 0) {
1121
+ return @{ ok = $true; hwnd = $h.ToString(); waitedMs = [int]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $at);
1122
+ title = [string]$p.MainWindowTitle }
1123
+ }
1124
+ $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1125
+ if ($now -ge $deadline) {
1126
+ return @{ ok = $true; hwnd = ''; detail = 'window-not-yet'; waitedMs = [int]($now - $at);
1127
+ note = "the process is running but has published no top-level window within $budget ms; keep polling, or address it by pid"
1128
+ }
1129
+ }
1130
+ Start-Sleep -Milliseconds 50
1131
+ }
1132
+ }
1133
+
1134
+ function Get-WpmClipboard {
1135
+ <#
1136
+ Read the SYSTEM clipboard. R8 in the plan is the reason this is written carefully: what is in the
1137
+ clipboard may be a password or a token the owner copied seconds ago. So:
1138
+ * text is capped at 64 KB and a longer payload is TRUNCATED AND SAYING so (`truncated=true`),
1139
+ rather than either silently cutting or dumping the whole thing into a model's context;
1140
+ * the audit records op/format/length, never the content (lib/index.js owns the audit line);
1141
+ * a non-text, non-image clipboard answers `unsupported-format` with the format names it did find
1142
+ -- an empty success would be indistinguishable from "the clipboard is empty".
1143
+ Requires STA, which the worker already runs under (`powershell.exe -STA`); measured in findings 5.2.
1144
+ #>
1145
+ param([string]$Format = 'text', [int]$MaxChars = 65536)
1146
+ Add-Type -AssemblyName System.Windows.Forms
1147
+ $fmt = if ($Format -eq 'image') { 'image' } else { 'text' }
1148
+ try {
1149
+ if ($fmt -eq 'text') {
1150
+ if (-not [System.Windows.Forms.Clipboard]::ContainsText()) {
1151
+ return @{ ok = $false; reason = 'the clipboard holds no text'; formats = (Get-WpmClipboardFormats) }
1152
+ }
1153
+ $t = [System.Windows.Forms.Clipboard]::GetText()
1154
+ if ($null -eq $t) { $t = '' }
1155
+ $cap = [Math]::Max(1, $MaxChars)
1156
+ $truncated = $t.Length -gt $cap
1157
+ return @{ ok = $true; format = 'text'; chars = [int]$t.Length; text = $(if ($truncated) { $t.Substring(0, $cap) } else { $t }); truncated = $truncated }
1158
+ }
1159
+ if (-not [System.Windows.Forms.Clipboard]::ContainsImage()) {
1160
+ return @{ ok = $false; reason = 'the clipboard holds no image'; formats = (Get-WpmClipboardFormats) }
1161
+ }
1162
+ $img = [System.Windows.Forms.Clipboard]::GetImage()
1163
+ if (-not $img) { return @{ ok = $false; reason = 'the clipboard claimed an image and returned none' } }
1164
+ $dir = Join-Path (Get-WpmDataDir) 'clipboard'
1165
+ if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
1166
+ $id = 'clip-' + [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1167
+ $file = Join-Path $dir ($id + '.png')
1168
+ $img.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
1169
+ $w = [int]$img.Width; $h = [int]$img.Height
1170
+ $img.Dispose()
1171
+ return @{ ok = $true; format = 'image'; file = $file; clipId = $id; width = $w; height = $h }
1172
+ } catch {
1173
+ # The clipboard is owned by whatever app last touched it and can be locked; that is a transient
1174
+ # state of the desktop, reported as a failure of this action with the OS's sentence attached.
1175
+ return @{ ok = $false; reason = 'clipboard read failed: ' + $_.Exception.Message }
1176
+ }
1177
+ }
1178
+
1179
+ function Get-WpmClipboardFormats {
1180
+ # The format NAMES, so a refusal can say what IS there instead of only what is not.
1181
+ try {
1182
+ $names = @([System.Windows.Forms.Clipboard]::GetDataObject().GetFormats())
1183
+ return @($names | ForEach-Object { [string]$_ } | Select-Object -First 12)
1184
+ } catch { return @() }
1185
+ }
1186
+
1187
+ function Set-WpmClipboard {
1188
+ <#
1189
+ Write the clipboard. `shotId` is accepted for an image so a screenshot can be pushed into the
1190
+ clipboard without the caller ever handling the pixels -- the same "the engine does the arithmetic"
1191
+ stance as space:"image" for a click. SetDataObject($true) flushes the data so it survives this
1192
+ process, which is the documented difference between a clipboard write and a clipboard promise.
1193
+ #>
1194
+ param([string]$Format = 'text', [string]$Text = '', [string]$ShotId = '')
1195
+ Add-Type -AssemblyName System.Windows.Forms
1196
+ Add-Type -AssemblyName System.Drawing
1197
+ $fmt = if ($Format -eq 'image') { 'image' } else { 'text' }
1198
+ try {
1199
+ if ($fmt -eq 'text') {
1200
+ if (-not $Text) { return @{ ok = $false; reason = 'clipboard write needs text; an empty write is indistinguishable from a clipboard the owner already cleared' } }
1201
+ [System.Windows.Forms.Clipboard]::Clear()
1202
+ # SetDataObject($value, $true), NOT Flush(): `Flush` is a .NET Core API and this engine's floor is
1203
+ # Windows PowerShell 5.1 (= .NET Framework 4.x), where the call does not exist. The first version
1204
+ # of this branch threw "Clipboard does not contain a method named 'Flush'" -- a method that exists
1205
+ # in the documentation people read and not in the runtime the product targets. The second argument
1206
+ # is what makes the data survive this process, which is the whole behaviour being asked for.
1207
+ [System.Windows.Forms.Clipboard]::SetDataObject($Text, $true)
1208
+ $back = ''
1209
+ try { $back = [string][System.Windows.Forms.Clipboard]::GetText() } catch { }
1210
+ return @{ ok = $true; format = 'text'; chars = [int]$Text.Length; readbackChars = [int]$back.Length;
1211
+ readbackMatches = ($back -ceq $Text) }
1212
+ }
1213
+ if (-not $ShotId) { return @{ ok = $false; reason = 'clipboard image write needs a shotId (the screenshot to put there) or a file' } }
1214
+ if (-not $script:WpmShots.ContainsKey($ShotId)) {
1215
+ return @{ ok = $false; stale = $true; reason = "shotId '$ShotId' is not a screenshot this worker still holds" }
1216
+ }
1217
+ $file = [string]$script:WpmShots[$ShotId].file
1218
+ if (-not (Test-Path -LiteralPath $file)) { return @{ ok = $false; reason = "the shot's PNG is no longer on disk: $file" } }
1219
+ # The shot's own recorded size travels along, so the engine can compare what the clipboard reports
1220
+ # against what was asked. Without it the image write has no prediction to check and would have to
1221
+ # claim success from "the clipboard now holds an image", which is a weaker statement than the text
1222
+ # path can make.
1223
+ $askedW = [int]$script:WpmShots[$ShotId].imageWidth
1224
+ $askedH = [int]$script:WpmShots[$ShotId].imageHeight
1225
+ $bmp = [System.Drawing.Image]::FromFile($file)
1226
+ try {
1227
+ [System.Windows.Forms.Clipboard]::Clear()
1228
+ [System.Windows.Forms.Clipboard]::SetDataObject($bmp, $true)
1229
+ } finally { $bmp.Dispose() }
1230
+ $ok = $false; $w = 0; $h = 0
1231
+ try {
1232
+ if ([System.Windows.Forms.Clipboard]::ContainsImage()) {
1233
+ $img = [System.Windows.Forms.Clipboard]::GetImage()
1234
+ $w = [int]$img.Width; $h = [int]$img.Height; $img.Dispose(); $ok = $true
1235
+ }
1236
+ } catch { }
1237
+ return @{ ok = $ok; format = 'image'; shotId = $ShotId; file = $file; width = $askedW; height = $askedH;
1238
+ readbackWidth = $w; readbackHeight = $h }
1239
+ } catch {
1240
+ return @{ ok = $false; reason = 'clipboard write failed: ' + $_.Exception.Message }
1241
+ }
1242
+ }
1243
+
1244
+ function Invoke-WpmWindowOp {
1245
+ <#
1246
+ One op on ONE window named by hwnd, and the verification is the OS's answer about the window, not
1247
+ the return value of the call. That distinction is the whole point of this function: ShowWindow and
1248
+ SetWindowPos return booleans about the CALL, and every action in this product that reported a call
1249
+ instead of a state has eventually turned out to be the lying kind.
1250
+ minimize -> IsIconic afterwards (must be true)
1251
+ restore -> IsIconic afterwards (must be false)
1252
+ move -> GetWindowRect afterwards (left/top must match what was asked)
1253
+ resize -> GetWindowRect afterwards (width/height must match, within 2px)
1254
+ topmost -> the WS_EX_TOPMOST bit, read back
1255
+ `topmost` is the promotion of `MakeTopmostNoActivate`, which shipped as a TEST-SUPPORT primitive
1256
+ (its comment says a model should not be able to topmost-raise arbitrary windows). 0.7.0 revisits
1257
+ that: it is now reachable, it never activates the window, and the result still reports the ex-style
1258
+ it read back -- see findings §5 for the reasoning that changed.
1259
+
1260
+ WHAT THIS FUNCTION DELIBERATELY DOES NOT REPORT: the foreground. `restore` activates by definition
1261
+ (SW_RESTORE is documented to bring the window up), so "did the owner lose focus" is a question about
1262
+ the moment around this call rather than about the state after it -- and engine.ps1 reads
1263
+ GetForegroundWindow on both sides and reports the pair, where this function can only see one.
1264
+ #>
1265
+ param([IntPtr]$Hwnd, [string]$Op, [int]$X = 0, [int]$Y = 0, [int]$Width = 0, [int]$Height = 0)
1266
+ if (-not $Hwnd -or -not [WpmWin]::IsWindow($Hwnd)) {
1267
+ return @{ ok = $false; refusal = 'no_hwnd'; reason = 'the hwnd does not identify a live window' }
1268
+ }
1269
+ $before = New-Object 'WpmWin+RECT'
1270
+ [void][WpmWin]::GetWindowRect($Hwnd, [ref]$before)
1271
+ switch ($Op) {
1272
+ 'minimize' {
1273
+ [void][WpmWin]::ShowWindow($Hwnd, [WpmWin]::SW_MINIMIZE)
1274
+ $iconic = [WpmWin]::IsIconic($Hwnd)
1275
+ return @{ ok = $iconic; op = $Op; iconic = $iconic;
1276
+ reason = $(if ($iconic) { '' } else { 'ShowWindow(SW_MINIMIZE) returned and the window is still not iconic' }) }
1277
+ }
1278
+ 'restore' {
1279
+ [void][WpmWin]::ShowWindow($Hwnd, [WpmWin]::SW_RESTORE)
1280
+ $iconic = [WpmWin]::IsIconic($Hwnd)
1281
+ return @{ ok = (-not $iconic); op = $Op; iconic = $iconic;
1282
+ reason = $(if ($iconic) { 'the window is still iconic after SW_RESTORE' } else { '' }) }
1283
+ }
1284
+ 'move' {
1285
+ # SWP_NOSIZE(1) | SWP_NOZORDER(4) | SWP_NOACTIVATE(10): a window move that stole the foreground
1286
+ # would be exactly the disturbance the rest of this product refuses to cause.
1287
+ $ok = [WpmWin]::SetWindowPos($Hwnd, [IntPtr]::Zero, $X, $Y, 0, 0, ([uint32]1 -bor [uint32]4 -bor [uint32]16))
1288
+ $r = New-Object 'WpmWin+RECT'
1289
+ [void][WpmWin]::GetWindowRect($Hwnd, [ref]$r)
1290
+ $moved = ($r.Left -eq $X -and $r.Top -eq $Y)
1291
+ return @{ ok = ($ok -and $moved); op = $Op; called = "$X,$Y"; rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)";
1292
+ before = "$($before.Left),$($before.Top),$($before.Right),$($before.Bottom)";
1293
+ reason = $(if (-not $ok) { 'SetWindowPos was refused' } elseif (-not $moved) { 'the call returned and the window did not land where it was told' } else { '' }) }
1294
+ }
1295
+ 'resize' {
1296
+ $w = [Math]::Max(1, $Width); $h = [Math]::Max(1, $Height)
1297
+ $ok = [WpmWin]::SetWindowPos($Hwnd, [IntPtr]::Zero, 0, 0, $w, $h, ([uint32]2 -bor [uint32]4 -bor [uint32]16))
1298
+ $r = New-Object 'WpmWin+RECT'
1299
+ [void][WpmWin]::GetWindowRect($Hwnd, [ref]$r)
1300
+ $cw = $r.Right - $r.Left; $ch = $r.Bottom - $r.Top
1301
+ # +-2 px: the window may clamp a size to its own minimum, and a 1px difference between the frame
1302
+ # the app asks for and the rect Windows reports is normal, not a lie worth failing the action over.
1303
+ $fits = ([Math]::Abs($cw - $w) -le 2) -and ([Math]::Abs($ch - $h) -le 2)
1304
+ return @{ ok = ($ok -and $fits); op = $Op; asked = "${w}x${h}"; size = "${cw}x${ch}";
1305
+ rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)";
1306
+ reason = $(if (-not $ok) { 'SetWindowPos was refused' } elseif (-not $fits) { 'the window came back a different size than was asked (a clamp, not a no-op)' } else { '' }) }
1307
+ }
1308
+ 'topmost' {
1309
+ $ok = [WpmWin]::MakeTopmostNoActivate($Hwnd)
1310
+ $ex = [WpmWin]::GetWindowLong($Hwnd, [WpmWin]::GWL_EXSTYLE)
1311
+ $isTop = ($ex -band [WpmWin]::WS_EX_TOPMOST) -ne 0
1312
+ return @{ ok = ($ok -and $isTop); op = $Op; exStyle = ('0x' + $ex.ToString('X'));
1313
+ topmost = $isTop; activated = 'no'
1314
+ reason = $(if (-not $isTop) { 'the WS_EX_TOPMOST bit is not set on the window after the call' } else { '' }) }
1315
+ }
1316
+ default {
1317
+ return @{ ok = $false; op = $Op; reason = "unknown window op '$Op'" }
1318
+ }
1319
+ }
1320
+ }
1321
+
864
1322
  # ==================================================================================================
865
1323
  # 0.5.0 READ PATHS: a frame the model can read, a picture whose coordinates are DATA, and a preview
866
1324
  # that answers in text. None of the three writes an input-queue entry or takes the focus.
@@ -1237,11 +1695,40 @@ function Get-WpmScreenshot {
1237
1695
 
1238
1696
  $bmp = $null
1239
1697
  $resized = $null
1698
+ $hbmp = [IntPtr]::Zero
1699
+ # THE PATH IS REPORTED, NEVER SWAPPED SILENTLY. Same discipline as `frame`: 'dwm' versus 'win32' is a
1700
+ # coordinate fact, and 'bitblt' versus 'gdiplus' is a content fact (a 32bppRgb surface instead of
1701
+ # 32bppArgb, and any difference in what an occluded window paints). A caller comparing two screenshots
1702
+ # has to be able to see that the producer changed, so the field is mandatory in the result.
1703
+ $captureBackend = 'gdiplus'
1704
+ $captureNote = ''
1240
1705
  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() }
1706
+ $capReason = ''
1707
+ try { $hbmp = [WpmWin]::CaptureBitBlt($frame.left, $frame.top, $w, $h, [ref]$capReason) }
1708
+ catch { $hbmp = [IntPtr]::Zero; $capReason = $_.Exception.Message }
1709
+ if ($hbmp -ne [IntPtr]::Zero) {
1710
+ try {
1711
+ $bmp = [System.Drawing.Image]::FromHbitmap($hbmp)
1712
+ $captureBackend = 'bitblt'
1713
+ } catch {
1714
+ # FromHbitmap can refuse (a format it cannot map). That is a capture failure, not a crash, and
1715
+ # the fallback below is the documented answer -- an exception here would turn a fast path into a
1716
+ # lost screenshot.
1717
+ $bmp = $null
1718
+ $capReason = 'FromHbitmap: ' + $_.Exception.Message
1719
+ } finally {
1720
+ [void][WpmWin]::FreeHbitmap($hbmp)
1721
+ $hbmp = [IntPtr]::Zero
1722
+ }
1723
+ }
1724
+ if (-not $bmp) {
1725
+ $captureNote = "bitblt-unavailable($capReason)"
1726
+ $bmp = New-Object System.Drawing.Bitmap($w, $h)
1727
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
1728
+ try { $g.CopyFromScreen($frame.left, $frame.top, 0, 0, (New-Object System.Drawing.Size($w, $h))) }
1729
+ finally { $g.Dispose() }
1730
+ $captureBackend = 'gdiplus'
1731
+ }
1245
1732
 
1246
1733
  $scale = 1.0
1247
1734
  $imgW = $w
@@ -1281,6 +1768,7 @@ function Get-WpmScreenshot {
1281
1768
  shotId = $shotId; file = $file; scale = $scale; identity = ($scale -eq 1.0)
1282
1769
  left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom
1283
1770
  imageWidth = [int]$imgW; imageHeight = [int]$imgH; frame = $frame.frame
1771
+ captureBackend = $captureBackend
1284
1772
  createdAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1285
1773
  }
1286
1774
  # Drop registry entries for shots the retention pass just removed.
@@ -1295,9 +1783,11 @@ function Get-WpmScreenshot {
1295
1783
  screenRect = @{ left = [int]$frame.left; top = [int]$frame.top; right = [int]$frame.right; bottom = [int]$frame.bottom }
1296
1784
  imageSize = @{ width = [int]$imgW; height = [int]$imgH }
1297
1785
  scale = $scale; identity = ($scale -eq 1.0); frame = $frame.frame
1786
+ captureBackend = $captureBackend; captureNote = $captureNote
1298
1787
  dpiAware = [bool]$script:WpmDpiAware; bytes = [long]$bytes; shotsKeep = $keepN
1299
1788
  capturedAtUtcMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }
1300
1789
  } finally {
1790
+ if ($hbmp -ne [IntPtr]::Zero) { [void][WpmWin]::FreeHbitmap($hbmp) }
1301
1791
  if ($resized) { $resized.Dispose() }
1302
1792
  if ($bmp) { $bmp.Dispose() }
1303
1793
  }
@@ -129,6 +129,10 @@ while ($true) {
129
129
  $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action click `
130
130
  -X ([int](Get-Arg $req 'x' -1)) -Y ([int](Get-Arg $req 'y' -1)) `
131
131
  -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
132
+ -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
133
+ -RequiredTier ([string](Get-Arg $req 'requiredTier' 'quiet')) `
134
+ -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
135
+ -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
132
136
  -Space ([string](Get-Arg $req 'space' 'screen')) `
133
137
  -ShotId ([string](Get-Arg $req 'shotId' '')) `
134
138
  -Label ([int](Get-Arg $req 'label' 0)) `
@@ -141,10 +145,19 @@ while ($true) {
141
145
  Write-Response $id @{ id = $id; ok = $true; result = $r }
142
146
  }
143
147
  'type' {
148
+ # caretPosition is forwarded as given: the engine's ValidateSet is the single place that decides
149
+ # what values exist, and coercing an unknown value to 'idle' here would launder a caller bug into
150
+ # a silent behaviour change -- the write would go through at the wrong caret and look like a
151
+ # successful default. A bad value must fail loudly, at the one layer that owns the vocabulary.
144
152
  $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action type `
145
153
  -Text ([string](Get-Arg $req 'text' '')) -ElementName ([string](Get-Arg $req 'elementName' '')) `
146
154
  -Label ([int](Get-Arg $req 'label' 0)) `
147
155
  -SnapId ([string](Get-Arg $req 'snapId' '')) `
156
+ -CaretPosition ([string](Get-Arg $req 'caretPosition' 'idle')) `
157
+ -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
158
+ -RequiredTier ([string](Get-Arg $req 'requiredTier' 'quiet')) `
159
+ -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
160
+ -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
148
161
  -Replace:([bool](Get-Arg $req 'replace' $false)) -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
149
162
  -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
150
163
  -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000)) `
@@ -159,6 +172,10 @@ while ($true) {
159
172
  -Label ([int](Get-Arg $req 'label' 0)) `
160
173
  -SnapId ([string](Get-Arg $req 'snapId' '')) `
161
174
  -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
175
+ -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
176
+ -RequiredTier ([string](Get-Arg $req 'requiredTier' 'quiet')) `
177
+ -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
178
+ -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
162
179
  -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
163
180
  -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000))
164
181
  Write-Response $id @{ id = $id; ok = $true; result = $r }
@@ -188,6 +205,46 @@ while ($true) {
188
205
  -X ([int](Get-Arg $req 'x' -1)) -Y ([int](Get-Arg $req 'y' -1))
189
206
  Write-Response $id @{ id = $id; ok = $true; result = $r }
190
207
  }
208
+ # ---- 0.7.0 desktop actions ---------------------------------------------------------------
209
+ # These three are dispatched to Invoke-WpmDesktopAction rather than Invoke-WpmAction: they choose
210
+ # no channel and cost no tier, so the door table has nothing to say about them. The SETTINGS gates
211
+ # (appLaunchAllowed and its whitelist, the policy tier, the idle check) live in the host half and
212
+ # have already been applied -- a request that reached here was authorised, exactly as with
213
+ # takeover:true above, and the engine still re-checks what only it can see (a live hwnd, the real
214
+ # window state after the call).
215
+ 'launch' {
216
+ $argv = Get-Arg $req 'args' @()
217
+ if ($null -eq $argv) { $argv = @() }
218
+ $allow = Get-Arg $req 'allowList' @()
219
+ if ($null -eq $allow) { $allow = @() }
220
+ $r = Invoke-WpmDesktopAction -Action launch `
221
+ -Target ([string](Get-Arg $req 'target' '')) `
222
+ -Arguments $argv `
223
+ -WaitMs ([int](Get-Arg $req 'waitMs' 3000)) `
224
+ -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
225
+ -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
226
+ -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
227
+ -AppLaunchAllowed:([bool](Get-Arg $req 'launchAllowed' $false)) `
228
+ -AppLaunchAllow ([string[]]@($allow))
229
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
230
+ }
231
+ 'clipboard' {
232
+ $r = Invoke-WpmDesktopAction -Action clipboard `
233
+ -Op ([string](Get-Arg $req 'op' 'read')) `
234
+ -Format ([string](Get-Arg $req 'format' 'text')) `
235
+ -Text ([string](Get-Arg $req 'text' '')) `
236
+ -ShotId ([string](Get-Arg $req 'shotId' '')) `
237
+ -MaxChars ([int](Get-Arg $req 'maxChars' 65536))
238
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
239
+ }
240
+ 'window' {
241
+ $r = Invoke-WpmDesktopAction -Action window `
242
+ -Hwnd ([string](Get-Arg $req 'hwnd' '')) `
243
+ -Op ([string](Get-Arg $req 'op' '')) `
244
+ -X ([int](Get-Arg $req 'x' 0)) -Y ([int](Get-Arg $req 'y' 0)) `
245
+ -Width ([int](Get-Arg $req 'width' 0)) -Height ([int](Get-Arg $req 'height' 0))
246
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
247
+ }
191
248
  'hud' {
192
249
  # Product surface for tests and for the owner: start/stop the HUD on its own, so its window
193
250
  # properties can be measured without an action in flight (test/hud-test.ps1).