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,64 @@
1
+ # 01-core.ps1 -- framing/io helpers, deadlines
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
+ # ---------------------------------------------------------------- framing / io
8
+ $script:utf8NoBom = New-Object System.Text.UTF8Encoding($false)
9
+ try {
10
+ [Console]::InputEncoding = $script:utf8NoBom
11
+ [Console]::OutputEncoding = $script:utf8NoBom
12
+ } catch { }
13
+
14
+ # The stdio JSON helpers (Esc/JsonOf/OneLine/Err/ArgOf/IntArg/StrArg/BoolArg/Dict/
15
+ # Split-Err) are shared verbatim with indicator-server.ps1 via ps-stdio.ps1; the
16
+ # escaping contract ("absent vs null" fields, 7-bit clean pipe) is documented there.
17
+ # Send-Ok/Send-Err stay here: they write $script:W.stats, which is worker-owned.
18
+ # $PSScriptRoot here is worker/lib, not worker/: the shared framing lives one level up.
19
+ . (Join-Path $PSScriptRoot '..\ps-stdio.ps1')
20
+
21
+ function Send-Ok($id, $result) {
22
+ $script:W.stats.commands += 1
23
+ $r = [ordered]@{ id = $id; ok = $true }
24
+ if ($null -ne $result) { $r['result'] = $result }
25
+ $r['stats'] = $script:W.stats
26
+ [Console]::Out.Write((JsonOf $r))
27
+ [Console]::Out.Write("`n")
28
+ [Console]::Out.Flush()
29
+ }
30
+
31
+ function Send-Err($id, $code, $message) {
32
+ $script:W.stats.commands += 1
33
+ $script:W.stats.refused += 1
34
+ $r = [ordered]@{ id = $id; ok = $false; code = [string]$code; error = (OneLine $message) }
35
+ $r['stats'] = $script:W.stats
36
+ [Console]::Out.Write((JsonOf $r))
37
+ [Console]::Out.Write("`n")
38
+ [Console]::Out.Flush()
39
+ }
40
+
41
+ function ListOf($o) {
42
+ if ($null -eq $o) { return @() }
43
+ if ($o -is [System.Collections.IEnumerable] -and -not ($o -is [string])) { return @($o) }
44
+ return @($o)
45
+ }
46
+
47
+ # deadline helpers -------------------------------------------------------------
48
+ function TickNow { return [Diagnostics.Stopwatch]::GetTimestamp() }
49
+ function MsFrom($startTick) { return [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $startTick) / 10000.0, 1) }
50
+ function Set-Deadline($ms) {
51
+ if ($ms -le 0) { $script:W.dl = [Int64]::MaxValue } else { $script:W.dl = (TickNow) + ([Int64]$ms * 10000) }
52
+ }
53
+ function Test-Deadline($what) {
54
+ if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) {
55
+ Err 'deadline_exceeded' ("budget exhausted during " + $what)
56
+ }
57
+ }
58
+ function BudgetLeftMs {
59
+ if ($script:W.dl -eq [Int64]::MaxValue) { return 9.0E+14 }
60
+ $left = ($script:W.dl - (TickNow)) / 10000.0
61
+ if ($left -lt 0) { return 0 }
62
+ return [Math]::Round($left, 1)
63
+ }
64
+
@@ -0,0 +1,224 @@
1
+ # 02-uia.ps1 -- UIA plumbing: patterns, rects, process names
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
+ # ---------------------------------------------------------------- uiA plumbing
8
+ $script:ctCache = @{}
9
+ function ControlTypeName($ct) {
10
+ if ($null -eq $ct) { return 'Unknown' }
11
+ $key = $null
12
+ try { $key = $ct.Id } catch { }
13
+ # Some providers return a partial ControlType with no Id. Hashtable.Item(null) throws,
14
+ # and unknown types must not poison the shared cache for later, healthy nodes.
15
+ if ($null -ne $key -and $script:ctCache.ContainsKey($key)) { return $script:ctCache[$key] }
16
+ $n = ''
17
+ try { $n = [string]$ct.ProgrammaticName } catch { }
18
+ if ($n -ne '') { $n = ($n -split '\.')[-1] }
19
+ if ([string]::IsNullOrEmpty($n)) { return 'Unknown' }
20
+ if ($null -ne $key) { $script:ctCache[$key] = $n }
21
+ return $n
22
+ }
23
+
24
+ $script:patCache = @{}
25
+ # GetSupportedPatterns() returns AutomationPattern objects (NOT AutomationPatternInfo): the
26
+ # usable name is $q.ProgrammaticName, shaped "ValuePatternIdentifiers.Pattern"; $q.Id is a bare
27
+ # int (10002) and has no ProgrammaticName, so reading $q.Id.ProgrammaticName yields '' and every
28
+ # node used to report an empty pattern list.
29
+ #
30
+ # The COM call itself cannot be avoided (78% of nodes in a real tree are interactive, so filtering
31
+ # by type saves nothing), but the string work after it can: the same control type yields the same
32
+ # pattern set, and a 300-node tree is mostly repeats of a handful of types. Caching by the pattern
33
+ # signature keeps the per-node cost at the one round-trip instead of round-trip + regex + dedupe.
34
+ $script:patSetCache = @{}
35
+ function PatternsOf($el) {
36
+ # Cached elements (snapshot subtree / find_text scan) build the list from the cached
37
+ # availability with no cross-process round-trip; anything without a usable cache keeps the
38
+ # live GetSupportedPatterns path below (the fallback is reserved for cache-read failures, and
39
+ # the mock/test harnesses stub this whole function out).
40
+ try {
41
+ $cached = Cached-PatternsOf $el
42
+ if ($null -ne $cached) { return ,$cached }
43
+ } catch { }
44
+ $names = @()
45
+ try {
46
+ $sp = $el.GetSupportedPatterns()
47
+ if ($null -ne $sp) {
48
+ # Build the signature cheaply, then look the friendly list up once per distinct signature.
49
+ # Every value that reaches a Hashtable key or a List[string] is normalised to a non-empty
50
+ # string first: a provider that reports a pattern with no ProgrammaticName and no Id used to
51
+ # put $null into both, and Hashtable indexing with $null throws "Key cannot be null" — which
52
+ # surfaced as a whole snapshot failing with internal_error.
53
+ $sigParts = New-Object System.Collections.Generic.List[string]
54
+ foreach ($q in $sp) {
55
+ $pk = ''
56
+ try { $pk = [string]$q.ProgrammaticName } catch { $pk = '' }
57
+ if ([string]::IsNullOrEmpty($pk)) {
58
+ $qid = -1
59
+ try { $qid = [int]$q.Id } catch { $qid = -1 }
60
+ $pk = 'id:' + $qid
61
+ }
62
+ $sigParts.Add($pk) | Out-Null
63
+ }
64
+ $sig = ($sigParts | Sort-Object) -join '|'
65
+ if ($sig -ne '') {
66
+ $hit = $script:patSetCache[$sig]
67
+ if ($null -ne $hit) { return ,$hit }
68
+ }
69
+ foreach ($pk in $sigParts) {
70
+ if ([string]::IsNullOrEmpty($pk)) { continue }
71
+ $friendly = $null
72
+ if ($script:patCache.ContainsKey($pk)) { $friendly = $script:patCache[$pk] }
73
+ if ($null -eq $friendly) {
74
+ if ($pk -match '^(.*?)PatternIdentifiers\.Pattern$') {
75
+ $friendly = $matches[1]
76
+ } else {
77
+ $n = ($pk -split '\.')[-1]
78
+ $n = $n -replace 'Pattern$', ''
79
+ $n = $n -replace 'Identifiers$', ''
80
+ $friendly = $n
81
+ }
82
+ if ([string]::IsNullOrEmpty($friendly)) { continue }
83
+ $script:patCache[$pk] = $friendly
84
+ }
85
+ if ($friendly -ne '' -and ($names -notcontains $friendly)) { $names += $friendly }
86
+ }
87
+ # Remember this exact pattern set for the next node that has the same one. Bounded: a
88
+ # long-lived worker walking many windows must not grow this without limit.
89
+ if ($sig -ne '' -and $script:patSetCache.Count -lt 512) { $script:patSetCache[$sig] = $names }
90
+ }
91
+ } catch { }
92
+ return ,$names
93
+ }
94
+
95
+ # The pattern list of a CACHED element (one that came back from GetUpdatedCache or from a walker
96
+ # request overload): built from the cached Is*PatternAvailable properties — zero cross-process
97
+ # calls. Returns $null when the element carries no usable cache (a live element throws on
98
+ # GetCachedPropertyValue), which is the caller's signal to fall back to the live
99
+ # GetSupportedPatterns path. Every Is*PatternAvailableProperty the managed client has IS cached
100
+ # (probe-verified: all exist; IsLegacyIAccessiblePatternAvailableProperty does not — there is no
101
+ # managed wrapper type for that pattern, so it can neither be requested nor reported here, and
102
+ # LegacyIAccessible is deliberately absent from a cached pattern list: the capability table
103
+ # computer_act checks never names it and the rendered tree filters patterns
104
+ # through ACTIONABLE, which never showed it either).
105
+ $script:cachedPatProps = @(
106
+ 'IsDockPatternAvailableProperty', 'IsExpandCollapsePatternAvailableProperty', 'IsGridItemPatternAvailableProperty',
107
+ 'IsGridPatternAvailableProperty', 'IsInvokePatternAvailableProperty', 'IsItemContainerPatternAvailableProperty',
108
+ 'IsMultipleViewPatternAvailableProperty', 'IsRangeValuePatternAvailableProperty', 'IsScrollItemPatternAvailableProperty',
109
+ 'IsScrollPatternAvailableProperty', 'IsSelectionItemPatternAvailableProperty', 'IsSelectionPatternAvailableProperty',
110
+ 'IsTableItemPatternAvailableProperty', 'IsTablePatternAvailableProperty', 'IsTextPatternAvailableProperty',
111
+ 'IsTogglePatternAvailableProperty', 'IsTransformPatternAvailableProperty', 'IsValuePatternAvailableProperty',
112
+ 'IsWindowPatternAvailableProperty'
113
+ )
114
+ function Cached-PatternsOf($el) {
115
+ if ($null -eq $el) { return $null }
116
+ $names = @()
117
+ $any = $false
118
+ foreach ($p in $script:cachedPatProps) {
119
+ $v = $null
120
+ try { $v = $el.GetCachedPropertyValue([System.Windows.Automation.AutomationElement]::$p) } catch { return $null }
121
+ $any = $true
122
+ if ($v -is [bool] -and $v) {
123
+ $n = ([string]$p) -replace '^Is', '' -replace 'PatternAvailableProperty$', ''
124
+ if ($n -ne '' -and ($names -notcontains $n)) { $names += $n }
125
+ }
126
+ }
127
+ if (-not $any) { return $null }
128
+ return $names
129
+ }
130
+
131
+ $patternTypes = @{
132
+ Invoke = [System.Windows.Automation.InvokePattern]
133
+ Value = [System.Windows.Automation.ValuePattern]
134
+ Toggle = [System.Windows.Automation.TogglePattern]
135
+ SelectionItem = [System.Windows.Automation.SelectionItemPattern]
136
+ ExpandCollapse = [System.Windows.Automation.ExpandCollapsePattern]
137
+ Scroll = [System.Windows.Automation.ScrollPattern]
138
+ RangeValue = [System.Windows.Automation.RangeValuePattern]
139
+ Window = [System.Windows.Automation.WindowPattern]
140
+ Transform = [System.Windows.Automation.TransformPattern]
141
+ Text = [System.Windows.Automation.TextPattern]
142
+ GridItem = [System.Windows.Automation.GridItemPattern]
143
+ # ScrollItem only became useful with the scroll_to verb; before that its absence was invisible
144
+ # (nothing asked for it) and adding it would have been a dead table entry.
145
+ ScrollItem = [System.Windows.Automation.ScrollItemPattern]
146
+ }
147
+
148
+ function GetPattern($el, $name) {
149
+ if (-not $patternTypes.ContainsKey($name)) { return $null }
150
+ try {
151
+ $p = $el.GetCurrentPattern($patternTypes[$name]::Pattern)
152
+ if ($null -eq $p) { return $null }
153
+ return $p
154
+ } catch { return $null }
155
+ }
156
+
157
+ # Same lookup as GetPattern, but the pattern OBJECT is kept on the ref record. The act sequence
158
+ # before → action → after used to call GetCurrentPattern for the SAME pattern three times (three
159
+ # cross-process round-trips for one set_value). Invalidated by Resolve-Ref on rebind, because the
160
+ # cached object is bound to the element it was fetched from.
161
+ function Get-RefPattern($re, $name) {
162
+ if ($null -eq $re) { return $null }
163
+ if ($null -eq $re.patCache) { $re.patCache = @{} }
164
+ if ($re.patCache.ContainsKey($name)) { return $re.patCache[$name] }
165
+ $p = GetPattern $re.ae $name
166
+ $re.patCache[$name] = $p
167
+ return $p
168
+ }
169
+
170
+ function RectOf($cp) {
171
+ try {
172
+ $r = $cp.BoundingRectangle
173
+ if ($null -eq $r -or [double]::IsNaN($r.X) -or [double]::IsNaN($r.Width)) { return @{ x = 0; y = 0; w = 0; h = 0 } }
174
+ # an empty WPF-style Rect comes back as X=Infinity / Width=-Infinity; [int] on that throws
175
+ if ([double]::IsInfinity($r.X) -or [double]::IsInfinity($r.Width) -or [double]::IsInfinity($r.Height) -or [double]::IsInfinity($r.Y)) {
176
+ return @{ x = 0; y = 0; w = 0; h = 0 }
177
+ }
178
+ if ($r.Width -le 0 -or $r.Height -le 0) { return @{ x = [int]$r.X; y = [int]$r.Y; w = 0; h = 0 } }
179
+ return @{ x = [int]$r.X; y = [int]$r.Y; w = [int]$r.Width; h = [int]$r.Height }
180
+ } catch { return @{ x = 0; y = 0; w = 0; h = 0 } }
181
+ }
182
+
183
+ function RuntimeIdKey($el) {
184
+ # Cached elements (snapshot subtree / find_text scan) read the runtime id from the cache —
185
+ # probe-verified bit-identical to GetRuntimeId() on real trees (the old comment here claimed the
186
+ # managed cache returns an empty array for RuntimeIdProperty; that was a probe artifact and did
187
+ # not reproduce on Chromium or Explorer windows, live request or GetUpdatedCache). A live element
188
+ # (or a provider that never cached it) keeps the live call below; both shapes land in the same
189
+ # comma-joined string, so the rebind identity check does not change meaning.
190
+ try {
191
+ $rid = $el.GetCachedPropertyValue([System.Windows.Automation.AutomationElement]::RuntimeIdProperty)
192
+ if ($null -ne $rid) { return (($rid | ForEach-Object { [string]$_ }) -join ',') }
193
+ } catch { }
194
+ try {
195
+ $rid = $el.GetRuntimeId()
196
+ if ($null -eq $rid) { return '' }
197
+ return (($rid | ForEach-Object { [string]$_ }) -join ',')
198
+ } catch { return '' }
199
+ }
200
+
201
+ function RootWindows {
202
+ $root = [System.Windows.Automation.AutomationElement]::RootElement
203
+ return @($root.FindAll([System.Windows.Automation.TreeScope]::Children, [System.Windows.Automation.Condition]::TrueCondition))
204
+ }
205
+
206
+ function TruncStr([string]$s, $max) {
207
+ if ($null -eq $s) { return '' }
208
+ if ($s.Length -le $max) { return $s }
209
+ return $s.Substring(0, $max) + '~'
210
+ }
211
+
212
+ function ProcNameOf($procId) {
213
+ $k = [string]$procId
214
+ if ($script:W.procNames.ContainsKey($k)) { return $script:W.procNames[$k] }
215
+ $n = ''
216
+ try { $n = [Native]::ProcName([int]$procId) } catch { }
217
+ if ($n -eq '') {
218
+ try { $p = Get-Process -Id ([int]$procId) -ErrorAction SilentlyContinue; if ($null -ne $p) { $n = [string]$p.ProcessName } } catch { }
219
+ }
220
+ $script:W.procNames[$k] = $n
221
+ return $n
222
+ }
223
+
224
+
@@ -0,0 +1,194 @@
1
+ # 03-window.ps1 -- window registry and ref table
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
+ # ---------------------------------------------------------------- window registry
8
+ function Ensure-Window($hwnd, $aeHint) {
9
+ $hk = [string]$hwnd
10
+ $existing = $script:W.winByHwnd.Item($hk)
11
+ if ($null -ne $existing) {
12
+ $e = $script:W.windows.Item($existing)
13
+ if ($null -ne $e) { return $e }
14
+ }
15
+ $ae = $aeHint
16
+ if ($null -eq $ae) {
17
+ try { $ae = [System.Windows.Automation.AutomationElement]::FromHandle([IntPtr]$hwnd) } catch { $ae = $null }
18
+ }
19
+ if ($null -eq $ae) { return $null }
20
+ try { $cp = $ae.Current } catch { return $null }
21
+ $script:W.winSeq += 1
22
+ $id = 'w' + $script:W.winSeq
23
+ $entry = @{
24
+ id = $id
25
+ hwnd = [int]$hwnd
26
+ pid = [int]$cp.ProcessId
27
+ class = [string]$cp.ClassName
28
+ revision = 0
29
+ snapshots = New-Object System.Collections.Generic.List[object]
30
+ lastSeen = (TickNow)
31
+ }
32
+ $script:W.windows[$id] = $entry
33
+ $script:W.winByHwnd[$hk] = $id
34
+ return $entry
35
+ }
36
+
37
+ function Window-Ae($entry) {
38
+ try {
39
+ $ae = [System.Windows.Automation.AutomationElement]::FromHandle([IntPtr]$entry.hwnd)
40
+ if ($null -eq $ae) { return $null }
41
+ $null = $ae.Current.Name
42
+ return $ae
43
+ } catch { return $null }
44
+ }
45
+
46
+
47
+ function Window-Entry($windowId) {
48
+ if ($null -eq $windowId -or [string]$windowId -eq '') { Err 'missing_arg' 'windowId is required' }
49
+ $e = $script:W.windows.Item([string]$windowId)
50
+ if ($null -eq $e) { Err 'unknown_window' ("no such windowId: " + $windowId + '; call list_windows or resolve_window first') }
51
+ return $e
52
+ }
53
+
54
+ function WindowInfo($entry, $cp) {
55
+ $rc = RectOf $cp
56
+ $fg = $false
57
+ try { $fg = ([Native]::GetForegroundWindow() -eq [IntPtr]$entry.hwnd) } catch { }
58
+ # Minimized matters to the caller: a minimized window has no usable screen rect, so stale
59
+ # snapshot coordinates point at nothing and pixel actions must not fire before a restore.
60
+ $iconic = $false
61
+ try { $iconic = [Native]::IsIconic([IntPtr]$entry.hwnd) } catch { }
62
+ return @{
63
+ windowId = $entry.id
64
+ pid = $entry.pid
65
+ appName = (ProcNameOf $entry.pid)
66
+ title = (TruncStr ([string]$cp.Name) 200)
67
+ class = [string]$cp.ClassName
68
+ hwnd = $entry.hwnd
69
+ rect = $rc
70
+ isForeground = $fg
71
+ isMinimized = $iconic
72
+ revision = $entry.revision
73
+ }
74
+ }
75
+
76
+ # Read-only position metadata for an observation result (snapshot / find_text): which window is
77
+ # foreground RIGHT NOW, where the UIA focus sits, and whether that focus lives inside the observed
78
+ # window (pid comparison — advisory only; a multi-process host can misreport "not in this window").
79
+ # The next observation after a click/type then carries free proof of whether the action took
80
+ # effect: the focus moved into (or out of) the target window. Every probe is try/catch-guarded —
81
+ # a failure just omits the field and must never fail the observation it decorates. FocusedElement
82
+ # can also be slow against elevated/UAC windows, so the focus probe is bounded by the request
83
+ # budget as well: a soft skip (no field), never a throw inside an observation.
84
+ function Window-ObservationHeader($entry) {
85
+ $obs = @{}
86
+ $fgHwnd = [IntPtr]::Zero
87
+ try { $fgHwnd = [Native]::GetForegroundWindow() } catch { }
88
+ if ($fgHwnd -ne [IntPtr]::Zero) {
89
+ try {
90
+ $fgPid = 0
91
+ try { [void][Native]::GetWindowThreadProcessId($fgHwnd, [ref]$fgPid) } catch { }
92
+ $fg = [ordered]@{
93
+ title = (TruncStr ([Native]::TitleOf($fgHwnd)) 200)
94
+ class = (TruncStr ([Native]::ClassOf($fgHwnd)) 120)
95
+ pid = [int]$fgPid
96
+ app = $(if ($fgPid -gt 0) { ProcNameOf ([int]$fgPid) } else { '' })
97
+ isTarget = $false
98
+ }
99
+ try { $fg['isTarget'] = ($fgHwnd -eq [IntPtr]$entry.hwnd) } catch { }
100
+ $obs['foreground'] = $fg
101
+ } catch { }
102
+ }
103
+ try {
104
+ if ((BudgetLeftMs) -gt 150) {
105
+ $fe = $null
106
+ try { $fe = [System.Windows.Automation.AutomationElement]::FocusedElement } catch { $fe = $null }
107
+ if ($null -ne $fe) {
108
+ $fcp = $fe.Current
109
+ $obs['focus'] = [ordered]@{
110
+ controlType = (ControlTypeName $fcp.ControlType)
111
+ name = (TruncStr ([string]$fcp.Name) 120)
112
+ pid = [int]$fcp.ProcessId
113
+ app = (ProcNameOf ([int]$fcp.ProcessId))
114
+ }
115
+ try { $obs['focusInWindow'] = ([int]$fcp.ProcessId -eq [int]$entry.pid) } catch { }
116
+ }
117
+ }
118
+ } catch { }
119
+ return $obs
120
+ }
121
+
122
+ # ---------------------------------------------------------------- ref table
123
+ function New-Ref($entry, $ae, $cp, $node) {
124
+ $script:W.refSeq += 1
125
+ $ref = 'e' + $script:W.refSeq
126
+ $re = @{
127
+ ref = $ref
128
+ windowId = $entry.id
129
+ hwnd = $entry.hwnd
130
+ revision = $entry.revision
131
+ ae = $ae
132
+ runtimeId = (RuntimeIdKey $ae)
133
+ controlType = $node.controlType
134
+ name = $node.name
135
+ className = $node.className
136
+ fullName = $node.fullName
137
+ automationId = $node.automationId
138
+ patterns = $node.patterns
139
+ enabled = $node.enabled
140
+ isOffscreen = $node.isOffscreen
141
+ rect = $node.rect
142
+ depth = $node.depth
143
+ rebound = $false
144
+ patCache = @{}
145
+ }
146
+ $script:W.refs[$ref] = $re
147
+ $script:W.refOrder.Add($ref)
148
+ $script:W.totalRefs += 1
149
+ if ($entry.snapshots.Count -gt 0) {
150
+ $entry.snapshots[$entry.snapshots.Count - 1].refs.Add($ref)
151
+ }
152
+ return $re
153
+ }
154
+
155
+ function Evict-ForReservation($needed) {
156
+ $evicted = @()
157
+ $guard = 0
158
+ while ($script:W.totalRefs + $needed -gt $script:W.maxRefs -and $guard -lt 400) {
159
+ $guard += 1
160
+ $victim = $null; $victimWin = $null
161
+ foreach ($wid in @($script:W.windows.Keys)) {
162
+ $e = $script:W.windows[$wid]
163
+ if ($null -eq $e.snapshots -or $e.snapshots.Count -le 1) { continue }
164
+ $cand = $e.snapshots[0]
165
+ if ($null -eq $victim -or $cand.createdTick -lt $victim.createdTick) { $victim = $cand; $victimWin = $e }
166
+ }
167
+ if ($null -eq $victim) { break }
168
+ $count = $victim.refs.Count
169
+ foreach ($rk in $victim.refs) {
170
+ # .Item($null) throws "Key cannot be null" and used to abort the whole snapshot with
171
+ # internal_error, because a ref list can hold an entry that never became a string key.
172
+ if ([string]::IsNullOrEmpty([string]$rk)) { continue }
173
+ $r = $null
174
+ if ($script:W.refs.ContainsKey($rk)) { $r = $script:W.refs[$rk] }
175
+ if ($null -ne $r) {
176
+ # Managed UIA elements are plain .NET objects (IsComObject(AutomationElement::RootElement)
177
+ # is False), so Marshal.ReleaseComObject always threw here and the empty catch swallowed
178
+ # it — a guaranteed-failing call that misled readers into seeing resource release. The
179
+ # wrappers are reclaimed by GC; dropping the last reference is the cleanup.
180
+ $r.ae = $null
181
+ $script:W.refs.Remove($rk) | Out-Null
182
+ }
183
+ $i = $script:W.refOrder.IndexOf($rk)
184
+ if ($i -ge 0) { $script:W.refOrder.RemoveAt($i) }
185
+ }
186
+ $victimWin.snapshots.RemoveAt(0)
187
+ $script:W.totalRefs -= $count
188
+ $script:W.stats.evictions += 1
189
+ $evicted += @{ windowId = $victimWin.id; revision = $victim.revision; refs = $count }
190
+ }
191
+ return ,$evicted
192
+ }
193
+
194
+