dsh-windows-parallel-mcp 0.8.2 → 0.9.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.de.md +444 -419
  2. package/CHANGELOG.es.md +444 -419
  3. package/CHANGELOG.fr.md +444 -419
  4. package/CHANGELOG.it.md +444 -419
  5. package/CHANGELOG.ja.md +444 -419
  6. package/CHANGELOG.ko.md +444 -419
  7. package/CHANGELOG.md +965 -940
  8. package/CHANGELOG.pt.md +444 -419
  9. package/CHANGELOG.ru.md +444 -419
  10. package/CHANGELOG.zh.md +444 -419
  11. package/INSTALL.de.md +126 -126
  12. package/INSTALL.es.md +126 -126
  13. package/INSTALL.fr.md +126 -126
  14. package/INSTALL.it.md +126 -126
  15. package/INSTALL.ja.md +126 -126
  16. package/INSTALL.ko.md +126 -126
  17. package/INSTALL.md +122 -122
  18. package/INSTALL.pt.md +126 -126
  19. package/INSTALL.ru.md +126 -126
  20. package/INSTALL.zh.md +126 -126
  21. package/README.de.md +684 -684
  22. package/README.es.md +684 -684
  23. package/README.fr.md +684 -684
  24. package/README.it.md +684 -684
  25. package/README.ja.md +684 -684
  26. package/README.ko.md +684 -684
  27. package/README.md +680 -680
  28. package/README.pt.md +684 -684
  29. package/README.ru.md +684 -684
  30. package/README.zh.md +684 -684
  31. package/cordis.patch.yml +15 -15
  32. package/docs/refusals.md +90 -90
  33. package/docs/takeover.md +128 -128
  34. package/dsh.plugin.json +18 -18
  35. package/lib/config.js +275 -275
  36. package/lib/engine.js +252 -252
  37. package/lib/host-tools.js +365 -338
  38. package/lib/index.js +1275 -1249
  39. package/lib/peers-schemastery.js +23 -23
  40. package/lib/peers-tools.js +15 -15
  41. package/lib/proof-window.mjs +427 -427
  42. package/package.json +122 -122
  43. package/server.json +110 -110
  44. package/src/engine/decide.ps1 +356 -356
  45. package/src/engine/engine.ps1 +1208 -1208
  46. package/src/engine/hud.ps1 +411 -411
  47. package/src/engine/input-inject.ps1 +176 -176
  48. package/src/engine/overlay.ps1 +389 -389
  49. package/src/engine/takeover.ps1 +144 -144
  50. package/src/engine/win.ps1 +1881 -1881
  51. package/src/engine/worker.ps1 +310 -310
  52. package/src/schema/tools.json +533 -533
  53. package/types/index.d.ts +190 -187
@@ -1,411 +1,411 @@
1
- # hud.ps1 -- the R3 safety surface: a three-phase window that says what the engine is doing with the
2
- # owner's mouse/keyboard/focus, offers a real stop button, and owns the global abort chord. (spec.md §2)
3
- #
4
- # WHY THIS IS A HARD PREREQUISITE RATHER THAN A NICETY. R3 lets the engine move the real cursor and type
5
- # into the foreground window. Both are invisible cost the owner pays; a takeover without a surface would
6
- # mean the pointer moves and text appears with no way to tell "an agent did that" from "the machine did
7
- # something". So: no HUD, no takeover -- enforced twice (engine refuses before any primitive call;
8
- # scripts/check-takeover-path.mjs G3 asserts the call order is structural).
9
- #
10
- # ARCHITECTURE IS BORROWED, DELIBERATELY: an STA runspace + WPF + a DispatcherTimer pump that reads and
11
- # writes ONLY [WpmCtl] fields. overlay.ps1 measured why (overlay.ps1:163-176): a cross-thread
12
- # Dispatcher.Invoke of a PowerShell scriptblock cost 1818ms and sometimes never returned, because the
13
- # pump thread is already inside Dispatcher.Run(). Three volatile fields cost nothing.
14
- #
15
- # TWO MEASURED DETAILS THAT CHANGED THE DESIGN (findings §G6, scripts/probe-hittest-children.ps1):
16
- # * the HwndSource hook DOES receive WM_NCHITTEST but its return value does not reach hit-testing
17
- # (empty point still answered HTCLIENT). So click-through is done with a WNDPROC subclass instead:
18
- # HTTRANSPARENT outside the button's rect, CallWindowProc inside it. Measured after the change:
19
- # empty point -> -1 and WindowFromPoint no longer returns this window; button point -> 1.
20
- # * WS_EX_NOACTIVATE + ShowActivated=false is what keeps the HUD from stealing the foreground while
21
- # the button stays clickable (measured: GetForegroundWindow unchanged across Show()).
22
- #
23
- # NO WATCHDOG, NO AUTO-CLOSE LOOP. The engine owns the lifecycle: it starts the HUD for one action and
24
- # stops it in its own finally block. A window that decided on its own to shut down mid-action would be a
25
- # second owner of the abort decision, which is exactly the bug the pause-flag comments elsewhere warn
26
- # about.
27
-
28
- Set-StrictMode -Version 2.0
29
-
30
- if (-not ('WpmCtl' -as [type])) {
31
- . (Join-Path $PSScriptRoot 'win.ps1')
32
- }
33
-
34
- if (-not (Get-Variable -Name WpmHudRunspace -Scope Script -ErrorAction SilentlyContinue)) {
35
- $script:WpmHudRunspace = $null
36
- $script:WpmHudPowerShell = $null
37
- $script:WpmHudHandle = $null
38
- }
39
- $script:WpmHudHotkeyId = 0xB002
40
-
41
- # Ctrl+Alt+Q is the PAUSE key and is already owned on this desktop; the abort chord needs its own space.
42
- # The candidate table exists for the same reason overlay.ps1 has one: whatever registers is reported, so
43
- # the owner reads the key that actually works instead of the one the docs promise.
44
- $script:WpmAbortChords = @(
45
- @{ label = 'Ctrl+Alt+X'; mods = 0x0003; vk = 0x58 },
46
- @{ label = 'Ctrl+Alt+Z'; mods = 0x0003; vk = 0x5A },
47
- @{ label = 'Ctrl+Alt+C'; mods = 0x0003; vk = 0x43 },
48
- @{ label = 'Ctrl+Alt+V'; mods = 0x0003; vk = 0x56 },
49
- @{ label = 'Ctrl+Alt+B'; mods = 0x0003; vk = 0x42 },
50
- @{ label = 'Ctrl+Alt+N'; mods = 0x0003; vk = 0x4E },
51
- @{ label = 'Ctrl+Shift+X'; mods = 0x0006; vk = 0x58 },
52
- @{ label = 'Ctrl+Alt+Shift+X'; mods = 0x0007; vk = 0x58 }
53
- )
54
-
55
- if (-not ('WpmHud' -as [type])) {
56
- Add-Type -TypeDefinition @'
57
- using System;
58
- using System.Runtime.InteropServices;
59
-
60
- public static class WpmHud
61
- {
62
- [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
63
- [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
64
- public delegate IntPtr WndProc(IntPtr h, uint m, IntPtr w, IntPtr l);
65
-
66
- [DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
67
- [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
68
- [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
69
- [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")] public static extern IntPtr SetWindowLongPtr(IntPtr h, int idx, IntPtr proc);
70
- [DllImport("user32.dll")] public static extern IntPtr CallWindowProc(IntPtr prev, IntPtr h, uint m, IntPtr w, IntPtr l);
71
- [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr h, uint msg, IntPtr w, IntPtr l);
72
-
73
- public const uint WM_NCHITTEST = 0x0084;
74
- public const int HTTRANSPARENT = -1;
75
- public const int SM_CXSCREEN = 0;
76
- public const int SM_CYSCREEN = 1;
77
-
78
- static IntPtr prev = IntPtr.Zero;
79
- static RECT zone;
80
- static WndProc keepAlive;
81
- public static int HitCount = 0;
82
-
83
- // Click-through outside the control zone, WPF's own hit-testing inside it. Installed AFTER Show()
84
- // so the button's physical rect is already known.
85
- public static bool InstallHitZone(IntPtr h, int left, int top, int right, int bottom) {
86
- zone = new RECT(); zone.Left = left; zone.Top = top; zone.Right = right; zone.Bottom = bottom;
87
- keepAlive = new WndProc(Proc);
88
- prev = SetWindowLongPtr(h, -4, Marshal.GetFunctionPointerForDelegate(keepAlive));
89
- return prev != IntPtr.Zero;
90
- }
91
- static IntPtr Proc(IntPtr h, uint m, IntPtr w, IntPtr l) {
92
- if (m == WM_NCHITTEST) {
93
- HitCount++;
94
- long packed = (long)l;
95
- int x = (short)(packed & 0xFFFF);
96
- int y = (short)((packed >> 16) & 0xFFFF);
97
- if (!(x >= zone.Left && x <= zone.Right && y >= zone.Top && y <= zone.Bottom)) return new IntPtr(HTTRANSPARENT);
98
- }
99
- return CallWindowProc(prev, h, m, w, l);
100
- }
101
- public static IntPtr HitTest(IntPtr h, int x, int y) {
102
- IntPtr lp = (IntPtr)((y << 16) | (x & 0xFFFF));
103
- return SendMessage(h, WM_NCHITTEST, IntPtr.Zero, lp);
104
- }
105
- public static IntPtr WindowAt(int x, int y) { POINT p; p.X = x; p.Y = y; return WindowFromPoint(p); }
106
- }
107
- '@
108
- }
109
-
110
- $script:WpmHudBody = @'
111
- param([string]$Action, [int]$MaxMs, [int]$ArmMs, [int]$HotkeyId, [object[]]$Chords)
112
- try {
113
- Add-Type -AssemblyName PresentationFramework
114
- Add-Type -AssemblyName PresentationCore
115
- Add-Type -AssemblyName WindowsBase
116
-
117
- $win = [System.Windows.Window]::new()
118
- $win.Title = 'WpmHud'
119
- $win.WindowStyle = [System.Windows.WindowStyle]::None
120
- $win.ResizeMode = [System.Windows.ResizeMode]::NoResize
121
- $win.ShowActivated = $false # WPF half of NOACTIVATE: Show() must not steal the foreground
122
- $win.ShowInTaskbar = $false
123
- $win.Topmost = $true
124
- $win.Width = 470.0
125
- $win.Height = 104.0
126
- $win.Left = -3000.0
127
- $win.Top = -3000.0
128
- $win.WindowStartupLocation = [System.Windows.WindowStartupLocation]::Manual
129
- # The surface colour is a PHASE SIGNAL, not decoration (see the pump). It starts on the arming tint so a
130
- # window that somehow never gets a pump tick is still telling the truth about what it is waiting for.
131
- $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(58, 44, 12))
132
- $win.Opacity = 0.94
133
-
134
- # THREE COLUMNS: a 5px accent bar, the text, the button. The bar is the second channel for the phase
135
- # colour, because a tinted background alone is easy to miss when the window is 470x104 at the screen edge
136
- # and the owner is looking at the target window rather than at the HUD.
137
- $grid = [System.Windows.Controls.Grid]::new()
138
- $grid.Margin = [System.Windows.Thickness]::new(0.0, 0.0, 14.0, 0.0)
139
- $colBar = [System.Windows.Controls.ColumnDefinition]::new()
140
- $colBar.Width = [System.Windows.GridLength]::new(5.0)
141
- $colA = [System.Windows.Controls.ColumnDefinition]::new()
142
- $colA.Width = [System.Windows.GridLength]::new(1.0, [System.Windows.GridUnitType]::Star)
143
- $colB = [System.Windows.Controls.ColumnDefinition]::new()
144
- $colB.Width = [System.Windows.GridLength]::Auto
145
- [void]$grid.ColumnDefinitions.Add($colBar)
146
- [void]$grid.ColumnDefinitions.Add($colA)
147
- [void]$grid.ColumnDefinitions.Add($colB)
148
-
149
- $bar = [System.Windows.Controls.Border]::new()
150
- $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(240, 173, 24))
151
- [System.Windows.Controls.Grid]::SetColumn($bar, 0)
152
- [void]$grid.Children.Add($bar)
153
-
154
- $tb = [System.Windows.Controls.TextBlock]::new()
155
- $tb.TextWrapping = [System.Windows.TextWrapping]::Wrap
156
- $tb.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
157
- $tb.Foreground = [System.Windows.Media.Brushes]::White
158
- $tb.FontSize = 13.0
159
- $tb.Text = 'WPM'
160
- $tb.Margin = [System.Windows.Thickness]::new(14.0, 10.0, 10.0, 10.0)
161
- [System.Windows.Controls.Grid]::SetColumn($tb, 1)
162
- [void]$grid.Children.Add($tb)
163
-
164
- $btn = [System.Windows.Controls.Button]::new()
165
- $btn.Content = '中止'
166
- $btn.Width = 92.0
167
- $btn.Height = 40.0
168
- $btn.FontSize = 13.0
169
- $btn.Focusable = $false
170
- $btn.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
171
- $btn.Margin = [System.Windows.Thickness]::new(0.0, 0.0, 0.0, 0.0)
172
- [System.Windows.Controls.Grid]::SetColumn($btn, 2)
173
- [void]$grid.Children.Add($btn)
174
-
175
- $win.Content = $grid
176
- $win.Show()
177
- $hwnd = (New-Object System.Windows.Interop.WindowInteropHelper($win)).Handle
178
- [WpmCtl]::HudHwnd = [int64]$hwnd
179
-
180
- # Topmost + no-activate, explicitly (the measured promise is the ex-style read-back, not the look).
181
- $bits = [WpmWin]::WS_EX_TOPMOST -bor [WpmWin]::WS_EX_NOACTIVATE
182
- [void][WpmWin]::AddExStyles($hwnd, $bits)
183
-
184
- # Physical placement bottom-right. WPF's Left/Top are device independent and did not agree with this
185
- # desktop at 150% (overlay.ps1 recorded marker at (303,263) for a target of (470,410)), so placement
186
- # is SetWindowPos in physical pixels after reading the real rect once.
187
- $rc0 = New-Object 'WpmWin+RECT'
188
- [void][WpmWin]::GetWindowRect([IntPtr]$hwnd, [ref]$rc0)
189
- $pw = [int]($rc0.Right - $rc0.Left); $ph = [int]($rc0.Bottom - $rc0.Top)
190
- if ($pw -le 0) { $pw = 470 }
191
- if ($ph -le 0) { $ph = 104 }
192
- $screenW = [WpmHud]::GetSystemMetrics([WpmHud]::SM_CXSCREEN)
193
- $screenH = [WpmHud]::GetSystemMetrics([WpmHud]::SM_CYSCREEN)
194
- [void][WpmWin]::MoveNoActivate([IntPtr]$hwnd, ($screenW - $pw - 24), ($screenH - $ph - 64), $pw, $ph)
195
-
196
- # Click-through outside the button. Measured in scripts/probe-hittest-children.ps1.
197
- $bp = $btn.PointToScreen([System.Windows.Point]::new(0.0, 0.0))
198
- $bw = [int]$btn.ActualWidth; $bh = [int]$btn.ActualHeight
199
- if ($bw -le 0) { $bw = 92 }
200
- if ($bh -le 0) { $bh = 40 }
201
- $hitOk = [WpmHud]::InstallHitZone([IntPtr]$hwnd, [int]$bp.X, [int]$bp.Y, [int]($bp.X + $bw), [int]($bp.Y + $bh))
202
-
203
- $hkOk = $false
204
- $hkLabel = ''
205
- foreach ($c in $Chords) {
206
- if ([WpmWin]::RegisterHotKey($hwnd, $HotkeyId, [uint32]$c.mods, [uint32]$c.vk)) {
207
- $hkOk = $true; $hkLabel = [string]$c.label; break
208
- }
209
- }
210
- [WpmCtl]::AbortChordOk = [bool]$hkOk
211
- [WpmCtl]::AbortChordLabel = $hkLabel
212
-
213
- $src = [System.Windows.Interop.HwndSource]::FromHwnd($hwnd)
214
- if ($src) {
215
- $hkId = $HotkeyId
216
- $hook = [System.Windows.Interop.HwndSourceHook] {
217
- param($h, $m, $wp, $lp, [ref]$handled)
218
- if ($m -eq [WpmWin]::WM_HOTKEY -and [int]$wp -eq $hkId) {
219
- [WpmCtl]::TakeoverAbort = $true
220
- $handled.Value = $true
221
- return [IntPtr]::Zero
222
- }
223
- $handled.Value = $false
224
- return [IntPtr]::Zero
225
- }
226
- [void]$src.AddHook($hook)
227
- }
228
-
229
- $btn.Add_Click({ [WpmCtl]::TakeoverAbort = $true })
230
-
231
- # THE PUMP. 50ms, reads fields, writes pixels. Nothing is marshalled from another thread.
232
- $lastPhase = ''
233
- $pump = [System.Windows.Threading.DispatcherTimer]::new()
234
- $pump.Interval = [TimeSpan]::FromMilliseconds(50)
235
- $pump.Add_Tick({
236
- $phase = [string][WpmCtl]::HudPhase
237
- $act = [string][WpmCtl]::HudAction
238
- $elapsed = [int][WpmCtl]::HudElapsedMs
239
- $max = [int][WpmCtl]::HudMaxMs
240
- $injected = [int][WpmCtl]::InjectedChars
241
- $chord = [string][WpmCtl]::AbortChordLabel
242
- $secs = [Math]::Round($elapsed / 1000.0, 1)
243
- $maxSecs = [Math]::Round($max / 1000.0, 1)
244
- # THE THREE PHASES MUST BE TELLABLE APART FROM ACROSS THE ROOM, not just by reading the words.
245
- # The owner's attention is on the target window while an agent borrows their pointer, so the phase is
246
- # encoded TWICE: the whole surface tint, and a 5px accent bar (a tint alone is easy to miss at the
247
- # screen edge). Colours are chosen for meaning rather than prettiness -- amber = not yet, red = now,
248
- # green = over -- and the accent stays the most saturated element so it reads at a glance.
249
- if ($phase -eq 'arming') {
250
- # AMBER: about to borrow. Nothing has moved yet; this is the cancellable window.
251
- $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(58, 44, 12))
252
- $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(240, 173, 24))
253
- $tb.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(255, 216, 138))
254
- $chordLine = if ($chord) { '中断键 ' + $chord + ' 可取消' } else { '中断键不可用,请点按钮' }
255
- $tb.Text = '即将使用你的鼠标/键盘/焦点 · ' + $act + [char]0x000A + $chordLine
256
- $btn.Content = '取消'
257
- $btn.IsEnabled = $true
258
- } elseif ($phase -eq 'active') {
259
- # RED: the pointer/focus are actually held. The one state that costs the owner something right now.
260
- $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(58, 18, 18))
261
- $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(232, 64, 64))
262
- $tb.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(255, 190, 190))
263
- $tb.Text = '占用中 · ' + $act + [char]0x000A + ('已用 ' + $secs.ToString() + 's / 上限 ' + $maxSecs.ToString() + 's') + [char]0x000A + ('已注入 ' + $injected.ToString() + ' 字')
264
- $btn.Content = '停止'
265
- $btn.IsEnabled = $true
266
- } else {
267
- # GREEN: returned. A completed state that says "nothing is being held" without needing to be read.
268
- $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(14, 46, 30))
269
- $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(52, 199, 123))
270
- $tb.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(178, 240, 205))
271
- $tb.Text = '已归还:光标已复位'
272
- $btn.Content = '完成'
273
- $btn.IsEnabled = $false
274
- }
275
- $lastPhase = $phase
276
- })
277
- $pump.Start()
278
-
279
- [WpmCtl]::Dispatcher = [System.Windows.Threading.Dispatcher]::CurrentDispatcher
280
- [WpmCtl]::Window = $win
281
- [WpmCtl]::Timer = $pump
282
- [WpmCtl]::HudOn = $true
283
- [WpmCtl]::Reason = if ($hitOk) { '' } else { 'WNDPROC subclass failed; the HUD is hit-testable everywhere (degraded)' }
284
-
285
- [System.Windows.Threading.Dispatcher]::Run()
286
- } catch {
287
- [WpmCtl]::Reason = $_.Exception.Message
288
- } finally {
289
- [WpmCtl]::HudOn = $false
290
- [WpmCtl]::HudPhase = ''
291
- [WpmCtl]::HudHwnd = [int64]0
292
- [WpmCtl]::AbortChordOk = $false
293
- [WpmCtl]::AbortChordLabel = ''
294
- [WpmCtl]::Window = $null
295
- [WpmCtl]::Timer = $null
296
- [WpmCtl]::Dispatcher = $null
297
- }
298
- '@
299
-
300
- function Start-WpmHud {
301
- param([string]$Action = 'action', [int]$MaxMs = 10000, [int]$ArmMs = 800, [int]$WaitMs = 3000)
302
- if ($script:WpmHudRunspace -and $script:WpmHudRunspace.RunspaceStateInfo.State -eq 'Opened') {
303
- return @{ started = $false; ready = [bool][WpmCtl]::HudOn; reason = 'already running' }
304
- }
305
- [WpmCtl]::Reason = ''
306
- [WpmCtl]::HudPhase = 'arming'
307
- [WpmCtl]::HudAction = $Action
308
- [WpmCtl]::HudMaxMs = $MaxMs
309
- [WpmCtl]::HudElapsedMs = 0
310
- [WpmCtl]::InjectedChars = 0
311
- $iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault2()
312
- $rs = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($iss)
313
- $rs.ApartmentState = [System.Threading.ApartmentState]::STA
314
- $rs.ThreadOptions = [System.Management.Automation.Runspaces.PSThreadOptions]::Default
315
- $rs.Open()
316
- if ($rs.RunspaceStateInfo.State -ne 'Opened') {
317
- return @{ started = $false; ready = $false; reason = "runspace failed to open: $($rs.RunspaceStateInfo)" }
318
- }
319
- $ps = [PowerShell]::Create()
320
- $ps.Runspace = $rs
321
- [void]$ps.AddScript($script:WpmHudBody).AddArgument($Action).AddArgument($MaxMs).AddArgument($ArmMs).AddArgument($script:WpmHudHotkeyId).AddArgument($script:WpmAbortChords)
322
- $script:WpmHudHandle = $ps.BeginInvoke()
323
- $script:WpmHudRunspace = $rs
324
- $script:WpmHudPowerShell = $ps
325
- $st = Get-WpmHudState -WaitMs $WaitMs
326
- return @{ started = [bool]$st.running; ready = [bool]$st.running; reason = [string]$st.reason; state = $st }
327
- }
328
-
329
- function Get-WpmHudState {
330
- # Wait for HudOn -- the same flag the readiness verdict uses. A budget that expired mid-init is
331
- # 'starting', not 'dead': the caller can tell a slow start from a body that threw (overlay.ps1:250-262).
332
- param([int]$WaitMs = 2500)
333
- $deadline = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + $WaitMs
334
- while ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -lt $deadline -and -not [WpmCtl]::HudOn) {
335
- Start-Sleep -Milliseconds 50
336
- }
337
- $hwnd = [WpmCtl]::HudHwnd
338
- $ex = 0
339
- if ($hwnd -ne 0) { $ex = [WpmWin]::GetWindowLong([IntPtr]$hwnd, [WpmWin]::GWL_EXSTYLE) }
340
- return @{
341
- running = [bool][WpmCtl]::HudOn
342
- starting = (-not [WpmCtl]::HudOn) -and ($script:WpmHudHandle -ne $null) -and (-not $script:WpmHudHandle.AsyncWaitHandle.WaitOne(0))
343
- hwnd = [string]$hwnd
344
- phase = [string][WpmCtl]::HudPhase
345
- abortChordRegistered = [bool][WpmCtl]::AbortChordOk
346
- abortChordLabel = [string][WpmCtl]::AbortChordLabel
347
- injectedChars = [int][WpmCtl]::InjectedChars
348
- abortRequested = [bool][WpmCtl]::TakeoverAbort
349
- reason = [string][WpmCtl]::Reason
350
- exStyle = '0x{0:X8}' -f $ex
351
- topmost = [bool]($ex -band [WpmWin]::WS_EX_TOPMOST)
352
- noActivate = [bool]($ex -band [WpmWin]::WS_EX_NOACTIVATE)
353
- transparent = [bool]($ex -band [WpmWin]::WS_EX_TRANSPARENT)
354
- foregroundNow = [WpmWin]::Fg()
355
- }
356
- }
357
-
358
- function Test-WpmHudReady {
359
- return [bool]([WpmCtl]::HudOn -and [WpmCtl]::HudHwnd -ne 0)
360
- }
361
-
362
- function Set-WpmHudPhase {
363
- # A REQUEST, not an action: three field writes, applied by the HUD's own pump. Called on every phase
364
- # change and every 50ms while active (for the elapsed clock).
365
- param([ValidateSet('arming', 'active', 'done')][string]$Phase, [string]$Action = '', [int]$MaxMs = -1, [int]$ElapsedMs = -1)
366
- [WpmCtl]::HudPhase = $Phase
367
- if ($Action) { [WpmCtl]::HudAction = $Action }
368
- if ($MaxMs -ge 0) { [WpmCtl]::HudMaxMs = $MaxMs }
369
- if ($ElapsedMs -ge 0) { [WpmCtl]::HudElapsedMs = $ElapsedMs }
370
- return @{ phase = $Phase; hudOn = [bool][WpmCtl]::HudOn }
371
- }
372
-
373
- function Stop-WpmHud {
374
- param([int]$WaitMs = 2500)
375
- $hwnd = [WpmCtl]::HudHwnd
376
- $posted = $false
377
- if ($hwnd -ne 0) {
378
- try { $posted = [bool][WpmWin]::PostMessageW([IntPtr]$hwnd, [uint32][WpmWin]::WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero) } catch { $posted = $false }
379
- }
380
- $completed = $false
381
- if ($script:WpmHudHandle) {
382
- $spin = 0
383
- while (-not $script:WpmHudHandle.IsCompleted -and $spin -lt 6) { Start-Sleep -Milliseconds 50; $spin++ }
384
- $completed = [bool]$script:WpmHudHandle.IsCompleted
385
- }
386
- if (-not $completed) {
387
- $d = [WpmCtl]::Dispatcher
388
- if ($d) { try { [void]$d.InvokeShutdown() } catch { } }
389
- $spin = 0
390
- while ($script:WpmHudHandle -and -not $script:WpmHudHandle.IsCompleted -and $spin -lt 20) { Start-Sleep -Milliseconds 25; $spin++ }
391
- $completed = [bool]($script:WpmHudHandle -and $script:WpmHudHandle.IsCompleted)
392
- }
393
- if ($script:WpmHudHandle) { try { $script:WpmHudPowerShell.EndInvoke($script:WpmHudHandle) | Out-Null } catch { } }
394
- if ($script:WpmHudPowerShell) { try { $script:WpmHudPowerShell.Dispose() } catch { }; $script:WpmHudPowerShell = $null }
395
- if ($script:WpmHudRunspace) { try { $script:WpmHudRunspace.Dispose() } catch { }; $script:WpmHudRunspace = $null }
396
- $script:WpmHudHandle = $null
397
- $st = Get-WpmHudState -WaitMs 150
398
- if (-not $completed) {
399
- [WpmCtl]::HudOn = $false
400
- [WpmCtl]::HudPhase = ''
401
- [WpmCtl]::HudHwnd = [int64]0
402
- [WpmCtl]::AbortChordOk = $false
403
- [WpmCtl]::AbortChordLabel = ''
404
- [WpmCtl]::Window = $null
405
- [WpmCtl]::Timer = $null
406
- [WpmCtl]::Dispatcher = $null
407
- $st = Get-WpmHudState -WaitMs 100
408
- $st.reason = 'hud pipeline did not end within the bound; state cleared by Stop-WpmHud'
409
- }
410
- return @{ stopped = $true; completed = $completed; posted = $posted; state = $st }
411
- }
1
+ # hud.ps1 -- the R3 safety surface: a three-phase window that says what the engine is doing with the
2
+ # owner's mouse/keyboard/focus, offers a real stop button, and owns the global abort chord. (spec.md §2)
3
+ #
4
+ # WHY THIS IS A HARD PREREQUISITE RATHER THAN A NICETY. R3 lets the engine move the real cursor and type
5
+ # into the foreground window. Both are invisible cost the owner pays; a takeover without a surface would
6
+ # mean the pointer moves and text appears with no way to tell "an agent did that" from "the machine did
7
+ # something". So: no HUD, no takeover -- enforced twice (engine refuses before any primitive call;
8
+ # scripts/check-takeover-path.mjs G3 asserts the call order is structural).
9
+ #
10
+ # ARCHITECTURE IS BORROWED, DELIBERATELY: an STA runspace + WPF + a DispatcherTimer pump that reads and
11
+ # writes ONLY [WpmCtl] fields. overlay.ps1 measured why (overlay.ps1:163-176): a cross-thread
12
+ # Dispatcher.Invoke of a PowerShell scriptblock cost 1818ms and sometimes never returned, because the
13
+ # pump thread is already inside Dispatcher.Run(). Three volatile fields cost nothing.
14
+ #
15
+ # TWO MEASURED DETAILS THAT CHANGED THE DESIGN (findings §G6, scripts/probe-hittest-children.ps1):
16
+ # * the HwndSource hook DOES receive WM_NCHITTEST but its return value does not reach hit-testing
17
+ # (empty point still answered HTCLIENT). So click-through is done with a WNDPROC subclass instead:
18
+ # HTTRANSPARENT outside the button's rect, CallWindowProc inside it. Measured after the change:
19
+ # empty point -> -1 and WindowFromPoint no longer returns this window; button point -> 1.
20
+ # * WS_EX_NOACTIVATE + ShowActivated=false is what keeps the HUD from stealing the foreground while
21
+ # the button stays clickable (measured: GetForegroundWindow unchanged across Show()).
22
+ #
23
+ # NO WATCHDOG, NO AUTO-CLOSE LOOP. The engine owns the lifecycle: it starts the HUD for one action and
24
+ # stops it in its own finally block. A window that decided on its own to shut down mid-action would be a
25
+ # second owner of the abort decision, which is exactly the bug the pause-flag comments elsewhere warn
26
+ # about.
27
+
28
+ Set-StrictMode -Version 2.0
29
+
30
+ if (-not ('WpmCtl' -as [type])) {
31
+ . (Join-Path $PSScriptRoot 'win.ps1')
32
+ }
33
+
34
+ if (-not (Get-Variable -Name WpmHudRunspace -Scope Script -ErrorAction SilentlyContinue)) {
35
+ $script:WpmHudRunspace = $null
36
+ $script:WpmHudPowerShell = $null
37
+ $script:WpmHudHandle = $null
38
+ }
39
+ $script:WpmHudHotkeyId = 0xB002
40
+
41
+ # Ctrl+Alt+Q is the PAUSE key and is already owned on this desktop; the abort chord needs its own space.
42
+ # The candidate table exists for the same reason overlay.ps1 has one: whatever registers is reported, so
43
+ # the owner reads the key that actually works instead of the one the docs promise.
44
+ $script:WpmAbortChords = @(
45
+ @{ label = 'Ctrl+Alt+X'; mods = 0x0003; vk = 0x58 },
46
+ @{ label = 'Ctrl+Alt+Z'; mods = 0x0003; vk = 0x5A },
47
+ @{ label = 'Ctrl+Alt+C'; mods = 0x0003; vk = 0x43 },
48
+ @{ label = 'Ctrl+Alt+V'; mods = 0x0003; vk = 0x56 },
49
+ @{ label = 'Ctrl+Alt+B'; mods = 0x0003; vk = 0x42 },
50
+ @{ label = 'Ctrl+Alt+N'; mods = 0x0003; vk = 0x4E },
51
+ @{ label = 'Ctrl+Shift+X'; mods = 0x0006; vk = 0x58 },
52
+ @{ label = 'Ctrl+Alt+Shift+X'; mods = 0x0007; vk = 0x58 }
53
+ )
54
+
55
+ if (-not ('WpmHud' -as [type])) {
56
+ Add-Type -TypeDefinition @'
57
+ using System;
58
+ using System.Runtime.InteropServices;
59
+
60
+ public static class WpmHud
61
+ {
62
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
63
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
64
+ public delegate IntPtr WndProc(IntPtr h, uint m, IntPtr w, IntPtr l);
65
+
66
+ [DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
67
+ [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
68
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
69
+ [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")] public static extern IntPtr SetWindowLongPtr(IntPtr h, int idx, IntPtr proc);
70
+ [DllImport("user32.dll")] public static extern IntPtr CallWindowProc(IntPtr prev, IntPtr h, uint m, IntPtr w, IntPtr l);
71
+ [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr h, uint msg, IntPtr w, IntPtr l);
72
+
73
+ public const uint WM_NCHITTEST = 0x0084;
74
+ public const int HTTRANSPARENT = -1;
75
+ public const int SM_CXSCREEN = 0;
76
+ public const int SM_CYSCREEN = 1;
77
+
78
+ static IntPtr prev = IntPtr.Zero;
79
+ static RECT zone;
80
+ static WndProc keepAlive;
81
+ public static int HitCount = 0;
82
+
83
+ // Click-through outside the control zone, WPF's own hit-testing inside it. Installed AFTER Show()
84
+ // so the button's physical rect is already known.
85
+ public static bool InstallHitZone(IntPtr h, int left, int top, int right, int bottom) {
86
+ zone = new RECT(); zone.Left = left; zone.Top = top; zone.Right = right; zone.Bottom = bottom;
87
+ keepAlive = new WndProc(Proc);
88
+ prev = SetWindowLongPtr(h, -4, Marshal.GetFunctionPointerForDelegate(keepAlive));
89
+ return prev != IntPtr.Zero;
90
+ }
91
+ static IntPtr Proc(IntPtr h, uint m, IntPtr w, IntPtr l) {
92
+ if (m == WM_NCHITTEST) {
93
+ HitCount++;
94
+ long packed = (long)l;
95
+ int x = (short)(packed & 0xFFFF);
96
+ int y = (short)((packed >> 16) & 0xFFFF);
97
+ if (!(x >= zone.Left && x <= zone.Right && y >= zone.Top && y <= zone.Bottom)) return new IntPtr(HTTRANSPARENT);
98
+ }
99
+ return CallWindowProc(prev, h, m, w, l);
100
+ }
101
+ public static IntPtr HitTest(IntPtr h, int x, int y) {
102
+ IntPtr lp = (IntPtr)((y << 16) | (x & 0xFFFF));
103
+ return SendMessage(h, WM_NCHITTEST, IntPtr.Zero, lp);
104
+ }
105
+ public static IntPtr WindowAt(int x, int y) { POINT p; p.X = x; p.Y = y; return WindowFromPoint(p); }
106
+ }
107
+ '@
108
+ }
109
+
110
+ $script:WpmHudBody = @'
111
+ param([string]$Action, [int]$MaxMs, [int]$ArmMs, [int]$HotkeyId, [object[]]$Chords)
112
+ try {
113
+ Add-Type -AssemblyName PresentationFramework
114
+ Add-Type -AssemblyName PresentationCore
115
+ Add-Type -AssemblyName WindowsBase
116
+
117
+ $win = [System.Windows.Window]::new()
118
+ $win.Title = 'WpmHud'
119
+ $win.WindowStyle = [System.Windows.WindowStyle]::None
120
+ $win.ResizeMode = [System.Windows.ResizeMode]::NoResize
121
+ $win.ShowActivated = $false # WPF half of NOACTIVATE: Show() must not steal the foreground
122
+ $win.ShowInTaskbar = $false
123
+ $win.Topmost = $true
124
+ $win.Width = 470.0
125
+ $win.Height = 104.0
126
+ $win.Left = -3000.0
127
+ $win.Top = -3000.0
128
+ $win.WindowStartupLocation = [System.Windows.WindowStartupLocation]::Manual
129
+ # The surface colour is a PHASE SIGNAL, not decoration (see the pump). It starts on the arming tint so a
130
+ # window that somehow never gets a pump tick is still telling the truth about what it is waiting for.
131
+ $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(58, 44, 12))
132
+ $win.Opacity = 0.94
133
+
134
+ # THREE COLUMNS: a 5px accent bar, the text, the button. The bar is the second channel for the phase
135
+ # colour, because a tinted background alone is easy to miss when the window is 470x104 at the screen edge
136
+ # and the owner is looking at the target window rather than at the HUD.
137
+ $grid = [System.Windows.Controls.Grid]::new()
138
+ $grid.Margin = [System.Windows.Thickness]::new(0.0, 0.0, 14.0, 0.0)
139
+ $colBar = [System.Windows.Controls.ColumnDefinition]::new()
140
+ $colBar.Width = [System.Windows.GridLength]::new(5.0)
141
+ $colA = [System.Windows.Controls.ColumnDefinition]::new()
142
+ $colA.Width = [System.Windows.GridLength]::new(1.0, [System.Windows.GridUnitType]::Star)
143
+ $colB = [System.Windows.Controls.ColumnDefinition]::new()
144
+ $colB.Width = [System.Windows.GridLength]::Auto
145
+ [void]$grid.ColumnDefinitions.Add($colBar)
146
+ [void]$grid.ColumnDefinitions.Add($colA)
147
+ [void]$grid.ColumnDefinitions.Add($colB)
148
+
149
+ $bar = [System.Windows.Controls.Border]::new()
150
+ $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(240, 173, 24))
151
+ [System.Windows.Controls.Grid]::SetColumn($bar, 0)
152
+ [void]$grid.Children.Add($bar)
153
+
154
+ $tb = [System.Windows.Controls.TextBlock]::new()
155
+ $tb.TextWrapping = [System.Windows.TextWrapping]::Wrap
156
+ $tb.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
157
+ $tb.Foreground = [System.Windows.Media.Brushes]::White
158
+ $tb.FontSize = 13.0
159
+ $tb.Text = 'WPM'
160
+ $tb.Margin = [System.Windows.Thickness]::new(14.0, 10.0, 10.0, 10.0)
161
+ [System.Windows.Controls.Grid]::SetColumn($tb, 1)
162
+ [void]$grid.Children.Add($tb)
163
+
164
+ $btn = [System.Windows.Controls.Button]::new()
165
+ $btn.Content = '中止'
166
+ $btn.Width = 92.0
167
+ $btn.Height = 40.0
168
+ $btn.FontSize = 13.0
169
+ $btn.Focusable = $false
170
+ $btn.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
171
+ $btn.Margin = [System.Windows.Thickness]::new(0.0, 0.0, 0.0, 0.0)
172
+ [System.Windows.Controls.Grid]::SetColumn($btn, 2)
173
+ [void]$grid.Children.Add($btn)
174
+
175
+ $win.Content = $grid
176
+ $win.Show()
177
+ $hwnd = (New-Object System.Windows.Interop.WindowInteropHelper($win)).Handle
178
+ [WpmCtl]::HudHwnd = [int64]$hwnd
179
+
180
+ # Topmost + no-activate, explicitly (the measured promise is the ex-style read-back, not the look).
181
+ $bits = [WpmWin]::WS_EX_TOPMOST -bor [WpmWin]::WS_EX_NOACTIVATE
182
+ [void][WpmWin]::AddExStyles($hwnd, $bits)
183
+
184
+ # Physical placement bottom-right. WPF's Left/Top are device independent and did not agree with this
185
+ # desktop at 150% (overlay.ps1 recorded marker at (303,263) for a target of (470,410)), so placement
186
+ # is SetWindowPos in physical pixels after reading the real rect once.
187
+ $rc0 = New-Object 'WpmWin+RECT'
188
+ [void][WpmWin]::GetWindowRect([IntPtr]$hwnd, [ref]$rc0)
189
+ $pw = [int]($rc0.Right - $rc0.Left); $ph = [int]($rc0.Bottom - $rc0.Top)
190
+ if ($pw -le 0) { $pw = 470 }
191
+ if ($ph -le 0) { $ph = 104 }
192
+ $screenW = [WpmHud]::GetSystemMetrics([WpmHud]::SM_CXSCREEN)
193
+ $screenH = [WpmHud]::GetSystemMetrics([WpmHud]::SM_CYSCREEN)
194
+ [void][WpmWin]::MoveNoActivate([IntPtr]$hwnd, ($screenW - $pw - 24), ($screenH - $ph - 64), $pw, $ph)
195
+
196
+ # Click-through outside the button. Measured in scripts/probe-hittest-children.ps1.
197
+ $bp = $btn.PointToScreen([System.Windows.Point]::new(0.0, 0.0))
198
+ $bw = [int]$btn.ActualWidth; $bh = [int]$btn.ActualHeight
199
+ if ($bw -le 0) { $bw = 92 }
200
+ if ($bh -le 0) { $bh = 40 }
201
+ $hitOk = [WpmHud]::InstallHitZone([IntPtr]$hwnd, [int]$bp.X, [int]$bp.Y, [int]($bp.X + $bw), [int]($bp.Y + $bh))
202
+
203
+ $hkOk = $false
204
+ $hkLabel = ''
205
+ foreach ($c in $Chords) {
206
+ if ([WpmWin]::RegisterHotKey($hwnd, $HotkeyId, [uint32]$c.mods, [uint32]$c.vk)) {
207
+ $hkOk = $true; $hkLabel = [string]$c.label; break
208
+ }
209
+ }
210
+ [WpmCtl]::AbortChordOk = [bool]$hkOk
211
+ [WpmCtl]::AbortChordLabel = $hkLabel
212
+
213
+ $src = [System.Windows.Interop.HwndSource]::FromHwnd($hwnd)
214
+ if ($src) {
215
+ $hkId = $HotkeyId
216
+ $hook = [System.Windows.Interop.HwndSourceHook] {
217
+ param($h, $m, $wp, $lp, [ref]$handled)
218
+ if ($m -eq [WpmWin]::WM_HOTKEY -and [int]$wp -eq $hkId) {
219
+ [WpmCtl]::TakeoverAbort = $true
220
+ $handled.Value = $true
221
+ return [IntPtr]::Zero
222
+ }
223
+ $handled.Value = $false
224
+ return [IntPtr]::Zero
225
+ }
226
+ [void]$src.AddHook($hook)
227
+ }
228
+
229
+ $btn.Add_Click({ [WpmCtl]::TakeoverAbort = $true })
230
+
231
+ # THE PUMP. 50ms, reads fields, writes pixels. Nothing is marshalled from another thread.
232
+ $lastPhase = ''
233
+ $pump = [System.Windows.Threading.DispatcherTimer]::new()
234
+ $pump.Interval = [TimeSpan]::FromMilliseconds(50)
235
+ $pump.Add_Tick({
236
+ $phase = [string][WpmCtl]::HudPhase
237
+ $act = [string][WpmCtl]::HudAction
238
+ $elapsed = [int][WpmCtl]::HudElapsedMs
239
+ $max = [int][WpmCtl]::HudMaxMs
240
+ $injected = [int][WpmCtl]::InjectedChars
241
+ $chord = [string][WpmCtl]::AbortChordLabel
242
+ $secs = [Math]::Round($elapsed / 1000.0, 1)
243
+ $maxSecs = [Math]::Round($max / 1000.0, 1)
244
+ # THE THREE PHASES MUST BE TELLABLE APART FROM ACROSS THE ROOM, not just by reading the words.
245
+ # The owner's attention is on the target window while an agent borrows their pointer, so the phase is
246
+ # encoded TWICE: the whole surface tint, and a 5px accent bar (a tint alone is easy to miss at the
247
+ # screen edge). Colours are chosen for meaning rather than prettiness -- amber = not yet, red = now,
248
+ # green = over -- and the accent stays the most saturated element so it reads at a glance.
249
+ if ($phase -eq 'arming') {
250
+ # AMBER: about to borrow. Nothing has moved yet; this is the cancellable window.
251
+ $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(58, 44, 12))
252
+ $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(240, 173, 24))
253
+ $tb.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(255, 216, 138))
254
+ $chordLine = if ($chord) { '中断键 ' + $chord + ' 可取消' } else { '中断键不可用,请点按钮' }
255
+ $tb.Text = '即将使用你的鼠标/键盘/焦点 · ' + $act + [char]0x000A + $chordLine
256
+ $btn.Content = '取消'
257
+ $btn.IsEnabled = $true
258
+ } elseif ($phase -eq 'active') {
259
+ # RED: the pointer/focus are actually held. The one state that costs the owner something right now.
260
+ $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(58, 18, 18))
261
+ $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(232, 64, 64))
262
+ $tb.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(255, 190, 190))
263
+ $tb.Text = '占用中 · ' + $act + [char]0x000A + ('已用 ' + $secs.ToString() + 's / 上限 ' + $maxSecs.ToString() + 's') + [char]0x000A + ('已注入 ' + $injected.ToString() + ' 字')
264
+ $btn.Content = '停止'
265
+ $btn.IsEnabled = $true
266
+ } else {
267
+ # GREEN: returned. A completed state that says "nothing is being held" without needing to be read.
268
+ $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(14, 46, 30))
269
+ $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(52, 199, 123))
270
+ $tb.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(178, 240, 205))
271
+ $tb.Text = '已归还:光标已复位'
272
+ $btn.Content = '完成'
273
+ $btn.IsEnabled = $false
274
+ }
275
+ $lastPhase = $phase
276
+ })
277
+ $pump.Start()
278
+
279
+ [WpmCtl]::Dispatcher = [System.Windows.Threading.Dispatcher]::CurrentDispatcher
280
+ [WpmCtl]::Window = $win
281
+ [WpmCtl]::Timer = $pump
282
+ [WpmCtl]::HudOn = $true
283
+ [WpmCtl]::Reason = if ($hitOk) { '' } else { 'WNDPROC subclass failed; the HUD is hit-testable everywhere (degraded)' }
284
+
285
+ [System.Windows.Threading.Dispatcher]::Run()
286
+ } catch {
287
+ [WpmCtl]::Reason = $_.Exception.Message
288
+ } finally {
289
+ [WpmCtl]::HudOn = $false
290
+ [WpmCtl]::HudPhase = ''
291
+ [WpmCtl]::HudHwnd = [int64]0
292
+ [WpmCtl]::AbortChordOk = $false
293
+ [WpmCtl]::AbortChordLabel = ''
294
+ [WpmCtl]::Window = $null
295
+ [WpmCtl]::Timer = $null
296
+ [WpmCtl]::Dispatcher = $null
297
+ }
298
+ '@
299
+
300
+ function Start-WpmHud {
301
+ param([string]$Action = 'action', [int]$MaxMs = 10000, [int]$ArmMs = 800, [int]$WaitMs = 3000)
302
+ if ($script:WpmHudRunspace -and $script:WpmHudRunspace.RunspaceStateInfo.State -eq 'Opened') {
303
+ return @{ started = $false; ready = [bool][WpmCtl]::HudOn; reason = 'already running' }
304
+ }
305
+ [WpmCtl]::Reason = ''
306
+ [WpmCtl]::HudPhase = 'arming'
307
+ [WpmCtl]::HudAction = $Action
308
+ [WpmCtl]::HudMaxMs = $MaxMs
309
+ [WpmCtl]::HudElapsedMs = 0
310
+ [WpmCtl]::InjectedChars = 0
311
+ $iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault2()
312
+ $rs = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($iss)
313
+ $rs.ApartmentState = [System.Threading.ApartmentState]::STA
314
+ $rs.ThreadOptions = [System.Management.Automation.Runspaces.PSThreadOptions]::Default
315
+ $rs.Open()
316
+ if ($rs.RunspaceStateInfo.State -ne 'Opened') {
317
+ return @{ started = $false; ready = $false; reason = "runspace failed to open: $($rs.RunspaceStateInfo)" }
318
+ }
319
+ $ps = [PowerShell]::Create()
320
+ $ps.Runspace = $rs
321
+ [void]$ps.AddScript($script:WpmHudBody).AddArgument($Action).AddArgument($MaxMs).AddArgument($ArmMs).AddArgument($script:WpmHudHotkeyId).AddArgument($script:WpmAbortChords)
322
+ $script:WpmHudHandle = $ps.BeginInvoke()
323
+ $script:WpmHudRunspace = $rs
324
+ $script:WpmHudPowerShell = $ps
325
+ $st = Get-WpmHudState -WaitMs $WaitMs
326
+ return @{ started = [bool]$st.running; ready = [bool]$st.running; reason = [string]$st.reason; state = $st }
327
+ }
328
+
329
+ function Get-WpmHudState {
330
+ # Wait for HudOn -- the same flag the readiness verdict uses. A budget that expired mid-init is
331
+ # 'starting', not 'dead': the caller can tell a slow start from a body that threw (overlay.ps1:250-262).
332
+ param([int]$WaitMs = 2500)
333
+ $deadline = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + $WaitMs
334
+ while ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -lt $deadline -and -not [WpmCtl]::HudOn) {
335
+ Start-Sleep -Milliseconds 50
336
+ }
337
+ $hwnd = [WpmCtl]::HudHwnd
338
+ $ex = 0
339
+ if ($hwnd -ne 0) { $ex = [WpmWin]::GetWindowLong([IntPtr]$hwnd, [WpmWin]::GWL_EXSTYLE) }
340
+ return @{
341
+ running = [bool][WpmCtl]::HudOn
342
+ starting = (-not [WpmCtl]::HudOn) -and ($script:WpmHudHandle -ne $null) -and (-not $script:WpmHudHandle.AsyncWaitHandle.WaitOne(0))
343
+ hwnd = [string]$hwnd
344
+ phase = [string][WpmCtl]::HudPhase
345
+ abortChordRegistered = [bool][WpmCtl]::AbortChordOk
346
+ abortChordLabel = [string][WpmCtl]::AbortChordLabel
347
+ injectedChars = [int][WpmCtl]::InjectedChars
348
+ abortRequested = [bool][WpmCtl]::TakeoverAbort
349
+ reason = [string][WpmCtl]::Reason
350
+ exStyle = '0x{0:X8}' -f $ex
351
+ topmost = [bool]($ex -band [WpmWin]::WS_EX_TOPMOST)
352
+ noActivate = [bool]($ex -band [WpmWin]::WS_EX_NOACTIVATE)
353
+ transparent = [bool]($ex -band [WpmWin]::WS_EX_TRANSPARENT)
354
+ foregroundNow = [WpmWin]::Fg()
355
+ }
356
+ }
357
+
358
+ function Test-WpmHudReady {
359
+ return [bool]([WpmCtl]::HudOn -and [WpmCtl]::HudHwnd -ne 0)
360
+ }
361
+
362
+ function Set-WpmHudPhase {
363
+ # A REQUEST, not an action: three field writes, applied by the HUD's own pump. Called on every phase
364
+ # change and every 50ms while active (for the elapsed clock).
365
+ param([ValidateSet('arming', 'active', 'done')][string]$Phase, [string]$Action = '', [int]$MaxMs = -1, [int]$ElapsedMs = -1)
366
+ [WpmCtl]::HudPhase = $Phase
367
+ if ($Action) { [WpmCtl]::HudAction = $Action }
368
+ if ($MaxMs -ge 0) { [WpmCtl]::HudMaxMs = $MaxMs }
369
+ if ($ElapsedMs -ge 0) { [WpmCtl]::HudElapsedMs = $ElapsedMs }
370
+ return @{ phase = $Phase; hudOn = [bool][WpmCtl]::HudOn }
371
+ }
372
+
373
+ function Stop-WpmHud {
374
+ param([int]$WaitMs = 2500)
375
+ $hwnd = [WpmCtl]::HudHwnd
376
+ $posted = $false
377
+ if ($hwnd -ne 0) {
378
+ try { $posted = [bool][WpmWin]::PostMessageW([IntPtr]$hwnd, [uint32][WpmWin]::WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero) } catch { $posted = $false }
379
+ }
380
+ $completed = $false
381
+ if ($script:WpmHudHandle) {
382
+ $spin = 0
383
+ while (-not $script:WpmHudHandle.IsCompleted -and $spin -lt 6) { Start-Sleep -Milliseconds 50; $spin++ }
384
+ $completed = [bool]$script:WpmHudHandle.IsCompleted
385
+ }
386
+ if (-not $completed) {
387
+ $d = [WpmCtl]::Dispatcher
388
+ if ($d) { try { [void]$d.InvokeShutdown() } catch { } }
389
+ $spin = 0
390
+ while ($script:WpmHudHandle -and -not $script:WpmHudHandle.IsCompleted -and $spin -lt 20) { Start-Sleep -Milliseconds 25; $spin++ }
391
+ $completed = [bool]($script:WpmHudHandle -and $script:WpmHudHandle.IsCompleted)
392
+ }
393
+ if ($script:WpmHudHandle) { try { $script:WpmHudPowerShell.EndInvoke($script:WpmHudHandle) | Out-Null } catch { } }
394
+ if ($script:WpmHudPowerShell) { try { $script:WpmHudPowerShell.Dispose() } catch { }; $script:WpmHudPowerShell = $null }
395
+ if ($script:WpmHudRunspace) { try { $script:WpmHudRunspace.Dispose() } catch { }; $script:WpmHudRunspace = $null }
396
+ $script:WpmHudHandle = $null
397
+ $st = Get-WpmHudState -WaitMs 150
398
+ if (-not $completed) {
399
+ [WpmCtl]::HudOn = $false
400
+ [WpmCtl]::HudPhase = ''
401
+ [WpmCtl]::HudHwnd = [int64]0
402
+ [WpmCtl]::AbortChordOk = $false
403
+ [WpmCtl]::AbortChordLabel = ''
404
+ [WpmCtl]::Window = $null
405
+ [WpmCtl]::Timer = $null
406
+ [WpmCtl]::Dispatcher = $null
407
+ $st = Get-WpmHudState -WaitMs 100
408
+ $st.reason = 'hud pipeline did not end within the bound; state cleared by Stop-WpmHud'
409
+ }
410
+ return @{ stopped = $true; completed = $completed; posted = $posted; state = $st }
411
+ }