dsh-native-uia 0.2.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.
Files changed (55) hide show
  1. package/README.md +81 -398
  2. package/client/client.js +236 -48
  3. package/cordis.patch.yml +7 -8
  4. package/locale/en.json +2 -2
  5. package/locale/zh.json +2 -2
  6. package/package.json +8 -17
  7. package/scripts/check-lease.mjs +1 -1
  8. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  9. package/scripts/lib/load-tools-source.mjs +17 -16
  10. package/scripts/lib/sources.mjs +62 -0
  11. package/scripts/load-tools.mjs +74 -0
  12. package/scripts/measure-parse.mjs +2 -2
  13. package/scripts/regression-tools.mjs +155 -6
  14. package/scripts/regression-worker.ps1 +29 -0
  15. package/scripts/verify-live-style.mjs +46 -0
  16. package/scripts/verify-live.mjs +12 -18
  17. package/scripts/verify.mjs +953 -192
  18. package/src/activity-window.js +71 -7
  19. package/src/dashboard.js +27 -69
  20. package/src/guard.js +39 -10
  21. package/src/index.js +187 -77
  22. package/src/notes.js +83 -0
  23. package/src/state.js +97 -10
  24. package/src/themes.js +66 -0
  25. package/src/tools/defs/act.js +671 -0
  26. package/src/tools/defs/lifecycle.js +205 -0
  27. package/src/tools/defs/observe.js +325 -0
  28. package/src/tools/defs/pointer.js +328 -0
  29. package/src/tools/format.js +338 -0
  30. package/src/tools/index.js +125 -0
  31. package/src/tools/ocr.js +91 -0
  32. package/src/tools/recipes.js +49 -0
  33. package/src/tools/runtime.js +42 -0
  34. package/src/worker-client.js +32 -10
  35. package/worker/assets/dsh-whale.path +1 -0
  36. package/worker/indicator-server.ps1 +1107 -72
  37. package/worker/lib/01-core.ps1 +64 -0
  38. package/worker/lib/02-uia.ps1 +224 -0
  39. package/worker/lib/03-window.ps1 +194 -0
  40. package/worker/lib/04-match.ps1 +435 -0
  41. package/worker/lib/05-value.ps1 +254 -0
  42. package/worker/lib/06-snapshot.ps1 +412 -0
  43. package/worker/lib/07-action.ps1 +329 -0
  44. package/worker/lib/08-command.ps1 +1495 -0
  45. package/worker/lib/09-pointer.ps1 +840 -0
  46. package/worker/lib/10-dispatch.ps1 +132 -0
  47. package/worker/ps-stdio.ps1 +7 -2
  48. package/worker/uia-worker.ps1 +599 -4220
  49. package/locale/desktop/en.json +0 -6
  50. package/locale/desktop/zh.json +0 -6
  51. package/scripts/regression-halt-latch.mjs +0 -100
  52. package/src/native-uia-remote.js +0 -80
  53. package/src/panel-face.js +0 -14
  54. package/src/tools.js +0 -1482
  55. package/web/control.html +0 -1413
@@ -0,0 +1,1495 @@
1
+ # 08-command.ps1 -- request handlers (snapshot..shutdown)
2
+ #
3
+ # Part of worker/uia-worker.ps1, dot-sourced by it in the order scripts/lib/sources.mjs declares.
4
+ # It lives in its own file only so a section can be read without scrolling the whole RPC server.
5
+ # Dot-sourcing shares the entry's script scope, so a helper here may use $script:W and may call
6
+ # any function from any other part: neighbour order is not a dependency.
7
+ # ---------------------------------------------------------------- commands
8
+ function Cmd-Ping($A) {
9
+ if ($script:dpiMode -eq 0 -and $script:nativeLoaded) {
10
+ try { $script:dpiMode = [Native]::MakeAware() } catch { }
11
+ }
12
+ # The station size comes from the ONE authoritative measurement (Get-VirtScreen: the virtual
13
+ # screen with its measured fallback chain). Ping used to re-derive it from its own SM_CXSCREEN
14
+ # read plus the WinForms primary-screen bounds, and also reported a dead "logical" pair no
15
+ # consumer ever read — a second opinion that disagreed with the pointer channel's answer on
16
+ # multi-monitor boxes, exactly the silent drift the "measure, never hardcode" rule exists for.
17
+ # MakeAware has already run at startup (and above), so the metrics are physical.
18
+ $v = Get-VirtScreen
19
+ $w = [int]$v.w; $h = [int]$v.h
20
+ return [ordered]@{
21
+ psVersion = $PSVersionTable.PSVersion.ToString()
22
+ station = @{ width = $w; height = $h }
23
+ workerPid = [int]$PID
24
+ maxRefs = [int]$script:W.maxRefs
25
+ windowCount = $script:W.windows.Count
26
+ totalRefs = $script:W.totalRefs
27
+ startupMs = [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $script:W.startTick) / 10000.0, 1)
28
+ nativeLoaded = [bool]$script:nativeLoaded
29
+ dpiAware = [int]$script:dpiMode
30
+ }
31
+ }
32
+
33
+ function Match-RootWindow($w, $wantPid, $wantTitle, $wantClass, $titleExact, $wantRegex) {
34
+ $cp = $null
35
+ try { $cp = $w.Current } catch { return $false }
36
+ $hwnd = [int]$cp.NativeWindowHandle
37
+ if ($hwnd -eq 0) { return $false }
38
+ $rc = RectOf $cp
39
+ $iconic = $false
40
+ try { $iconic = [Native]::IsIconic([IntPtr]$hwnd) } catch { }
41
+ if (($rc.w -le 0 -or $rc.h -le 0) -and -not $iconic) { return $false }
42
+ if ($wantPid -gt 0 -and [int]$cp.ProcessId -ne $wantPid) { return $false }
43
+ if ($wantClass -ne '' -and ([string]$cp.ClassName).IndexOf($wantClass, [StringComparison]::OrdinalIgnoreCase) -lt 0) { return $false }
44
+ $t = [string]$cp.Name
45
+ if ($wantTitle -ne '') {
46
+ if ($titleExact) { if (-not $t.Equals($wantTitle, [StringComparison]::OrdinalIgnoreCase)) { return $false } }
47
+ elseif ($t.IndexOf($wantTitle, [StringComparison]::OrdinalIgnoreCase) -lt 0) { return $false }
48
+ }
49
+ if ($wantRegex -ne '') {
50
+ try { if ($t -notmatch $wantRegex) { return $false } } catch { return $false }
51
+ }
52
+ return $true
53
+ }
54
+
55
+ function Cmd-ResolveWindow($A) {
56
+ $windowId = StrArg $A 'windowId' ''
57
+ if ($windowId -ne '') {
58
+ $e = Window-Entry $windowId
59
+ $ae = Window-Ae $e
60
+ if ($null -eq $ae) { Err 'window_not_found' ("windowId " + $windowId + " is gone") }
61
+ $info = WindowInfo $e ($ae.Current)
62
+ $info['appearedMs'] = 0
63
+ return $info
64
+ }
65
+ $wantPid = IntArg $A 'pid' 0
66
+ $wantTitle = StrArg $A 'title' ''
67
+ $wantClass = StrArg $A 'class' ''
68
+ $wantRegex = StrArg $A 'titleRegex' ''
69
+ $titleExact = BoolArg $A 'titleExact' $false
70
+ $timeoutMs = IntArg $A 'timeoutMs' 4000
71
+ if ($wantPid -eq 0 -and $wantTitle -eq '' -and $wantClass -eq '' -and $wantRegex -eq '') { Err 'missing_arg' 'resolve_window needs windowId, pid, title, class or titleRegex' }
72
+ $st = TickNow
73
+ $left = BudgetLeftMs
74
+ if ($timeoutMs -gt $left) { $timeoutMs = [int]$left }
75
+ if ($timeoutMs -lt 0) { $timeoutMs = 0 }
76
+ $deadline = $st + ([Int64]$timeoutMs * 10000)
77
+ while ($true) {
78
+ foreach ($w in (RootWindows)) {
79
+ if (Match-RootWindow $w $wantPid $wantTitle $wantClass $titleExact $wantRegex) {
80
+ $hwnd = 0
81
+ try { $hwnd = [int]$w.Current.NativeWindowHandle } catch { continue }
82
+ $e = Ensure-Window $hwnd $w
83
+ if ($null -eq $e) { continue }
84
+ $info = WindowInfo $e ($w.Current)
85
+ $info['appearedMs'] = [Math]::Round((MsFrom $st), 1)
86
+ return $info
87
+ }
88
+ }
89
+ if ((TickNow) -ge $deadline) { break }
90
+ Start-Sleep -Milliseconds 150
91
+ }
92
+ $script:W.stats.refused += 1
93
+ Err 'window_not_found' ("no window matching pid=" + $wantPid + " title='" + $wantTitle + "' class='" + $wantClass + "' after " + $timeoutMs + 'ms of polling')
94
+ }
95
+
96
+ function Cmd-ListWindows($A) {
97
+ $onlyVisible = BoolArg $A 'onlyVisible' $true
98
+ $out = New-Object System.Collections.Generic.List[object]
99
+ foreach ($w in (RootWindows)) {
100
+ $cp = $null
101
+ try { $cp = $w.Current } catch { continue }
102
+ $hwnd = [int]$cp.NativeWindowHandle
103
+ if ($hwnd -eq 0) { continue }
104
+ $rc = RectOf $cp
105
+ $iconic = $false
106
+ try { $iconic = [Native]::IsIconic([IntPtr]$hwnd) } catch { }
107
+ $vis = $false
108
+ try { $vis = [Native]::IsWindowVisible([IntPtr]$hwnd) } catch { }
109
+ if ($onlyVisible -and (($rc.w -le 0 -or $rc.h -le 0) -or (-not $vis -and -not $iconic))) { continue }
110
+ $e = Ensure-Window $hwnd $w
111
+ if ($null -eq $e) { continue }
112
+ $info = WindowInfo $e $cp
113
+ $info['isMinimized'] = $iconic
114
+ $out.Add($info) | Out-Null
115
+ }
116
+ return [ordered]@{ windows = $out; count = $out.Count; totalRefs = $script:W.totalRefs }
117
+ }
118
+
119
+ function Cmd-Snapshot($A) {
120
+ $entry = Window-Entry (StrArg $A 'windowId' '')
121
+ return Build-Snapshot $entry $A
122
+ }
123
+
124
+ function Cmd-Describe($A) {
125
+ $ref = StrArg $A 'ref' ''
126
+ $re = Resolve-Ref $ref $A
127
+ # The descriptor rides the ref record: New-Ref already cached controlType/name/className/
128
+ # automationId/patterns/enabled/isOffscreen/rect at snapshot time, and the only caller
129
+ # (computer_act's Node-side policy precheck) needs exactly those fields — the same
130
+ # cached-descriptor semantics Cmd-PrepareBatch has always judged policy on. The live COM re-read
131
+ # is confined to the cache-miss branch: a rebound ref's cached fields belong to the OLD element
132
+ # (Resolve-Ref swaps $re.ae without refreshing them), so only there is a re-read honest.
133
+ if ($re.rebound) {
134
+ $d = DescriptorOf $re $true
135
+ $d['rebound'] = $true
136
+ return $d
137
+ }
138
+ return DescriptorOf $re $false
139
+ }
140
+
141
+ function Cmd-DescriptorMatch($A) {
142
+ # Read-only: resolves a by-descriptor exactly the way act / commit_batch / wait would, and reports
143
+ # WHY (which rung of the ladder, how confident, whether it degraded) or what it nearly matched.
144
+ # It sends no input, moves no pointer and mints no ref, so it is safe to call before a batch.
145
+ $entry = Window-Entry (StrArg $A 'windowId' '')
146
+ $by = Dict (ArgOf $A 'by')
147
+ if ($null -eq $by) { Err 'missing_arg' 'descriptor_match needs a by descriptor' }
148
+ $el = Find-ByDescriptor $entry $by
149
+ $lm = $script:W.lastMatch
150
+ if ($null -eq $lm) {
151
+ $lm = @{
152
+ matchedBy = ''; ladder = ''; score = 0.0; degraded = $false; candidateCount = 0
153
+ scanned = 'all'; nameExact = $true; reason = 'no_match'; tried = @(); candidates = @()
154
+ ambiguityAt = ''; diagnosticTruncated = $false
155
+ candidateCountKnown = $true; fastCond = $null
156
+ }
157
+ }
158
+ # The strict fast path resolved through FindFirst, which stops at the first hit and leaves the
159
+ # real same-name count unknown (candidateCountKnown=false). This command is the read-only
160
+ # diagnostic, so it re-runs the EXACT condition the resolver used as a full enumeration: a
161
+ # same-name ambiguity surfaces here with its true candidate count instead of hiding behind a
162
+ # fabricated one. Reads only — no input, no refs.
163
+ if ($null -ne $el -and -not [bool]$lm.candidateCountKnown -and $null -ne $lm.fastCond) {
164
+ $aeD = Window-Ae $entry
165
+ if ($null -ne $aeD) {
166
+ $recount = @()
167
+ try { $recount = @($aeD.FindAll([System.Windows.Automation.TreeScope]::Descendants, $lm.fastCond)) } catch { $recount = @() }
168
+ if ($recount.Count -ge 1) {
169
+ $lm.candidateCount = $recount.Count
170
+ $lm.candidateCountKnown = $true
171
+ if ($recount.Count -gt 1 -and [string]$lm.ambiguityAt -eq '') { $lm.ambiguityAt = [string]$lm.ladder }
172
+ }
173
+ }
174
+ }
175
+ $r = [ordered]@{
176
+ found = [bool]($null -ne $el)
177
+ windowId = $entry.id
178
+ matchedBy = [string]$lm.matchedBy
179
+ ladder = [string]$lm.ladder
180
+ score = [double]$lm.score
181
+ degraded = [bool]$lm.degraded
182
+ candidateCount = [int]$lm.candidateCount
183
+ # true = counted from a full enumeration (or the recount above); false = the resolver only
184
+ # ran FindFirst, so the count is "at least one" and a same-name ambiguity may still hide.
185
+ candidateCountKnown = [bool]$lm.candidateCountKnown
186
+ scanned = [string]$lm.scanned
187
+ nameExact = [bool]$lm.nameExact
188
+ # NOT @($lm.tried)/@($lm.candidates): Windows PowerShell 5.1 throws "Argument types do not
189
+ # match" for @() around a List[object] made by New-Object (verified on 5.1.26100). JsonOf walks
190
+ # IEnumerable, so the raw collections serialise as arrays without the cast.
191
+ tried = $lm.tried
192
+ candidates = $lm.candidates
193
+ }
194
+ if ([string]$lm.reason -ne '') { $r['reason'] = [string]$lm.reason }
195
+ if ([string]$lm.ambiguityAt -ne '') { $r['ambiguityAt'] = [string]$lm.ambiguityAt }
196
+ if ([bool]$lm.diagnosticTruncated) { $r['diagnosticTruncated'] = $true }
197
+ if ($null -ne $el) {
198
+ $cp = $null
199
+ try { $cp = $el.Current } catch { $cp = $null }
200
+ if ($null -ne $cp) {
201
+ $r['element'] = [ordered]@{
202
+ name = (TruncStr ([string]$cp.Name) 160)
203
+ automationId = [string]$cp.AutomationId
204
+ controlType = (ControlTypeName $cp.ControlType)
205
+ className = [string]$cp.ClassName
206
+ enabled = [bool]$cp.IsEnabled
207
+ isOffscreen = [bool]$cp.IsOffscreen
208
+ rect = (RectOf $cp)
209
+ }
210
+ }
211
+ }
212
+ if ([string]$r['matchedBy'] -eq '' -and $r.Contains('matchedBy')) {
213
+ $r.Remove('matchedBy')
214
+ if ($r.Contains('ladder')) { $r.Remove('ladder') }
215
+ }
216
+ return $r
217
+ }
218
+
219
+ function Apply-ModeArg($A) {
220
+ # The Node side sends the user's chosen delivery mode on every act/commit_batch, so a fresh worker
221
+ # (respawned lazily) picks it up on the next action instead of resetting to the default.
222
+ $m = (StrArg $A 'mode' '').ToLowerInvariant()
223
+ if (@('background', 'auto', 'foreground') -contains $m) { $script:W.pointerMode = $m }
224
+ }
225
+
226
+ function Cmd-SetPointerMode($A) {
227
+ $m = (StrArg $A 'mode' '').ToLowerInvariant()
228
+ if (@('background', 'auto', 'foreground') -notcontains $m) { Err 'bad_arg' ("pointer mode '" + $m + "' is not background|auto|foreground") }
229
+ $script:W.pointerMode = $m
230
+ return [ordered]@{ mode = $m }
231
+ }
232
+
233
+ function Cmd-EscapePressed($A) {
234
+ # Fallback probe for the Node host's global-ESC watcher (the indicator is the primary channel).
235
+ # Same latch as the indicator: the low bit reports "pressed since the previous call", so a tap
236
+ # shorter than the poll interval still counts once. Test-Escape stays the plain held-read for
237
+ # aborting a batch mid-step, where "is it down right now" is the correct question.
238
+ try {
239
+ $state = [int][Native]::GetAsyncKeyState(0x1B)
240
+ return [ordered]@{ pressed = [bool](($state -band 0x8000) -ne 0 -or ($state -band 0x0001) -ne 0) }
241
+ } catch {
242
+ return [ordered]@{ pressed = $false }
243
+ }
244
+ }
245
+
246
+ function Ensure-InView($re) {
247
+ # A ref can be valid and still be scrolled out of the viewport (the tree carries offscreen nodes,
248
+ # that is the point of UIA). Before acting, ask the provider to scroll it in: ScrollItem.ScrollIntoView
249
+ # is the non-destructive, focus-free way, and it is exactly what a human does before clicking.
250
+ # Returns $true when it actually scrolled, so the caller can report it instead of pretending the
251
+ # click landed where the model thought.
252
+ try {
253
+ $cp = $re.ae.Current
254
+ if (-not [bool]$cp.IsOffscreen) { return $false }
255
+ $p = $null
256
+ try { $p = $re.ae.GetCurrentPattern([System.Windows.Automation.ScrollItemPattern]::Pattern) } catch { $p = $null }
257
+ if ($null -eq $p) { return $false }
258
+ $p.ScrollIntoView()
259
+ Start-Sleep -Milliseconds 120
260
+ return $true
261
+ } catch { return $false }
262
+ }
263
+
264
+ function Cmd-Act($A) {
265
+ Apply-ModeArg $A
266
+ $ref = StrArg $A 'ref' ''
267
+ $action = StrArg $A 'action' ''
268
+ if ($action -eq '') { Err 'missing_arg' 'act needs an action' }
269
+ $value = ArgOf $A 'value'
270
+ $re = Resolve-Ref $ref $A
271
+ # Offscreen refs are acted on, not refused: scroll the element into view first unless the caller
272
+ # turned it off. Reported as `scrolled` so the reply can say the viewport moved.
273
+ $scrolled = $false
274
+ if (-not (BoolArg $A 'noScrollIntoView' $false)) { $scrolled = Ensure-InView $re }
275
+ # Third arg = the ref record: before/action/after then share ONE cached pattern object each
276
+ # instead of re-running GetCurrentPattern for the same pattern three times.
277
+ $before = Read-Value $re.ae $re.patterns $re
278
+ # scroll_percent_changed 的动作前基线:只有滚动动作或 verify 明确要它才多读一次(否则每个
279
+ # act 都白付一次跨进程 pattern 读)。
280
+ $scrollBefore = $null
281
+ $vpre = Dict (ArgOf $A 'verify')
282
+ $vpreType = if ($null -ne $vpre) { [string]$vpre.Item('type') } else { '' }
283
+ if ($action -eq 'scroll_up' -or $action -eq 'scroll_down' -or $vpreType -eq 'scroll_percent_changed') {
284
+ $scrollBefore = Read-ScrollPercent $re
285
+ }
286
+ $cur0 = Cursor-Pos
287
+ $fg0 = Foreground-Hwnd
288
+ $st = TickNow
289
+ $via = Do-Action $re $action $value $A
290
+ $script:W.stats.actionsPerformed += 1
291
+ $ms = MsFrom $st
292
+ $re2 = Resolve-Ref $ref $A
293
+ $after = Read-Value $re2.ae $re2.patterns $re2
294
+ $cur1 = Cursor-Pos
295
+ $fg1 = Foreground-Hwnd
296
+ $r = [ordered]@{
297
+ applied = $true
298
+ before = (TruncStr ([string]$before) 200)
299
+ after = (TruncStr ([string]$after) 200)
300
+ ms = $ms
301
+ via = $via
302
+ ref = $ref
303
+ action = $action
304
+ scrolled = [bool]$scrolled
305
+ cursorMoved = -not ($cur0.x -eq $cur1.x -and $cur0.y -eq $cur1.y)
306
+ foregroundChanged = ($fg0 -ne $fg1)
307
+ revision = $re.revision
308
+ }
309
+ $v = Dict (ArgOf $A 'verify')
310
+ if ($null -ne $v) {
311
+ $entry = $script:W.windows.Item($re.windowId)
312
+ # A verify that does not name its own target is a claim about the element this very action
313
+ # just touched, so default it to that ref. Without this, value_equals resolves nothing and
314
+ # every post-action check reads "target missing" no matter how correct the action was.
315
+ if (-not $v.ContainsKey('ref') -and $null -eq $v.Item('by')) { $v['ref'] = $ref }
316
+ $vm = IntArg $v 'timeoutMs' 900
317
+ $vv = Wait-Condition $entry $v $vm $before $null $scrollBefore
318
+ $r['verify'] = $vv
319
+ $verdict = if ([bool]$vv.matched) { 'matched' } else { 'unmatched' }
320
+ $r['detail'] = ('verify=' + [string]$vv.type + ':' + $verdict)
321
+ }
322
+ return $r
323
+ }
324
+
325
+ function Cmd-PrepareBatch($A) {
326
+ $steps = ListOf (ArgOf $A 'steps')
327
+ if ($steps.Count -eq 0) { Err 'missing_arg' 'prepare_batch needs steps' }
328
+ if ($steps.Count -gt 64) { Err 'too_many_steps' ('prepare_batch supports at most 64 steps, got ' + $steps.Count) }
329
+ $descs = New-Object System.Collections.Generic.List[object]
330
+ $allOk = $true
331
+ $revSeen = @{}
332
+ $batchWid = StrArg $A 'windowId' ''
333
+ $i = -1
334
+ foreach ($raw in $steps) {
335
+ $i += 1
336
+ $s = Dict $raw
337
+ $ref = [string]$s.Item('ref')
338
+ $by = Dict $s.Item('by')
339
+ $re = $null
340
+ try {
341
+ if ($ref -ne '') {
342
+ $re = Resolve-Ref $ref $null
343
+ $d = DescriptorOf $re $false
344
+ $d['index'] = $i
345
+ $e = $script:W.windows.Item($re.windowId)
346
+ $revSeen[$re.windowId] = $e.revision
347
+ } elseif ($null -ne $by) {
348
+ $wid = [string]$s.Item('windowId')
349
+ # A replayed recipe step carries only a `by` descriptor; the window it belongs to comes
350
+ # from the batch-level windowId, not from the step. Fall back to it before refusing.
351
+ if ($wid -eq '') { $wid = $batchWid }
352
+ if ($wid -eq '') { Err 'missing_arg' ("step " + $i + " has a by-descriptor but no windowId") }
353
+ $entry = Window-Entry $wid
354
+ $el = Find-ByDescriptor $entry $by
355
+ if ($null -eq $el) { Err 'descriptor_unresolved' ("step " + $i + " descriptor matched nothing in " + $wid) }
356
+ # A by-descriptor is a guess (a name can churn, an id can be ambiguous), so the dry run has
357
+ # to say HOW the guess was reached. These fields come from the ladder record the call above
358
+ # just left behind, and only the by branch gets them: a ref is an exact identity, not a
359
+ # locator decision, so attaching a score to it would describe a match that never happened.
360
+ $loc = Get-LocatorFields $script:W.lastMatch
361
+ $cp = $el.Current
362
+ $pats = PatternsOf $el
363
+ $d = [ordered]@{
364
+ index = $i
365
+ windowId = $wid
366
+ resolvedBy = 'descriptor'
367
+ name = (TruncStr ([string]$cp.Name) 160)
368
+ controlType = (ControlTypeName $cp.ControlType)
369
+ className = [string]$cp.ClassName
370
+ automationId = [string]$cp.AutomationId
371
+ availablePatterns = @($pats)
372
+ supportedAction = (SupportedActionOf $pats)
373
+ enabled = [bool]$cp.IsEnabled
374
+ isOffscreen = [bool]$cp.IsOffscreen
375
+ rect = (RectOf $cp)
376
+ }
377
+ if ($null -ne $loc) {
378
+ $d['matchedBy'] = $loc['matchedBy']
379
+ $d['ladder'] = $loc['ladder']
380
+ $d['score'] = $loc['score']
381
+ $d['degraded'] = $loc['degraded']
382
+ }
383
+ # Same rule as DescriptorOf: only when the 160-cut display name differs from the real one,
384
+ # so a recipe rebuilt from this descriptor can carry a name that still resolves.
385
+ if ([string]$cp.Name -ne [string]$d['name']) { $d['fullName'] = [string]$cp.Name }
386
+ $revSeen[$wid] = $entry.revision
387
+ } else {
388
+ Err 'missing_ref' ("step " + $i + " needs a ref or a by descriptor")
389
+ }
390
+ $actName = [string]$s.Item('action')
391
+ # Validate the verb at prepare time. Prepare is the dry run: its whole job is to answer
392
+ # "would this batch work?" before a single event reaches the desktop. It used to copy the
393
+ # action through untouched, so "fly" resolved happily and only commit_batch refused it —
394
+ # the model paid for two round-trips and a revision to learn a typo it could have heard
395
+ # about immediately.
396
+ if ($actName -eq '') { Err 'missing_arg' ("step " + $i + " needs an action") }
397
+ # PowerShell's switch is case-INSENSITIVE by default, but the values it compares come from
398
+ # model-authored JSON and a "Invoke" used to sail through prepare while the case-sensitive
399
+ # hashtable check later refused it. Normalise once here so prepare and commit agree.
400
+ $actName = $actName.ToLowerInvariant()
401
+ if (-not $script:W.actionNames.ContainsKey($actName)) {
402
+ Err 'unknown_action' ("step " + $i + " action '" + $actName + "' is not one of " + (($script:W.actionNames.Keys | Sort-Object) -join '|'))
403
+ }
404
+ $d['action'] = $actName
405
+ $descs.Add($d) | Out-Null
406
+ } catch {
407
+ $allOk = $false
408
+ $code, $msg = Split-Err $_
409
+ $descs.Add([ordered]@{ index = $i; ref = $ref; action = [string]$s.Item('action'); error = $msg; code = $code }) | Out-Null
410
+ }
411
+ }
412
+ # A batch is validated against ONE revision (commit compares every step against the single value
413
+ # returned here). Steps that span two snapshotted windows can never satisfy that: prepare passed
414
+ # on the first window's revision, commit then died on the second window's step — reported as
415
+ # "revision stale" when the real answer is "one batch per window". Refuse at the dry run, where
416
+ # nothing has been executed and the caller can restructure for free.
417
+ if ($revSeen.Count -gt 1) {
418
+ $script:W.stats.refused += 1
419
+ Err 'multi_window_batch' (("the steps span " + $revSeen.Count + " windows (" + ((@($revSeen.Keys) | Sort-Object) -join ',') + "); split them into one batch per window and run each batch with its own revision"))
420
+ }
421
+ $rev = 0
422
+ if ($revSeen.Count -ge 1) { $rev = [int](@($revSeen.Values)[0]) }
423
+ return [ordered]@{ descriptors = $descs; revision = $rev; allResolved = $allOk; revisionsByWindow = $revSeen; steps = $steps.Count }
424
+ }
425
+
426
+ function Cmd-CommitBatch($A) {
427
+ Apply-ModeArg $A
428
+ $steps = ListOf (ArgOf $A 'steps')
429
+ if ($steps.Count -eq 0) { Err 'missing_arg' 'commit_batch needs steps' }
430
+ if ($steps.Count -gt 64) { Err 'too_many_steps' ('commit_batch supports at most 64 steps, got ' + $steps.Count) }
431
+ $givenRev = ArgOf $A 'revision'
432
+ if ($null -eq $givenRev) {
433
+ $script:W.stats.refused += 1
434
+ Err 'revision_mismatch' 'commit_batch requires the exact revision returned by prepare_batch; refusing to perform 0 actions'
435
+ }
436
+ $wantRev = [int]$givenRev
437
+ $batchWid = StrArg $A 'windowId' ''
438
+ # phase 1: resolve every step, perform nothing
439
+ $plan = New-Object System.Collections.Generic.List[object]
440
+ $i = -1
441
+ foreach ($raw in $steps) {
442
+ $i += 1
443
+ $s = Dict $raw
444
+ $ref = [string]$s.Item('ref')
445
+ # Normalise exactly like prepare_batch, so a verb that passed the dry run cannot fail here on
446
+ # casing alone. The two phases must agree on what they accepted.
447
+ $action = ([string]$s.Item('action')).ToLowerInvariant()
448
+ $entry = $null
449
+ $re = $null
450
+ $loc = $null
451
+ if ($ref -ne '') {
452
+ $re = Resolve-Ref $ref $null
453
+ $entry = $script:W.windows.Item($re.windowId)
454
+ if ($re.revision -ne $wantRev) {
455
+ $script:W.stats.refused += 1
456
+ Err 'revision_mismatch' ("ref " + $ref + " is at revision " + $re.revision + " of " + $re.windowId + " but the batch declared revision " + $wantRev + '; performing 0 actions')
457
+ }
458
+ } else {
459
+ $wid = [string]$s.Item('windowId')
460
+ # Same rule as prepare_batch: a replayed step has no per-step windowId, so inherit the
461
+ # batch-level one instead of tripping Window-Entry('') with 'windowId is required'.
462
+ if ($wid -eq '') { $wid = $batchWid }
463
+ $entry = Window-Entry $wid
464
+ if ($entry.revision -ne $wantRev) {
465
+ $script:W.stats.refused += 1
466
+ Err 'revision_mismatch' ("window " + $wid + " is at revision " + $entry.revision + " but the batch declared revision " + $wantRev + '; performing 0 actions')
467
+ }
468
+ $by = Dict $s.Item('by')
469
+ if ($null -eq $by) { Err 'missing_ref' ("step " + $i + " needs a ref or a by descriptor") }
470
+ $el = Find-ByDescriptor $entry $by
471
+ if ($null -eq $el) { Err 'descriptor_unresolved' ("step " + $i + " descriptor matched nothing in " + $wid) }
472
+ # Read from THIS resolution, not from prepare_batch: commit re-resolves on purpose (the tree
473
+ # may have moved on), so the honest report is what the ladder decided now. Costs no extra
474
+ # scan — the record is a by-product of the call above.
475
+ $loc = Get-LocatorFields $script:W.lastMatch
476
+ $cp = $el.Current
477
+ $node = @{ controlType = (ControlTypeName $cp.ControlType); name = [string]$cp.Name; className = [string]$cp.ClassName; automationId = [string]$cp.AutomationId; patterns = (PatternsOf $el); enabled = [bool]$cp.IsEnabled; isOffscreen = [bool]$cp.IsOffscreen; rect = (RectOf $cp); depth = 0 }
478
+ $re = New-Ref $entry $el $cp $node
479
+ }
480
+ $verifyOnly = $false
481
+ if ($action -eq '' -or $action -eq 'verify' -or $action -eq 'no_op' -or $action -eq 'check') {
482
+ $hasCheck = ($null -ne $s.Item('verify') -or $null -ne $s.Item('type'))
483
+ if (-not $hasCheck) { Err 'missing_arg' ("step " + $i + " needs an action (or a verify/type for a check-only step)") }
484
+ $verifyOnly = $true
485
+ if ($action -eq '') { $action = 'verify' }
486
+ }
487
+ $plan.Add(@{ index = $i; s = $s; re = $re; entry = $entry; action = $action; verifyOnly = $verifyOnly; loc = $loc }) | Out-Null
488
+ }
489
+ # phase 2: perform in order, stop at the first failure
490
+ $results = New-Object System.Collections.Generic.List[object]
491
+ $performed = 0
492
+ $stoppedAt = -1
493
+ $status = 'ok'
494
+ # ---- top-level window diff around phase 2 -----------------------------------------------
495
+ # A dialog that pops up mid-batch is invisible to the model until its NEXT observation, and its
496
+ # "确定/取消" text then hijacks the next find_text ranking. A read-only hwnd-set diff around
497
+ # phase 2 (RootWindows is one FindAll over ~9 desktop roots, ~20-30 ms) surfaces it with the
498
+ # result. The indicator overlay's own process is excluded when the caller passes its pid: the
499
+ # capsule lights asynchronously at activity.claim, so a cold first batch can genuinely see it
500
+ # appear — reporting our own overlay as a "new window" would be exactly the noise this diff
501
+ # exists to kill. The renderer filters the same pid again as a belt-and-braces.
502
+ $indicatorPid = IntArg $A 'indicatorPid' 0
503
+ $hwndsBefore = @{}
504
+ foreach ($w in (RootWindows)) {
505
+ $h = 0
506
+ try { $cpW = $w.Current; $h = [int]$cpW.NativeWindowHandle } catch { continue }
507
+ if ($h -ne 0) { $hwndsBefore[[string]$h] = $true }
508
+ }
509
+ for ($k = 0; $k -lt $plan.Count; $k++) {
510
+ $p = $plan[$k]
511
+ if (Test-Escape) { $stoppedAt = $p.index; $status = 'cancelled'; break }
512
+ $s = $p.s
513
+ $re = $p.re
514
+ $action = $p.action
515
+ $value = $s.Item('value')
516
+ $cur0 = Cursor-Pos
517
+ $fg0 = Foreground-Hwnd
518
+ $before = Read-Value $re.ae $re.patterns $re
519
+ # scroll_percent_changed 的动作前基线:只在"这一步可能用它"时才读——本步是滚动动作,或
520
+ # verify 声明了该类型(含 check-only 步,其条件就是步本身)。无关节点每步多读一次就是
521
+ # 1-3ms × 步数的纯跨进程开销。
522
+ $scrollBefore = $null
523
+ $vpre = Dict $s.Item('verify')
524
+ $vpreType = if ($null -ne $vpre) { [string]$vpre.Item('type') } else { [string]$s.Item('type') }
525
+ if ($action -eq 'scroll_up' -or $action -eq 'scroll_down' -or $vpreType -eq 'scroll_percent_changed') {
526
+ $scrollBefore = Read-ScrollPercent $re
527
+ }
528
+ $st = TickNow
529
+ $res = [ordered]@{ index = $p.index; ref = $re.ref; action = $action; status = 'failed'; ms = 0; before = (TruncStr ([string]$before) 200); after = ''; performed = $false }
530
+ # Same four fields the dry run reported, so the caller can see afterwards which steps were
531
+ # resolved by a downgraded rung. Ref steps carry none (see Get-LocatorFields).
532
+ if ($null -ne $p.loc) {
533
+ $res['matchedBy'] = $p.loc['matchedBy']
534
+ $res['ladder'] = $p.loc['ladder']
535
+ $res['score'] = $p.loc['score']
536
+ $res['degraded'] = $p.loc['degraded']
537
+ }
538
+ try {
539
+ # Step-boundary budget check. The batch must stop ITSELF once its request budget is gone:
540
+ # Node aborts the CALL after 30 s while the worker kept executing steps and delivering
541
+ # actions, so a model that saw "timeout" retried a batch that was still landing (duplicate
542
+ # input). Throwing INSIDE the try means the existing catch records this step as failed with
543
+ # deadline_exceeded and the partial results return with an accurate performedCount.
544
+ Test-Deadline 'commit_batch'
545
+ if ($null -ne $s.Item('foreground') -and (BoolArg $s 'foreground' $false)) { Raise-Foreground $p.entry }
546
+ if ($p.verifyOnly) {
547
+ # check-only step: performs NOTHING, it only evaluates the condition that follows the
548
+ # previous action. It never counts towards performedCount.
549
+ $cond = Dict $s.Item('verify')
550
+ if ($null -ne $cond) {
551
+ if (-not $cond.ContainsKey('ref') -and $null -eq $cond.Item('by')) { $cond['ref'] = $re.ref }
552
+ } else { $cond = $s }
553
+ $vm = IntArg $s 'timeoutMs' 900
554
+ # Same check right before the wait: budget that died mid-step must not enter a verify
555
+ # clamped to 0ms and report "unmatched" for a condition that was never measured.
556
+ Test-Deadline 'commit_batch'
557
+ $vv = Wait-Condition $p.entry $cond $vm $before $null $scrollBefore
558
+ $res['verify'] = $vv
559
+ if ($vv.Contains('observed')) { $res['after'] = (TruncStr ([string]$vv.observed) 200) }
560
+ if ($vv.matched) {
561
+ $res['status'] = 'passed'
562
+ $res['ms'] = MsFrom $st
563
+ $results.Add($res) | Out-Null
564
+ continue
565
+ }
566
+ $res['status'] = 'verify_failed'
567
+ $res['detail'] = 'verify condition ' + [string]$vv.type + ' did not match within ' + $vm + 'ms'
568
+ $res['ms'] = MsFrom $st
569
+ $results.Add($res) | Out-Null
570
+ $stoppedAt = $p.index
571
+ $status = 'verify_failed'
572
+ break
573
+ }
574
+ if (-not (BoolArg $s 'noScrollIntoView' $false)) { $res['scrolled'] = [bool](Ensure-InView $re) }
575
+ $via = Do-Action $re $action $value $s
576
+ # Delivery has happened even if a later read/verify fails. Count it immediately.
577
+ $performed += 1
578
+ $script:W.stats.actionsPerformed += 1
579
+ $res['performed'] = $true
580
+ $res['via'] = $via
581
+ $after = ''
582
+ # $re.patterns, not a second PatternsOf scan: the ref already carries the pattern list taken
583
+ # when this step resolved, and $before above read the same list.
584
+ try { $after = Read-Value $re.ae $re.patterns $re } catch { }
585
+ $res['after'] = (TruncStr ([string]$after) 200)
586
+ $c1 = Cursor-Pos
587
+ $res['cursorMoved'] = -not ($cur0.x -eq $c1.x -and $cur0.y -eq $c1.y)
588
+ $res['foregroundChanged'] = ($fg0 -ne (Foreground-Hwnd))
589
+ $v = Dict $s.Item('verify')
590
+ if ($null -ne $v) {
591
+ if (-not $v.ContainsKey('ref') -and $null -eq $v.Item('by')) { $v['ref'] = $re.ref }
592
+ $vm = IntArg $v 'timeoutMs' 900
593
+ # Budget may have died inside the action; a 0ms-clamped verify would report "unmatched"
594
+ # for a condition that was never measured. deadline_exceeded says what actually happened
595
+ # (and the result already carries performed=true: the action WAS delivered).
596
+ Test-Deadline 'commit_batch'
597
+ $vv = Wait-Condition $p.entry $v $vm $before $null $scrollBefore
598
+ $res['verify'] = $vv
599
+ if (-not $vv.matched) {
600
+ $res['status'] = 'verify_failed'
601
+ $res['ms'] = MsFrom $st
602
+ $res['detail'] = 'verify condition ' + [string]$v.Item('type') + ' did not match within ' + $vm + 'ms'
603
+ $results.Add($res) | Out-Null
604
+ $stoppedAt = $p.index
605
+ $status = 'verify_failed'
606
+ break
607
+ }
608
+ }
609
+ $res['status'] = 'passed'
610
+ $res['ms'] = MsFrom $st
611
+ $results.Add($res) | Out-Null
612
+ } catch {
613
+ $code, $msg = Split-Err $_
614
+ $res['status'] = 'failed'
615
+ $res['code'] = $code
616
+ $res['detail'] = $msg
617
+ $res['ms'] = MsFrom $st
618
+ $results.Add($res) | Out-Null
619
+ $stoppedAt = $p.index
620
+ $status = 'failed'
621
+ break
622
+ }
623
+ }
624
+ # Every step the batch never reached still gets a result entry, so the reply carries one line
625
+ # per step. Previously the tail was invisible: the model only had performedCount and one stop
626
+ # sentence, and could not tell which planned steps were skipped. not_executed means an earlier
627
+ # step failed or the run was cancelled; the fixed Chinese wording is rendered on the Node side
628
+ # (this file is parsed as ANSI, so Chinese string literals here would corrupt the parser).
629
+ if ($stoppedAt -ge 0) {
630
+ for ($k2 = ($stoppedAt + 1); $k2 -lt $steps.Count; $k2++) {
631
+ $p2 = $null
632
+ foreach ($pp in $plan) { if ($pp.index -eq $k2) { $p2 = $pp; break } }
633
+ if ($null -eq $p2) { continue }
634
+ $results.Add([ordered]@{
635
+ index = $k2
636
+ ref = $(if ($null -ne $p2.re) { $p2.re.ref } else { '' })
637
+ action = $p2.action
638
+ status = 'not_executed'
639
+ ms = 0
640
+ before = ''
641
+ after = ''
642
+ performed = $false
643
+ detail = 'not executed: an earlier step failed or the run was cancelled'
644
+ }) | Out-Null
645
+ }
646
+ }
647
+ # The Node side reads "no stop" as stoppedAt === null (see the allPassed check in
648
+ # src/tools/defs/act.js), so a
649
+ # sentinel of -1 here would be mistaken for a stop at step -1 and would suppress the recipe
650
+ # save on an otherwise clean batch. Emit the real index, or an explicit JSON null (DBNull, so
651
+ # the generic serializer keeps the key instead of dropping it) when every step passed.
652
+ $stoppedOut = if ($stoppedAt -lt 0) { [System.DBNull]::Value } else { $stoppedAt }
653
+ # "after" half of the window diff: every top-level hwnd that did not exist before phase 2 is
654
+ # reported with its title/class/pid. Empty when nothing appeared — the key stays ABSENT then, so
655
+ # consumers can distinguish "no diff" from an empty diff without extra contract.
656
+ $newWindows = @()
657
+ foreach ($w in (RootWindows)) {
658
+ $h = 0
659
+ $cpW = $null
660
+ try { $cpW = $w.Current; $h = [int]$cpW.NativeWindowHandle } catch { continue }
661
+ if ($h -eq 0) { continue }
662
+ if ($hwndsBefore.ContainsKey([string]$h)) { continue }
663
+ if ($indicatorPid -gt 0 -and [int]$cpW.ProcessId -eq [int]$indicatorPid) { continue }
664
+ $newWindows += [ordered]@{
665
+ hwnd = $h
666
+ pid = [int]$cpW.ProcessId
667
+ title = (TruncStr ([string]$cpW.Name) 120)
668
+ class = (TruncStr ([string]$cpW.ClassName) 80)
669
+ }
670
+ }
671
+ $r = [ordered]@{
672
+ results = $results
673
+ stoppedAt = $stoppedOut
674
+ performedCount = $performed
675
+ revision = $wantRev
676
+ status = $status
677
+ steps = $steps.Count
678
+ batchOk = ($stoppedAt -lt 0)
679
+ }
680
+ if ($newWindows.Count -gt 0) { $r['newWindows'] = $newWindows }
681
+ return $r
682
+ }
683
+
684
+ function Cmd-Wait($A) {
685
+ $cond = Dict (ArgOf $A 'condition')
686
+ if ($null -eq $cond) { Err 'missing_arg' 'wait needs a condition' }
687
+ $timeoutMs = IntArg $A 'timeoutMs' 3000
688
+ $wid = StrArg $A 'windowId' ''
689
+ $entry = $null
690
+ if ($wid -ne '') { $entry = Window-Entry $wid }
691
+ $type = [string]$cond.Item('type')
692
+ if ($type -eq 'element_appears' -or $type -eq 'element_gone') {
693
+ if ($null -eq $entry) {
694
+ $st = TickNow
695
+ $left = BudgetLeftMs
696
+ if ($timeoutMs -gt $left) { $timeoutMs = [int]$left }
697
+ $deadline = $st + ([Int64]$timeoutMs * 10000)
698
+ $hitWin = ''
699
+ while ($true) {
700
+ $hit = $null
701
+ foreach ($e in @($script:W.windows.Values)) {
702
+ $el = Find-ByDescriptor $e (Dict $cond.Item('by'))
703
+ if ($null -ne $el) { $hit = $e; break }
704
+ }
705
+ if ($type -eq 'element_appears') { if ($null -ne $hit) { $hitWin = $hit.id; break } }
706
+ else { if ($null -eq $hit) { break } else { $hitWin = $hit.id } }
707
+ if ((TickNow) -ge $deadline) { break }
708
+ Start-Sleep -Milliseconds 120
709
+ }
710
+ $matched = if ($type -eq 'element_appears') { $hitWin -ne '' } else { $hitWin -eq '' }
711
+ return [ordered]@{ matched = $matched; ms = [Math]::Round((MsFrom $st), 1); type = $type; windowId = $hitWin; scannedWindows = $script:W.windows.Count }
712
+ }
713
+ }
714
+ if ($type -eq 'window_appears' -or $type -eq 'window_gone' -or $type -eq 'window_title_contains') {
715
+ return Wait-Window $entry $cond $timeoutMs
716
+ }
717
+ if ($null -eq $entry) { Err 'missing_arg' 'wait needs windowId for this condition type' }
718
+ return Wait-Condition $entry $cond $timeoutMs $null $null
719
+ }
720
+
721
+ function Wait-Window($entry, $cond, $timeoutMs) {
722
+ # Window-level waits. "did the dialog appear" was previously only expressible as a sleep plus a
723
+ # list_windows round trip, which is exactly the guesswork computer_wait exists to remove.
724
+ # window_appears — a top-level window matching titleContains/class/pid exists; returns its windowId
725
+ # window_gone — the given windowId closed, or no window matches the criteria any more
726
+ # window_title_contains — one known window's title now contains the text (retitle, save-as path)
727
+ $c = $cond
728
+ $type = [string]$c.Item('type')
729
+ if (@('window_appears', 'window_gone', 'window_title_contains') -notcontains $type) {
730
+ Err 'unknown_condition' ("Wait-Window does not handle '" + (OneLine $type) + "'")
731
+ }
732
+ if ($needle -eq '') { $needle = [string]$c.Item('title') }
733
+ $wantClass = [string]$c.Item('class')
734
+ $wantPid = 0
735
+ try { $wantPid = [int]$c.Item('pid') } catch { $wantPid = 0 }
736
+ $hasCriteria = ($needle -ne '' -or $wantClass -ne '' -or $wantPid -ne 0)
737
+ if ($type -eq 'window_title_contains' -and $null -eq $entry) { Err 'missing_arg' 'window_title_contains needs windowId' }
738
+ if ($type -ne 'window_title_contains' -and $null -eq $entry -and -not $hasCriteria) {
739
+ Err 'bad_arg' ($type + ' needs titleContains, class or pid (or a windowId, for window_gone)')
740
+ }
741
+ $budget = $timeoutMs
742
+ $left = BudgetLeftMs
743
+ if ($left -lt $budget) { $budget = [int]$left }
744
+ if ($budget -lt 0) { $budget = 0 }
745
+ $st = TickNow
746
+ $deadline = $st + ([Int64]$budget * 10000)
747
+ $matched = $false
748
+ $hitId = ''
749
+ $hitTitle = ''
750
+ $obs = ''
751
+ while ($true) {
752
+ $hit = $null
753
+ if ($type -eq 'window_title_contains') {
754
+ $ae = Window-Ae $entry
755
+ $nm = ''
756
+ if ($null -ne $ae) { try { $nm = [string]$ae.Current.Name } catch { } }
757
+ $obs = 'title="' + (TruncStr $nm 60) + '"'
758
+ if ($nm -ne '' -and ($needle -eq '' -or $nm.IndexOf($needle, [StringComparison]::OrdinalIgnoreCase) -ge 0)) { $hit = $entry; $hitTitle = $nm }
759
+ } elseif ($type -eq 'window_gone' -and $null -ne $entry -and -not $hasCriteria) {
760
+ $ae = Window-Ae $entry
761
+ if ($null -eq $ae) { $matched = $true; $obs = 'window closed' } else { $obs = 'still open' }
762
+ } else {
763
+ foreach ($w in (RootWindows)) {
764
+ $cp = $null
765
+ try { $cp = $w.Current } catch { continue }
766
+ $title = [string]$cp.Name
767
+ if ($needle -ne '' -and $title.IndexOf($needle, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
768
+ $hwnd = [int]$cp.NativeWindowHandle
769
+ if ($hwnd -eq 0) { continue }
770
+ if ($wantClass -ne '') {
771
+ $cls = ''
772
+ try { $cls = [string]$cp.ClassName } catch { }
773
+ if ($cls.IndexOf($wantClass, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
774
+ }
775
+ if ($wantPid -ne 0) {
776
+ $wpid = 0
777
+ try { $wpid = [int]$cp.ProcessId } catch { $wpid = 0 }
778
+ if ($wpid -ne $wantPid) { continue }
779
+ }
780
+ $e = Ensure-Window $hwnd $w
781
+ if ($null -ne $e) { $hit = $e; $hitTitle = $title; break }
782
+ }
783
+ if ($type -eq 'window_gone') {
784
+ $matched = ($null -eq $hit)
785
+ $obs = if ($matched) { 'no matching window' } else { 'still ' + $hit.id }
786
+ } else {
787
+ $obs = if ($null -ne $hit) { 'found ' + $hit.id } else { 'not found' }
788
+ }
789
+ }
790
+ if ($type -ne 'window_gone' -and $null -ne $hit) { $matched = $true; $hitId = [string]$hit.id }
791
+ if ($matched) { break }
792
+ if ((TickNow) -ge $deadline) { break }
793
+ Start-Sleep -Milliseconds 120
794
+ }
795
+ $r = [ordered]@{ type = $type; matched = [bool]$matched; ms = [Math]::Round((MsFrom $st), 1); observed = $obs }
796
+ if ($hitId -ne '') { $r['windowId'] = $hitId }
797
+ if ($hitTitle -ne '') { $r['title'] = (TruncStr $hitTitle 80) }
798
+ return $r
799
+ }
800
+
801
+ function Cmd-CaptureScreen($A) {
802
+ # Native 1:1 by default, same rule as the window capture: a downscaled desktop reads as "the
803
+ # screen was cut off" and makes the model convert coordinates it could use directly.
804
+ $maxDim = IntArg $A 'maxDim' 0
805
+ $st = TickNow
806
+ if ($null -eq ('Native' -as [type])) { Err 'native_missing' 'the P/Invoke helper did not compile; capture is unavailable' }
807
+ $cap = [Native]::CaptureScreen($maxDim)
808
+ $v = Get-VirtScreen
809
+ $r = [ordered]@{
810
+ scope = 'screen'
811
+ method = [string]$cap.method
812
+ blank = [bool]$cap.blank
813
+ width = [int]$cap.width
814
+ height = [int]$cap.height
815
+ distinct = [int]$cap.distinct
816
+ pngBytes = 0
817
+ ms = (MsFrom $st)
818
+ # Measured, not assumed: the virtual screen origin is negative when a monitor sits left of or
819
+ # above the primary one, and it is re-read through GetSystemMetrics on every call.
820
+ screenRect = @{ x = [int]$v.x; y = [int]$v.y; w = [int]$v.w; h = [int]$v.h }
821
+ }
822
+ if ($null -ne $cap.png) {
823
+ $r['pngBytes'] = $cap.png.Length
824
+ if (BoolArg $A 'inline' $true) { $r['pngBase64'] = [Convert]::ToBase64String($cap.png) }
825
+ }
826
+ if ($cap.width -gt 0 -and $cap.height -gt 0) {
827
+ $r['imageWidth'] = [int]$cap.width
828
+ $r['imageHeight'] = [int]$cap.height
829
+ $r['scaleX'] = [Math]::Round([double]$v.w / [double]$cap.width, 4)
830
+ $r['scaleY'] = [Math]::Round([double]$v.h / [double]$cap.height, 4)
831
+ $r['coordinateMap'] = ('screenX = ' + [int]$v.x + ' + imgX * ' + [string]$r['scaleX'] + ' ; screenY = ' + [int]$v.y + ' + imgY * ' + [string]$r['scaleY'])
832
+ }
833
+ $note = [string]$cap.error
834
+ if ($cap.blank) { $note += ('desktop capture came back blank (distinct colors=' + [int]$cap.distinct + '); the session may be locked or on a disconnected desktop') }
835
+ if ($note -ne '') { $r['detail'] = (OneLine $note) }
836
+ return $r
837
+ }
838
+
839
+ function Parse-Region($A, $wr) {
840
+ # region = [x0,y0,x1,y1] in WINDOW physical pixels (the space snapshot rects live in), so a model
841
+ # that zoomed by cropping can keep using the same numbers it read from the tree. Returns $null
842
+ # when absent; clamps to the window and refuses a degenerate box instead of silently cropping 0px.
843
+ $raw = ArgOf $A 'region'
844
+ if ($null -eq $raw) { return $null }
845
+ $arr = @()
846
+ if ($raw -is [System.Collections.IEnumerable] -and -not ($raw -is [string])) { foreach ($v in $raw) { $arr += [double]$v } }
847
+ else { $arr = @(([string]$raw) -split ',' | ForEach-Object { [double]$_.Trim() }) }
848
+ if ($arr.Count -ne 4) { Err 'bad_arg' 'region must be [x0,y0,x1,y1]' }
849
+ $x0 = [int][Math]::Max([double]$wr.x, [Math]::Min($arr[0], $arr[2]))
850
+ $y0 = [int][Math]::Max([double]$wr.y, [Math]::Min($arr[1], $arr[3]))
851
+ $x1 = [int][Math]::Min([double]($wr.x + $wr.w), [Math]::Max($arr[0], $arr[2]))
852
+ $y1 = [int][Math]::Min([double]($wr.y + $wr.h), [Math]::Max($arr[1], $arr[3]))
853
+ if ($x1 - $x0 -lt 8 -or $y1 - $y0 -lt 8) { Err 'bad_arg' 'region is empty or smaller than 8x8 inside the window' }
854
+ return [ordered]@{ x = $x0; y = $y0; w = ($x1 - $x0); h = ($y1 - $y0) }
855
+ }
856
+
857
+ function Crop-PngBox($bytes, $x, $y, $w, $h) {
858
+ $ms = New-Object System.IO.MemoryStream(, $bytes)
859
+ $img = [System.Drawing.Image]::FromStream($ms)
860
+ try {
861
+ if ($x -lt 0 -or $y -lt 0 -or ($x + $w) -gt $img.Width -or ($y + $h) -gt $img.Height) {
862
+ Err 'bad_arg' ('crop box ' + $x + ',' + $y + ' ' + $w + 'x' + $h + ' exceeds the ' + $img.Width + 'x' + $img.Height + ' capture')
863
+ }
864
+ $bmp = New-Object System.Drawing.Bitmap($w, $h)
865
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
866
+ try {
867
+ $g.DrawImage($img, (New-Object System.Drawing.Rectangle(0, 0, $w, $h)), (New-Object System.Drawing.Rectangle($x, $y, $w, $h)), [System.Drawing.GraphicsUnit]::Pixel)
868
+ } finally { $g.Dispose() }
869
+ $out = New-Object System.IO.MemoryStream
870
+ try { $bmp.Save($out, [System.Drawing.Imaging.ImageFormat]::Png) } finally { $bmp.Dispose() }
871
+ return $out.ToArray()
872
+ } finally {
873
+ $img.Dispose()
874
+ $ms.Dispose()
875
+ }
876
+ }
877
+
878
+ function Cmd-Capture($A) {
879
+ $entry = Window-Entry (StrArg $A 'windowId' '')
880
+ # Native 1:1 by default. A downscaled window capture silently changes what the model can read —
881
+ # small text turns to mush and the coordinateMap picks up a scale factor — so the honest default
882
+ # is the window's real pixel size. Callers that want a cheaper preview pass maxDim explicitly.
883
+ $maxDim = IntArg $A 'maxDim' 0
884
+ $st = TickNow
885
+ if ($null -eq ('Native' -as [type])) { Err 'native_missing' 'the P/Invoke helper did not compile; capture is unavailable' }
886
+ $cap = [Native]::Capture([IntPtr]$entry.hwnd, $maxDim)
887
+ $r = [ordered]@{
888
+ windowId = $entry.id
889
+ method = [string]$cap.method
890
+ blank = [bool]$cap.blank
891
+ width = [int]$cap.width
892
+ height = [int]$cap.height
893
+ distinct = [int]$cap.distinct
894
+ isForeground = (Is-ForegroundHwnd $entry.hwnd)
895
+ pngBytes = 0
896
+ ms = (MsFrom $st)
897
+ }
898
+ if ($null -ne $cap.png) {
899
+ $r['pngBytes'] = $cap.png.Length
900
+ if (BoolArg $A 'inline' $true) { $r['pngBase64'] = [Convert]::ToBase64String($cap.png) }
901
+ }
902
+ # region crops the capture to a window-space box (zoom for small text). The crop happens in image
903
+ # pixels, but the reported rect stays in the caller's coordinate space, so coordinateMap keeps
904
+ # producing click/tree coordinates without the model doing region arithmetic.
905
+ $wr = RectOf (Window-Ae $entry).Current
906
+ $reg = Parse-Region $A $wr
907
+ if ($null -ne $reg -and $null -ne $cap.png -and [int]$cap.width -gt 0 -and [int]$cap.height -gt 0 -and $wr.w -gt 0 -and $wr.h -gt 0) {
908
+ $sx0 = [double]$wr.w / [double]$cap.width
909
+ $sy0 = [double]$wr.h / [double]$cap.height
910
+ $ix = [int][Math]::Max(0, [Math]::Round(([double]$reg.x - [double]$wr.x) / $sx0))
911
+ $iy = [int][Math]::Max(0, [Math]::Round(([double]$reg.y - [double]$wr.y) / $sy0))
912
+ $iw = [int][Math]::Max(1, [Math]::Min([int]$cap.width - $ix, [Math]::Round([double]$reg.w / $sx0)))
913
+ $ih = [int][Math]::Max(1, [Math]::Min([int]$cap.height - $iy, [Math]::Round([double]$reg.h / $sy0)))
914
+ $cap.png = Crop-PngBox $cap.png $ix $iy $iw $ih
915
+ $cap.width = $iw; $cap.height = $ih
916
+ $r['cropped'] = $true
917
+ $r['regionRect'] = $reg
918
+ }
919
+ $eff = if ($null -ne $reg) { $reg } else { $wr }
920
+ if ($cap.width -gt 0 -and $cap.height -gt 0 -and $eff.w -gt 0 -and $eff.h -gt 0) {
921
+ $r['windowRect'] = $eff
922
+ $r['imageWidth'] = [int]$cap.width
923
+ $r['imageHeight'] = [int]$cap.height
924
+ $r['scaleX'] = [Math]::Round([double]$eff.w / [double]$cap.width, 4)
925
+ $r['scaleY'] = [Math]::Round([double]$eff.h / [double]$cap.height, 4)
926
+ $r['coordinateMap'] = ('screenX = ' + [int]$eff.x + ' + imgX * ' + [string]$r['scaleX'] + ' ; screenY = ' + [int]$eff.y + ' + imgY * ' + [string]$r['scaleY'])
927
+ }
928
+ $note = [string]$cap.error
929
+ if ($cap.blank) { $note += ('capture came back blank (distinct colors=' + [int]$cap.distinct + '); the window is not rendering into the PrintWindow DC') }
930
+ if ($note -ne '') { $r['detail'] = (OneLine $note) }
931
+ return $r
932
+ }
933
+
934
+ function Resolve-OcrExe {
935
+ # The compiled WinRT shim. Shipped in worker\bin (7 KB, no model: Windows.Media.Ocr is an OS
936
+ # component). DSH_OCR_EXE overrides it for testing. Returns $null when absent so the caller can
937
+ # fail with a clear reason rather than a raw process error.
938
+ $p = $env:DSH_OCR_EXE
939
+ # $PSScriptRoot is worker/lib here, so the bundled OCR helper sits one level up.
940
+ if ([string]::IsNullOrEmpty($p)) { $p = Join-Path $PSScriptRoot '..\bin\ocr.exe' }
941
+ if (-not (Test-Path -LiteralPath $p)) { return $null }
942
+ return (Resolve-Path -LiteralPath $p).Path
943
+ }
944
+
945
+ function Invoke-OcrExe($exe, $pngPath) {
946
+ $psi = New-Object System.Diagnostics.ProcessStartInfo
947
+ $psi.FileName = $exe
948
+ $psi.Arguments = '"' + $pngPath + '"'
949
+ $psi.UseShellExecute = $false
950
+ $psi.RedirectStandardOutput = $true
951
+ $psi.RedirectStandardError = $true
952
+ $psi.CreateNoWindow = $true
953
+ $psi.StandardOutputEncoding = [System.Text.Encoding]::UTF8
954
+ $proc = [System.Diagnostics.Process]::Start($psi)
955
+ $stdout = $proc.StandardOutput.ReadToEnd()
956
+ $stderr = $proc.StandardError.ReadToEnd()
957
+ $proc.WaitForExit()
958
+ return @{ code = $proc.ExitCode; out = $stdout; err = $stderr }
959
+ }
960
+
961
+ function Cmd-Ocr($A) {
962
+ $st = TickNow
963
+ $entry = Window-Entry (StrArg $A 'windowId' '')
964
+ $maxDim = IntArg $A 'maxDim' 1400
965
+ $exe = Resolve-OcrExe
966
+ if ($null -eq $exe) { Err 'ocr_unavailable' 'ocr.exe not found (place it in worker\bin or set DSH_OCR_EXE)' }
967
+ $ae = Window-Ae $entry
968
+ $wr = RectOf $ae.Current
969
+ if ($wr.w -le 0 -or $wr.h -le 0) { Err 'no_rect' 'window has no usable rect (minimized?); activate/restore it first' }
970
+ $cap = [Native]::Capture([IntPtr]$entry.hwnd, $maxDim)
971
+ if ($null -eq $cap.png -or [bool]$cap.blank) {
972
+ Err 'capture_blank' ('window did not render into the capture (method=' + [string]$cap.method + ' distinct=' + [int]$cap.distinct + ')')
973
+ }
974
+ # OCR a region when asked: cropping first is what makes small text readable, because the OCR engine
975
+ # sees the pixels at full size instead of inside a 1400-px-wide window shot.
976
+ $reg = Parse-Region $A $wr
977
+ if ($null -ne $reg -and [int]$cap.width -gt 0 -and [int]$cap.height -gt 0) {
978
+ $sx0 = [double]$wr.w / [double]$cap.width
979
+ $sy0 = [double]$wr.h / [double]$cap.height
980
+ $ix = [int][Math]::Max(0, [Math]::Round(([double]$reg.x - [double]$wr.x) / $sx0))
981
+ $iy = [int][Math]::Max(0, [Math]::Round(([double]$reg.y - [double]$wr.y) / $sy0))
982
+ $iw = [int][Math]::Max(1, [Math]::Min([int]$cap.width - $ix, [Math]::Round([double]$reg.w / $sx0)))
983
+ $ih = [int][Math]::Max(1, [Math]::Min([int]$cap.height - $iy, [Math]::Round([double]$reg.h / $sy0)))
984
+ $cap.png = Crop-PngBox $cap.png $ix $iy $iw $ih
985
+ $wr = $reg
986
+ }
987
+ $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ('yuping-ocr-' + $PID + '-' + (Get-Random) + '.png')
988
+ [System.IO.File]::WriteAllBytes($tmp, $cap.png)
989
+ $imgW = [int]$cap.width; $imgH = [int]$cap.height
990
+ $r = Invoke-OcrExe $exe $tmp
991
+ try { Remove-Item -LiteralPath $tmp -ErrorAction SilentlyContinue } catch { }
992
+ if ($r.code -ne 0) { Err 'ocr_failed' ('ocr.exe exit ' + [string]$r.code + ': ' + (TruncStr ([string]($r.err + $r.out)) 200)) }
993
+ $parsed = $null
994
+ try { $parsed = $r.out | ConvertFrom-Json } catch { Err 'ocr_parse' ('bad ocr json: ' + (TruncStr ([string]$r.out) 200)) }
995
+ if ($null -eq $parsed -or -not [bool]$parsed.ok) { Err 'ocr_error' (TruncStr ([string]$parsed.error) 200) }
996
+ # The capture is the whole window at its physical size (possibly downscaled to maxDim), so image
997
+ # pixels map onto the window rect by a per-axis scale; word centers become clickable screen points.
998
+ $sx = [double]$wr.w / [double]$imgW
999
+ $sy = [double]$wr.h / [double]$imgH
1000
+ $words = @()
1001
+ foreach ($wd in $parsed.words) {
1002
+ $words += [ordered]@{
1003
+ text = [string]$wd.t
1004
+ cx = [int]([double]$wr.x + (([double]$wd.x + [double]$wd.w / 2.0) * $sx))
1005
+ cy = [int]([double]$wr.y + (([double]$wd.y + [double]$wd.h / 2.0) * $sy))
1006
+ rect = [ordered]@{
1007
+ x = [int]([double]$wr.x + [double]$wd.x * $sx)
1008
+ y = [int]([double]$wr.y + [double]$wd.y * $sy)
1009
+ w = [int]([double]$wd.w * $sx)
1010
+ h = [int]([double]$wd.h * $sy)
1011
+ }
1012
+ }
1013
+ }
1014
+ return [ordered]@{
1015
+ windowId = $entry.id
1016
+ engine = 'windows-media-ocr'
1017
+ imageWidth = $imgW
1018
+ imageHeight = $imgH
1019
+ windowRect = $wr
1020
+ cropped = [bool]($null -ne $reg)
1021
+ scaleX = [Math]::Round($sx, 4)
1022
+ scaleY = [Math]::Round($sy, 4)
1023
+ text = [string]$parsed.text
1024
+ count = $words.Count
1025
+ words = $words
1026
+ ms = (MsFrom $st)
1027
+ }
1028
+ }
1029
+
1030
+ function Cmd-FindText($A) {
1031
+ $st = TickNow
1032
+ $entry = Window-Entry (StrArg $A 'windowId' '')
1033
+ $text = StrArg $A 'text' ''
1034
+ if ($text -eq '') { Err 'missing_arg' 'find_text needs text' }
1035
+ $exact = BoolArg $A 'exact' $false
1036
+ $max = IntArg $A 'max' 60
1037
+ $ae = Window-Ae $entry
1038
+ if ($null -eq $ae) { Err 'window_not_found' ("window " + $entry.id + " is gone") }
1039
+ # Scoped search: the documented rhythm "find_text INTO the container you located" had no way to
1040
+ # say which container, so every search re-enumerated the whole window (1-3 ms per element on a
1041
+ # Chromium tree). With a ref the scan starts at that element, which is both narrower and faster.
1042
+ $within = StrArg $A 'within' ''
1043
+ if ($within -ne '') {
1044
+ $reWithin = Resolve-Ref $within $null
1045
+ $ae = $reWithin.ae
1046
+ }
1047
+ # ---- cached scan: Activate a PRIVATE request (same property/pattern shape as the snapshot
1048
+ # request, incl. pattern availability + RuntimeId), so FindAll returns elements that already
1049
+ # carry their cache and the per-element loop reads $c.Cached with no per-node round-trips
1050
+ # (measured ~160 ms for a ~500-element tree vs ~650 ms of live Current reads). Deliberately a
1051
+ # SEPARATE request object (Find-CacheRequest), never the shared $script:snapReq. Mode stays Full,
1052
+ # so refs minted from these elements are still live elements and every later pattern call on
1053
+ # them works. The scope is popped before the element loop: the cache stays materialised on the
1054
+ # elements themselves. Any failure here falls back to the historical live scan below.
1055
+ $all = @()
1056
+ $usedCached = $false
1057
+ $freq = Find-CacheRequest
1058
+ if ($null -ne $freq) {
1059
+ try {
1060
+ # [void] on both Activate and Pop is load-bearing: Activate returns a CacheRequestActivation
1061
+ # marker, and a bare expression inside a function joins the function's OUTPUT STREAM — the
1062
+ # reply would then be [result, activation] and every consumer would read garbage.
1063
+ [void]$freq.Activate()
1064
+ try {
1065
+ $all = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, [System.Windows.Automation.Condition]::TrueCondition))
1066
+ # One probe decides the batch: an element without a usable cache throws on .Cached, and
1067
+ # then everything is re-enumerated through the live path below.
1068
+ if ($all.Count -gt 0) { $null = $all[0].Cached; $usedCached = $true }
1069
+ } finally {
1070
+ try { [void]$freq.Pop() } catch { }
1071
+ }
1072
+ } catch { $usedCached = $false }
1073
+ }
1074
+ if (-not $usedCached) {
1075
+ try { $all = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, [System.Windows.Automation.Condition]::TrueCondition)) } catch { Err 'uia_error' ('FindAll threw: ' + $_.Exception.Message) }
1076
+ }
1077
+ $out = New-Object System.Collections.Generic.List[object]
1078
+ # How many times each (name, controlType) pair has been emitted so far. A `by` descriptor is
1079
+ # resolved later by FindFirst, which always returns the first match — so without this, a window
1080
+ # with three "复制" buttons can only ever reach the first one and the model's second/third pick
1081
+ # silently lands on the wrong control ("点不准" with perfect coordinates). Carrying `nth` in the
1082
+ # descriptor makes each match individually addressable.
1083
+ $seen = @{}
1084
+ $matchedTotal = 0
1085
+ $truncated = $false
1086
+ foreach ($c in $all) {
1087
+ # Same per-element guard as before, but a timeout no longer DISCARDS the command: every hit
1088
+ # already collected is still true, so the partial list returns marked truncated (the old
1089
+ # deadline_exceeded error threw away all of it — the model paid for a full scan and got
1090
+ # nothing back).
1091
+ if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) { $truncated = $true; break }
1092
+ try { $cp = if ($usedCached) { $c.Cached } else { $c.Current } } catch { continue }
1093
+ $n = [string]$cp.Name
1094
+ $ctn = ''
1095
+ if ($n -eq '') {
1096
+ # A nameless Edit/Document/Text can still carry the text the caller is after (a label-less
1097
+ # input box's content lives in its value, not its name). This used to read $cp.Value — a
1098
+ # property AutomationElementInformation does not HAVE — so it silently returned '' forever
1099
+ # and the documented value search never fired. Read the value from ValuePattern, for that
1100
+ # narrow type set only, so the extra pattern call stays rare on container-heavy trees.
1101
+ try { $ctn = ControlTypeName $cp.ControlType } catch { $ctn = '' }
1102
+ if ($ctn -eq 'Edit' -or $ctn -eq 'Document' -or $ctn -eq 'Text') {
1103
+ try {
1104
+ $vp = $c.GetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern)
1105
+ if ($null -ne $vp) { $n = [string]$vp.Current.Value }
1106
+ } catch { $n = '' }
1107
+ }
1108
+ }
1109
+ if ($n.Length -eq 0) { continue }
1110
+ # Literal, case-insensitive containment. -like treated * ? [ ] in the caller's text as
1111
+ # wildcards, so searching for a name containing brackets matched unrelated controls.
1112
+ $m = if ($exact) { $n.Equals($text, [StringComparison]::OrdinalIgnoreCase) } else { $n.IndexOf($text, [StringComparison]::OrdinalIgnoreCase) -ge 0 }
1113
+ if (-not $m) { continue }
1114
+ # The honest hit total, INCLUDING everything past max: the scan already walked the tree, so
1115
+ # counting the tail costs one Name read per remaining element and turns the silent drop into
1116
+ # a reported truncation (matchedTotal > count ⇔ the reply must say so).
1117
+ $matchedTotal += 1
1118
+ if ($out.Count -ge $max) { $truncated = $true; continue }
1119
+ $rc = RectOf $cp
1120
+ if ($ctn -eq '') { $ctn = ControlTypeName $cp.ControlType }
1121
+ $key = $ctn + '#' + $n
1122
+ $nth = 1
1123
+ if ($seen.ContainsKey($key)) { $nth = $seen[$key] + 1 }
1124
+ $seen[$key] = $nth
1125
+ # The descriptor must be able to RESOLVE later, so it is built from the real identity, never
1126
+ # from the display text: a name cut at 160 chars could never satisfy an exact match, and a
1127
+ # non-empty AutomationId is a stable anchor when the visible label changes or repeats.
1128
+ $selName = $n
1129
+ $pats = @()
1130
+ try { $pats = PatternsOf $c } catch { $pats = @() }
1131
+ $node = [ordered]@{
1132
+ controlType = $ctn
1133
+ name = (TruncStr $n 160)
1134
+ className = [string]$cp.ClassName
1135
+ automationId = [string]$cp.AutomationId
1136
+ patterns = @($pats)
1137
+ enabled = [bool]$cp.IsEnabled
1138
+ isOffscreen = [bool]$cp.IsOffscreen
1139
+ rect = $rc
1140
+ depth = 0
1141
+ }
1142
+ # Same convention the snapshot uses: when the node's 160-cut display name differs from the
1143
+ # real one, carry the untruncated name so a recipe can re-resolve it strictly.
1144
+ if ($n.Length -gt 160) { $node['fullName'] = $n }
1145
+ $byDesc = @{ controlType = $ctn }
1146
+ if ($selName.Length -gt 200) {
1147
+ $byDesc['name'] = $selName.Substring(0, 200)
1148
+ $byDesc['nameExact'] = $false
1149
+ } else {
1150
+ $byDesc['name'] = $selName
1151
+ }
1152
+ if ([string]$node.automationId -ne '') { $byDesc['automationId'] = [string]$node.automationId }
1153
+ if ($nth -gt 1) { $byDesc['nth'] = $nth }
1154
+ # Issue a ref for every hit. find_text used to return only coordinates and a by-descriptor, so
1155
+ # computer_act (which takes a ref and nothing else) could not be driven from a search result —
1156
+ # the model had to fall back to a physical computer_click, moving the real cursor for what
1157
+ # should have been a background action. Refs cost one table entry each and make the two tools
1158
+ # compose.
1159
+ $refRec = $null
1160
+ try { $refRec = New-Ref $entry $c $cp $node } catch { $refRec = $null }
1161
+ # The item reads back what the node already holds — className/automationId/enabled/isOffscreen
1162
+ # were each read TWICE before (once for $node, once for $item), one avoidable round-trip each.
1163
+ $item = [ordered]@{
1164
+ name = $node.name
1165
+ controlType = $ctn
1166
+ className = $node.className
1167
+ automationId = $node.automationId
1168
+ rect = $rc
1169
+ enabled = $node.enabled
1170
+ isOffscreen = $node.isOffscreen
1171
+ patterns = $node.patterns
1172
+ ref = $(if ($null -ne $refRec) { $refRec.ref } else { $null })
1173
+ center = @{ x = ($rc.x + [int]($rc.w / 2)); y = ($rc.y + [int]($rc.h / 2)) }
1174
+ # nth is only meaningful once a duplicate exists; a unique hit keeps the old 1-field shape
1175
+ # and nth=1 so recipes saved before this change still replay against the same element.
1176
+ nth = $nth
1177
+ by = $byDesc
1178
+ }
1179
+ $out.Add($item) | Out-Null
1180
+ }
1181
+ $r = [ordered]@{ windowId = $entry.id; revision = $entry.revision; text = $text; matches = $out; count = $out.Count; scanned = $all.Count; matchedTotal = $matchedTotal; truncated = [bool]$truncated; ms = (MsFrom $st) }
1182
+ if ($within -ne '') { $r['within'] = $within }
1183
+ # Position metadata, same contract as snapshot's: advisory fields, omitted on failure.
1184
+ try {
1185
+ $obsHeader = Window-ObservationHeader $entry
1186
+ if ($null -ne $obsHeader) {
1187
+ foreach ($k in @($obsHeader.Keys)) { $r[$k] = $obsHeader[$k] }
1188
+ }
1189
+ } catch { }
1190
+ return $r
1191
+ }
1192
+
1193
+ function Resolve-LaunchTarget($app) {
1194
+ $info = @{ path = ''; via = '' }
1195
+ if ($null -eq $app -or [string]$app -eq '') { Err 'missing_arg' 'launch needs app, uri or msAppAlias' }
1196
+ $app = [string]$app
1197
+ if ($app -match '[\\/]' -and (Test-Path -LiteralPath $app)) {
1198
+ $info.path = (Resolve-Path -LiteralPath $app).Path
1199
+ $info.via = 'literal-path'
1200
+ return $info
1201
+ }
1202
+ $names = @($app)
1203
+ if ($app -notmatch '\.(exe|com)$') { $names = @(($app + '.exe'), $app) }
1204
+ $win = $env:SystemRoot
1205
+ foreach ($n in $names) {
1206
+ foreach ($dir in @(($win + '\System32'), ($win + '\SysWOW64'), $win)) {
1207
+ $f = Join-Path $dir $n
1208
+ if (Test-Path -LiteralPath $f -PathType Leaf) { $info.path = $f; $info.via = 'windows-dir'; return $info }
1209
+ }
1210
+ $wa = Join-Path $env:LOCALAPPDATA ('Microsoft\WindowsApps\' + $n)
1211
+ if (Test-Path -LiteralPath $wa) { $info.path = $wa; $info.via = 'app-execution-alias'; return $info }
1212
+ foreach ($hive in @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths')) {
1213
+ $key = $hive + '\' + $n
1214
+ if (Test-Path -LiteralPath $key) {
1215
+ $v = (Get-ItemProperty -LiteralPath $key -ErrorAction SilentlyContinue).'(default)'
1216
+ if ($null -ne $v -and [string]$v -ne '' -and (Test-Path -LiteralPath ([string]$v))) { $info.path = [string]$v; $info.via = 'app-paths-registry'; return $info }
1217
+ }
1218
+ }
1219
+ }
1220
+ # PATH, but only real Windows executables. Git's usr/bin ships POSIX scripts named
1221
+ # like windows tools; ShellExecute on those opens an editor instead of the tool.
1222
+ foreach ($n in $names) {
1223
+ foreach ($dir in ($env:PATH -split ';')) {
1224
+ if ($dir -eq '') { continue }
1225
+ if ($dir -match '(?i)\\git\\|\\usr\\bin|\\bin\\sh|\\msys|\\cygwin|\\busybox') { continue }
1226
+ $f = Join-Path $dir $n
1227
+ if (Test-Path -LiteralPath $f -PathType Leaf) {
1228
+ $it = Get-Item -LiteralPath $f
1229
+ if ($it.Extension -eq '.exe' -or $it.Extension -eq '.com') { $info.path = $it.FullName; $info.via = 'path'; return $info }
1230
+ }
1231
+ }
1232
+ }
1233
+ $roots = @(($env:APPDATA + '\Microsoft\Windows\Start Menu\Programs'), ($env:ProgramData + '\Microsoft\Windows\Start Menu\Programs')) | Where-Object { Test-Path -LiteralPath $_ }
1234
+ foreach ($n in $names) {
1235
+ $stem = ($n -replace '\.(exe|com)$', '')
1236
+ $lnk = Get-ChildItem -LiteralPath $roots[0] -Recurse -Filter '*.lnk' -ErrorAction SilentlyContinue | Where-Object { $_.BaseName -replace ' & ', '' -match ('(?i)^' + [regex]::Escape($stem) + '$') } | Select-Object -First 1
1237
+ if ($null -eq $lnk -and $roots.Count -gt 1) {
1238
+ $lnk = Get-ChildItem -LiteralPath $roots[1] -Recurse -Filter '*.lnk' -ErrorAction SilentlyContinue | Where-Object { $_.BaseName -replace ' & ', '' -match ('(?i)^' + [regex]::Escape($stem) + '$') } | Select-Object -First 1
1239
+ }
1240
+ if ($null -ne $lnk) { $info.path = $lnk.FullName; $info.via = 'start-menu'; return $info }
1241
+ }
1242
+ Err 'launch_failed' ("cannot resolve '" + $app + "' through windows-dir, app-execution-alias, app-paths, PATH or start-menu")
1243
+ }
1244
+
1245
+ function Cmd-Launch($A) {
1246
+ $app = StrArg $A 'app' ''
1247
+ $alias = StrArg $A 'msAppAlias' ''
1248
+ $uri = StrArg $A 'uri' ''
1249
+ $timeoutMs = IntArg $A 'timeoutMs' 8000
1250
+ $argList = ListOf (ArgOf $A 'args')
1251
+ $titleFilter = StrArg $A 'title' ''
1252
+ $classFilter = StrArg $A 'class' ''
1253
+ if ($app -eq '' -and $alias -eq '' -and $uri -eq '') { Err 'missing_arg' 'launch needs app, msAppAlias or uri' }
1254
+ # app accepts protocol URIs too (for example microsoft.windows.camera:). A drive
1255
+ # prefix, including drive-relative C:foo, is a Windows path rather than a URI scheme.
1256
+ if ($uri -eq '' -and $alias -eq '' -and $app -match '^[A-Za-z][A-Za-z0-9+.-]*:' -and $app -notmatch '^[A-Za-z]:') { $uri = $app }
1257
+ $exe = ''; $via = ''
1258
+ $st = TickNow
1259
+ if ($uri -ne '') { $exe = $uri; $via = 'uri-shell' }
1260
+ elseif ($alias -ne '') { $r = Resolve-LaunchTarget $alias; $exe = $r.path; $via = 'ms-app-alias:' + $r.via }
1261
+ else { $r = Resolve-LaunchTarget $app; $exe = $r.path; $via = $r.via }
1262
+ $argline = ''
1263
+ foreach ($a in $argList) {
1264
+ $sa = [string]$a
1265
+ if ($sa -match '[\s"]') { $argline += ' "' + $sa.Replace('"', '\"') + '"' } else { $argline += ' ' + $sa }
1266
+ }
1267
+ $argline = $argline.Trim()
1268
+ $beforePids = @{}
1269
+ foreach ($pr in [System.Diagnostics.Process]::GetProcesses()) { try { $beforePids[[string]$pr.Id] = 1 } catch { } }
1270
+ $beforeHwnds = @{}
1271
+ $beforeTitle = @{}
1272
+ foreach ($w in (RootWindows)) {
1273
+ $cp = $null
1274
+ try { $cp = $w.Current; $bh = [int]$cp.NativeWindowHandle } catch { continue }
1275
+ if ($bh -eq 0) { continue }
1276
+ $beforeHwnds[[string]$bh] = 1
1277
+ $beforeTitle[[string]$bh] = ([string]$cp.Name).ToLowerInvariant()
1278
+ }
1279
+ # Optional title/appName hint. On Windows 11 `notepad` is a store alias and the real
1280
+ # editor is a SINGLE process that owns every open document: launching a file folds it
1281
+ # into a window that already existed, so neither a new pid nor a new hwnd appears -- the
1282
+ # only observable event is that window's TITLE changing to mention our file. Deriving the
1283
+ # hint from the file argument's basename (never from the app name) is what lets us resolve
1284
+ # our own document without ever matching a foreign document (e.g. CARVE-*.md) in the same
1285
+ # process. An explicit title/appName always wins.
1286
+ $hint = ''
1287
+ foreach ($tok in @($titleFilter)) {
1288
+ $t = [string]$tok
1289
+ if ($t -ne '') { $hint = $t.ToLowerInvariant(); break }
1290
+ }
1291
+ if ($hint -eq '') {
1292
+ foreach ($a in $argList) {
1293
+ $sa = [string]$a
1294
+ if ($sa -match '[\\/]' -or $sa -match '\.[A-Za-z0-9]{1,8}$') {
1295
+ $base = ($sa -replace '[\\/]+$', '')
1296
+ $base = $base -replace '^.*[\\/]', ''
1297
+ $base = $base -replace '\.[A-Za-z0-9]{1,8}$', ''
1298
+ if ($base.Length -ge 3) { $hint = $base.ToLowerInvariant(); break }
1299
+ }
1300
+ }
1301
+ }
1302
+ $launchedPid = 0
1303
+ try {
1304
+ $pi = New-Object System.Diagnostics.ProcessStartInfo
1305
+ $pi.FileName = $exe
1306
+ $pi.Arguments = $argline
1307
+ $pi.UseShellExecute = $true
1308
+ $cwd = StrArg $A 'cwd' ''
1309
+ if ($cwd -ne '') { $pi.WorkingDirectory = $cwd }
1310
+ $proc = [System.Diagnostics.Process]::Start($pi)
1311
+ if ($null -ne $proc) { $launchedPid = $proc.Id }
1312
+ } catch {
1313
+ Err 'launch_failed' ("Process.Start('" + $exe + "') threw: " + $_.Exception.Message)
1314
+ }
1315
+ $left = BudgetLeftMs
1316
+ $budget = $timeoutMs
1317
+ if ($budget -gt $left) { $budget = [int]$left }
1318
+ if ($budget -lt 200) { $budget = 200 }
1319
+ $deadline = (TickNow) + ([Int64]$budget * 10000)
1320
+ $foundEntry = $null
1321
+ $matchedBy = ''
1322
+ $foundPidNew = $false
1323
+ $fallbackEntry = $null
1324
+ $fallbackBy = ''
1325
+ $fallbackPidNew = $false
1326
+ while ($true) {
1327
+ Test-Deadline 'launch'
1328
+ foreach ($w in (RootWindows)) {
1329
+ $hwnd = 0; $cp = $null
1330
+ try { $cp = $w.Current; $hwnd = [int]$cp.NativeWindowHandle } catch { continue }
1331
+ if ($hwnd -eq 0) { continue }
1332
+ $hk = [string]$hwnd
1333
+ $isNew = -not $beforeHwnds.ContainsKey($hk)
1334
+ $p = [int]$cp.ProcessId
1335
+ $isPidNew = ($launchedPid -ne 0 -and $p -eq $launchedPid) -or (-not $beforePids.ContainsKey([string]$p))
1336
+ $tNow = ([string]$cp.Name).ToLowerInvariant()
1337
+ $titleChanged = ($beforeTitle.ContainsKey($hk) -and ($beforeTitle[$hk] -ne $tNow))
1338
+ $hintHit = ($hint -ne '' -and $tNow.Contains($hint))
1339
+ # A STRONG candidate is a top-level window that appeared after the start timestamp
1340
+ # (new hwnd or new owner pid -- the store-alias handoff) OR the window whose title
1341
+ # changed to mention our file after the start timestamp (Win11 single-process tab reuse).
1342
+ # A WEAK candidate is a visible top-level window that already carries our hint; it is only
1343
+ # used after the full budget, so a genuinely new window still wins over a stale same-named one.
1344
+ $strong = ($isNew -or $isPidNew) -or ($titleChanged -and $hintHit)
1345
+ $weak = ($hintHit -and -not $isNew -and -not $isPidNew -and -not $titleChanged)
1346
+ if (-not $strong -and -not $weak) { continue }
1347
+ # When we have a discriminator hint, even a new window must belong to it -- that is what
1348
+ # keeps an unrelated popup (or another document in the same process) from being grabbed.
1349
+ if ($hint -ne '' -and -not $hintHit) { continue }
1350
+ $rc = RectOf $cp
1351
+ $iconic = $false
1352
+ try { $iconic = [Native]::IsIconic([IntPtr]$hwnd) } catch { }
1353
+ if (($rc.w -lt 40 -or $rc.h -lt 40) -and -not $iconic) { continue }
1354
+ if ($titleFilter -ne '' -and ([string]$tNow).IndexOf($titleFilter, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
1355
+ if ($classFilter -ne '' -and ([string]$cp.ClassName).IndexOf($classFilter, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
1356
+ $e = Ensure-Window $hwnd $w
1357
+ if ($null -eq $e) { continue }
1358
+ if ($strong) {
1359
+ $foundEntry = $e
1360
+ if ($p -eq $launchedPid) { $matchedBy = 'launched-pid' }
1361
+ elseif ($isPidNew -and -not $isNew) { $matchedBy = 'new-pid-handoff' }
1362
+ elseif ($isNew) { $matchedBy = 'new-hwnd' }
1363
+ else { $matchedBy = 'title-change-handoff' }
1364
+ $foundPidNew = $isPidNew
1365
+ break
1366
+ } elseif ($null -eq $fallbackEntry) {
1367
+ $fallbackEntry = $e; $fallbackBy = 'title-hint-reuse'; $fallbackPidNew = $isPidNew
1368
+ }
1369
+ }
1370
+ if ($null -ne $foundEntry) { break }
1371
+ if ((TickNow) -ge $deadline) { break }
1372
+ Start-Sleep -Milliseconds 150
1373
+ }
1374
+ if ($null -eq $foundEntry -and $null -ne $fallbackEntry) {
1375
+ $foundEntry = $fallbackEntry; $matchedBy = $fallbackBy; $foundPidNew = $fallbackPidNew
1376
+ }
1377
+ if ($null -eq $foundEntry) {
1378
+ $script:W.stats.refused += 1
1379
+ Err 'window_not_found' ("launched " + $exe + " (pid " + $launchedPid + ") but no matching new window appeared within " + $budget + 'ms')
1380
+ }
1381
+ $ae = Window-Ae $foundEntry
1382
+ $cp2 = $ae.Current
1383
+ # The plugin may only claim ownership of a window it actually created. When the owning
1384
+ # process already existed before this launch (the Win11 single-process hand-off), that same
1385
+ # process also hosts the user's other documents, so returning its pid would let a later
1386
+ # policy check treat those documents as ours and close them. In that case report the
1387
+ # launcher pid instead -- disjoint from the window owner -- so policy keeps treating the
1388
+ # window as foreign and it must be closed explicitly. Only a brand-new owner pid is claimed.
1389
+ $ownerPid = [int]$foundEntry.pid
1390
+ $claimPid = if ($foundPidNew) { $ownerPid } else { $launchedPid }
1391
+ return [ordered]@{
1392
+ pid = $claimPid
1393
+ ownerPid = $ownerPid
1394
+ windowId = $foundEntry.id
1395
+ title = (TruncStr ([string]$cp2.Name) 200)
1396
+ class = [string]$cp2.ClassName
1397
+ appearedMs = [Math]::Round((MsFrom $st), 1)
1398
+ launchedPid = $launchedPid
1399
+ matchedBy = $matchedBy
1400
+ exe = $exe
1401
+ via = $via
1402
+ revision = $foundEntry.revision
1403
+ }
1404
+ }
1405
+
1406
+ function Remove-Window($entry) {
1407
+ $refs = @()
1408
+ foreach ($snap in $entry.snapshots) { $refs += $snap.refs }
1409
+ foreach ($rk in $refs) {
1410
+ $r = $script:W.refs.Item($rk)
1411
+ if ($null -ne $r) {
1412
+ # No Marshal.ReleaseComObject here: managed UIA elements are not COM objects
1413
+ # (IsComObject(AutomationElement::RootElement) is False), so the call always threw and an
1414
+ # empty catch swallowed it. GC reclaims the wrappers once the last reference drops.
1415
+ $r.ae = $null
1416
+ $script:W.refs.Remove($rk) | Out-Null
1417
+ }
1418
+ $i = $script:W.refOrder.IndexOf($rk)
1419
+ if ($i -ge 0) { $script:W.refOrder.RemoveAt($i) }
1420
+ $script:W.totalRefs -= 1
1421
+ }
1422
+ $entry.snapshots.Clear()
1423
+ $script:W.winByHwnd.Remove([string]$entry.hwnd) | Out-Null
1424
+ $script:W.windows.Remove($entry.id) | Out-Null
1425
+ }
1426
+
1427
+ function Cmd-CloseWindow($A) {
1428
+ $entry = Window-Entry (StrArg $A 'windowId' '')
1429
+ $timeoutMs = IntArg $A 'timeoutMs' 3000
1430
+ $method = ''
1431
+ $ae = Window-Ae $entry
1432
+ if ($null -eq $ae) {
1433
+ Remove-Window $entry
1434
+ return [ordered]@{ windowId = $entry.id; closed = $true; method = 'already-gone' }
1435
+ }
1436
+ $wp = GetPattern $ae 'Window'
1437
+ if ($null -ne $wp) {
1438
+ try { $wp.Close(); $method = 'windowpattern' } catch { $method = 'windowpattern-threw' }
1439
+ }
1440
+ if ($method -eq '') {
1441
+ try {
1442
+ [void][Native]::PostMessageW([IntPtr]$entry.hwnd, 0x0010, [IntPtr]0, [IntPtr]0)
1443
+ $method = 'postmessage-wm_close'
1444
+ } catch { Err 'action_failed' ('PostMessage WM_CLOSE threw: ' + $_.Exception.Message) }
1445
+ }
1446
+ $st = TickNow
1447
+ $left = BudgetLeftMs
1448
+ $budget = $timeoutMs
1449
+ if ($budget -gt $left) { $budget = [int]$left }
1450
+ $gone = $false
1451
+ $dialogs = New-Object System.Collections.Generic.List[object]
1452
+ while ((TickNow) -lt ($st + ([Int64]$budget * 10000))) {
1453
+ $alive = $false
1454
+ foreach ($w in (RootWindows)) {
1455
+ $h = 0
1456
+ try { $cp = $w.Current; $h = [int]$cp.NativeWindowHandle } catch { continue }
1457
+ if ($h -eq $entry.hwnd) { $alive = $true; continue }
1458
+ if ([int]$cp.ProcessId -eq $entry.pid) {
1459
+ $cn = [string]$cp.ClassName
1460
+ if ($cn -eq '#32770' -or $cn -like '*Dialog*' -or $cn -like '*XamlWindow*') {
1461
+ $known = $false
1462
+ foreach ($d in $dialogs) { if ($d.hwnd -eq $h) { $known = $true } }
1463
+ if (-not $known) {
1464
+ $de = Ensure-Window $h $w
1465
+ $dialogs.Add([ordered]@{ windowId = $de.id; hwnd = $h; class = $cn; title = (TruncStr ([string]$cp.Name) 120) }) | Out-Null
1466
+ }
1467
+ }
1468
+ }
1469
+ }
1470
+ if (-not $alive) { $gone = $true; break }
1471
+ Start-Sleep -Milliseconds 120
1472
+ }
1473
+ $r = [ordered]@{
1474
+ windowId = $entry.id
1475
+ method = $method
1476
+ closed = $gone
1477
+ pidStillRunning = $false
1478
+ waitedMs = (MsFrom $st)
1479
+ dialogAppeared = ($dialogs.Count -gt 0)
1480
+ }
1481
+ if (-not $gone) {
1482
+ try { $null = [System.Diagnostics.Process]::GetProcessById($entry.pid); $r['pidStillRunning'] = $true } catch { }
1483
+ if ($dialogs.Count -gt 0) {
1484
+ $r['dialogs'] = $dialogs
1485
+ $r['detail'] = 'a modal dialog is blocking the close; resolve it with find_text + act (the worker never clicks on its own)'
1486
+ } else {
1487
+ $r['detail'] = 'the window ignored the close request'
1488
+ }
1489
+ } else {
1490
+ Remove-Window $entry
1491
+ }
1492
+ return $r
1493
+ }
1494
+
1495
+