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,254 @@
1
+ # 05-value.ps1 -- value/state reads and descriptor projection
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
+ # ---------------------------------------------------------------- values
8
+ # Reads one value-bearing property from the element's CACHE (GetCachedPattern + pattern.Cached).
9
+ # Returns $null when the pattern is not usable (not in the cache, provider refused) so the caller
10
+ # falls back to the live pattern lookup. Only Read-Value's SNAPSHOT path calls this: the whole
11
+ # subtree's pattern objects were already materialised by the cache request, so the reading costs
12
+ # no cross-process round-trip. The act/wait/verify path never calls it — a verify must read the
13
+ # value as it is NOW, not as it was when the tree was materialised.
14
+ function Cached-ValueOf($el, $name) {
15
+ if ($null -eq $el) { return $null }
16
+ if (-not $patternTypes.ContainsKey($name)) { return $null }
17
+ try {
18
+ $p = $el.GetCachedPattern($patternTypes[$name]::Pattern)
19
+ if ($null -eq $p) { return $null }
20
+ switch ($name) {
21
+ 'Value' { return [string]$p.Cached.Value }
22
+ 'RangeValue' { return [string]$p.Cached.Value }
23
+ 'Toggle' { return [string]$p.Cached.ToggleState }
24
+ 'ExpandCollapse' { return [string]$p.Cached.ExpandCollapseState }
25
+ }
26
+ } catch { }
27
+ return $null
28
+ }
29
+
30
+ function Read-Value($el, $patterns, $refRec, $useCached) {
31
+ # $refRec, when given, routes the pattern fetch through the ref's pattern cache (Get-RefPattern):
32
+ # the act before→action→after sequence then fetches each pattern ONCE instead of three times.
33
+ # Callers without a ref record keep the plain lookup. $useCached marks the SNAPSHOT path: the
34
+ # value then comes from the element's cache (Cached-ValueOf) and only a failed cached read falls
35
+ # back to the live pattern for that one node.
36
+ if ($null -ne $patterns -and $patterns -contains 'Value') {
37
+ $v = $null
38
+ if ($useCached) { $v = Cached-ValueOf $el 'Value' }
39
+ if ($null -ne $v) { return $v }
40
+ $vp = if ($null -ne $refRec) { Get-RefPattern $refRec 'Value' } else { GetPattern $el 'Value' }
41
+ if ($null -ne $vp) { try { return [string]$vp.Current.Value } catch { } }
42
+ }
43
+ if ($null -ne $patterns -and $patterns -contains 'RangeValue') {
44
+ $v = $null
45
+ if ($useCached) { $v = Cached-ValueOf $el 'RangeValue' }
46
+ if ($null -ne $v) { return $v }
47
+ $rp = if ($null -ne $refRec) { Get-RefPattern $refRec 'RangeValue' } else { GetPattern $el 'RangeValue' }
48
+ if ($null -ne $rp) { try { return [string]$rp.Current.Value } catch { } }
49
+ }
50
+ if ($null -ne $patterns -and $patterns -contains 'Toggle') {
51
+ $v = $null
52
+ if ($useCached) { $v = Cached-ValueOf $el 'Toggle' }
53
+ if ($null -ne $v) { return $v }
54
+ $tp = if ($null -ne $refRec) { Get-RefPattern $refRec 'Toggle' } else { GetPattern $el 'Toggle' }
55
+ if ($null -ne $tp) { try { return [string]$tp.Current.ToggleState } catch { } }
56
+ }
57
+ if ($null -ne $patterns -and $patterns -contains 'ExpandCollapse') {
58
+ $v = $null
59
+ if ($useCached) { $v = Cached-ValueOf $el 'ExpandCollapse' }
60
+ if ($null -ne $v) { return $v }
61
+ $ep = if ($null -ne $refRec) { Get-RefPattern $refRec 'ExpandCollapse' } else { GetPattern $el 'ExpandCollapse' }
62
+ if ($null -ne $ep) { try { return [string]$ep.Current.ExpandCollapseState } catch { } }
63
+ }
64
+ # No LegacyIAccessible branch here: the managed UIAutomationClient has no
65
+ # System.Windows.Automation.LegacyIAccessiblePattern type, so GetPattern could never return one
66
+ # and this read was unreachable (the pattern name only appears in PatternsOf's report of what the
67
+ # PROVIDER exposes, never in what this client can obtain).
68
+ if ($null -ne $patterns -and $patterns -contains 'Text') {
69
+ $tx = GetPattern $el 'Text'
70
+ if ($null -ne $tx) { try { return [string]$tx.DocumentRange.GetText(200) } catch { } }
71
+ }
72
+ return ''
73
+ }
74
+
75
+ # ---------------------------------------------------------------- node state
76
+ # A snapshot used to hand the model ONE string per node (`value`), so every state-bearing control
77
+ # read the same: an unchecked checkbox and a checked one both said "Toggle", a selected tab said
78
+ # nothing, an expanded tree node said nothing, a slider at 40% said 40 without its range, and a
79
+ # scrolled list said nothing at all. The model then had to guess or drive blind.
80
+ #
81
+ # $useCached reads the state out of the CacheRequest the snapshot already materialised (no
82
+ # cross-process round-trip). Some providers — Explorer's shell items, several MSAA-bridged apps —
83
+ # answer the pattern lookup and then hand back an EMPTY cached struct; for those the caller may
84
+ # retry this function with $useCached=$false ONCE per node, which is a real round-trip and is
85
+ # therefore budgeted by the snapshot (see Build-SnapshotNode), not spent freely.
86
+ # Did the cached read leave a state we KNOW is readable on the table? Called before spending the
87
+ # one budgeted live read per node. Scroll is deliberately absent: a list that cannot scroll reports
88
+ # NoScroll on both axes and legitimately produces no `scroll` key, so demanding one would burn the
89
+ # whole budget on unscrollable nodes.
90
+ function State-Missing($patterns, $st) {
91
+ if ($null -eq $patterns -or $patterns.Count -eq 0) { return $false }
92
+ $want = @(
93
+ @{ pattern = 'Toggle'; key = 'toggle' },
94
+ @{ pattern = 'SelectionItem'; key = 'selected' },
95
+ @{ pattern = 'ExpandCollapse'; key = 'expanded' },
96
+ @{ pattern = 'RangeValue'; key = 'range' }
97
+ )
98
+ foreach ($w in $want) {
99
+ if ($patterns -contains $w.pattern) {
100
+ if ($null -eq $st -or -not $st.Contains($w.key)) { return $true }
101
+ }
102
+ }
103
+ return $false
104
+ }
105
+
106
+ function Get-StatePattern($el, $type, $useCached) {
107
+ if ($null -eq $el) { return $null }
108
+ try {
109
+ if ($useCached) { return $el.GetCachedPattern($type) }
110
+ return $el.GetCurrentPattern($type)
111
+ } catch { return $null }
112
+ }
113
+
114
+ function State-Of($el, $patterns, $useCached) {
115
+ if ($null -eq $el -or $null -eq $patterns -or $patterns.Count -eq 0) { return $null }
116
+ $st = [ordered]@{}
117
+ if ($patterns -contains 'Toggle') {
118
+ $c = $null
119
+ $p = Get-StatePattern $el ([System.Windows.Automation.TogglePattern]::Pattern) $useCached
120
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
121
+ if ($null -ne $c) {
122
+ # A provider can answer the lookup and still refuse the struct: the field then reads as '',
123
+ # and publishing `"expanded": ""` is worse than publishing nothing — it looks like a state
124
+ # called empty.
125
+ $sv = ''
126
+ try { $sv = [string]$c.ToggleState } catch { }
127
+ if ($sv -ne '') { $st['toggle'] = $sv }
128
+ }
129
+ }
130
+ if ($patterns -contains 'SelectionItem') {
131
+ $c = $null
132
+ $p = Get-StatePattern $el ([System.Windows.Automation.SelectionItemPattern]::Pattern) $useCached
133
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
134
+ if ($null -ne $c) { try { $st['selected'] = [bool]$c.IsSelected } catch { } }
135
+ }
136
+ if ($patterns -contains 'ExpandCollapse') {
137
+ $c = $null
138
+ $p = Get-StatePattern $el ([System.Windows.Automation.ExpandCollapsePattern]::Pattern) $useCached
139
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
140
+ if ($null -ne $c) {
141
+ $sv = ''
142
+ try { $sv = [string]$c.ExpandCollapseState } catch { }
143
+ if ($sv -ne '') { $st['expanded'] = $sv }
144
+ }
145
+ }
146
+ if ($patterns -contains 'RangeValue') {
147
+ $c = $null
148
+ $p = Get-StatePattern $el ([System.Windows.Automation.RangeValuePattern]::Pattern) $useCached
149
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
150
+ if ($null -ne $c) {
151
+ # Minimum/Maximum are what turn "40" into "40 of 0..100" — without them the model cannot tell
152
+ # a slider at 40% from one pinned at its floor.
153
+ $rv = [double]$c.Value
154
+ if (-not [double]::IsNaN($rv)) {
155
+ $st['range'] = @{ value = $rv; min = [double]$c.Minimum; max = [double]$c.Maximum }
156
+ }
157
+ }
158
+ }
159
+ if ($patterns -contains 'Scroll') {
160
+ $c = $null
161
+ $p = Get-StatePattern $el ([System.Windows.Automation.ScrollPattern]::Pattern) $useCached
162
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
163
+ if ($null -ne $c) {
164
+ $h = [double]$c.HorizontalScrollPercent
165
+ $v = [double]$c.VerticalScrollPercent
166
+ # -1 is ScrollPattern.NoScroll: an axis that cannot move is a fact worth keeping only when the
167
+ # other axis can.
168
+ if ($h -ge 0 -or $v -ge 0) {
169
+ $st['scroll'] = @{
170
+ h = $(if ($h -ge 0) { [Math]::Round($h, 0) } else { -1 })
171
+ v = $(if ($v -ge 0) { [Math]::Round($v, 0) } else { -1 })
172
+ }
173
+ }
174
+ }
175
+ }
176
+ if ($st.Count -eq 0) { return $null }
177
+ return $st
178
+ }
179
+
180
+ function SupportedActionOf($patterns) {
181
+ if ($null -eq $patterns) { return 'focus' }
182
+ if ($patterns -contains 'Invoke') { return 'invoke' }
183
+ if ($patterns -contains 'Toggle') { return 'toggle' }
184
+ if ($patterns -contains 'SelectionItem') { return 'select' }
185
+ if ($patterns -contains 'ExpandCollapse') { return 'expand' }
186
+ if ($patterns -contains 'Value') { return 'set_value' }
187
+ if ($patterns -contains 'Scroll') { return 'scroll_down' }
188
+ # LegacyIAccessible is NOT actionable from the managed UIA client (there is no
189
+ # System.Windows.Automation.LegacyIAccessiblePattern type in UIAutomationClient), so it is
190
+ # reported but never advertised as an action.
191
+ return 'focus'
192
+ }
193
+
194
+ function DescriptorOf($re, $live) {
195
+ $cp = $null
196
+ $patterns = $re.patterns
197
+ $name = $re.name
198
+ # The UNtruncated name, when the snapshot recorded one: a saved recipe needs it because a
199
+ # 160-cut name with '~' can never satisfy a strict re-match (F: recipe save quality).
200
+ $full = ''
201
+ if ($re.ContainsKey('fullName')) { $full = [string]$re.fullName }
202
+ $enabled = $re.enabled
203
+ $off = $re.isOffscreen
204
+ $rect = $re.rect
205
+ if ($live) {
206
+ try { $cp = $re.ae.Current } catch { $cp = $null }
207
+ if ($null -ne $cp) {
208
+ $name = [string]$cp.Name
209
+ $full = $name
210
+ $enabled = [bool]$cp.IsEnabled
211
+ $off = [bool]$cp.IsOffscreen
212
+ $rect = RectOf $cp
213
+ $p2 = PatternsOf $re.ae
214
+ if ($null -ne $p2 -and $p2.Count -gt 0) { $patterns = $p2 }
215
+ }
216
+ }
217
+ $d = [ordered]@{
218
+ ref = $re.ref
219
+ windowId = $re.windowId
220
+ revision = $re.revision
221
+ name = (TruncStr ([string]$name) 160)
222
+ controlType = $re.controlType
223
+ className = $re.className
224
+ automationId = $re.automationId
225
+ availablePatterns = @($patterns)
226
+ supportedAction = (SupportedActionOf $patterns)
227
+ enabled = $enabled
228
+ isOffscreen = $off
229
+ rect = $rect
230
+ depth = $re.depth
231
+ runtimeId = $re.runtimeId
232
+ }
233
+ # Attach only when truncation actually happened, so the common short-name descriptor keeps the
234
+ # old wire shape and no caller can mistake fullName for an always-present field.
235
+ if ($full -ne '' -and $full -ne [string]$d['name']) { $d['fullName'] = $full }
236
+ if ($live -and $null -ne $cp) {
237
+ $v = Read-Value $re.ae $patterns
238
+ if ($v -ne '') {
239
+ $d['value'] = (TruncStr $v 200)
240
+ if ($v.Length -gt 200) { $d['valueTruncated'] = $true }
241
+ }
242
+ }
243
+ # Attach the owning window so a saved recipe can rebind to it later. src/tools/defs/act.js reads
244
+ # descriptors[0].ownerWindow to populate recipe.window; without it the recipe falls back to
245
+ # the store's window list, which is empty for a batch taken before any computer_windows call,
246
+ # and the recipe then replays with no windowId.
247
+ $we = $script:W.windows.Item([string]$re.windowId)
248
+ if ($null -ne $we) {
249
+ $d['ownerWindow'] = [ordered]@{ windowId = $re.windowId; hwnd = $we.hwnd; pid = $we.pid; revision = $we.revision }
250
+ }
251
+ return $d
252
+ }
253
+
254
+
@@ -0,0 +1,412 @@
1
+ # 06-snapshot.ps1 -- snapshot walker and node building
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
+ # ---------------------------------------------------------------- snapshot
8
+ # One CacheRequest shared by every snapshot walk, handed to the walker's cached overloads
9
+ # (GetFirstChild/GetNextSibling with a request — reflection-confirmed overloads) and, at Subtree
10
+ # scope, to the one-shot GetUpdatedCache path. The request carries the seven properties the node
11
+ # builder reads, PLUS RuntimeIdProperty (probe-verified bit-identical to GetRuntimeId() on real
12
+ # trees — the old "cache returns an empty array" note was a probe artifact and did not reproduce),
13
+ # PLUS every Is*PatternAvailableProperty the managed client has (19 exist; there is no managed
14
+ # LegacyIAccessible availability property, so a cached pattern list never names it — accepted
15
+ # shrink, see Cached-PatternsOf), PLUS the four value-bearing pattern objects Read-Value's
16
+ # snapshot path reads from the cache. AutomationElementMode stays Full so refs minted from cached
17
+ # elements remain usable for live pattern calls later (invoke/set_value read patterns through the
18
+ # same element).
19
+ $script:snapReq = $null
20
+ $script:subTreeReq = $null
21
+ $script:findReq = $null
22
+ $script:snapProps = @(
23
+ 'NameProperty', 'ClassNameProperty', 'ControlTypeProperty', 'AutomationIdProperty',
24
+ 'IsEnabledProperty', 'IsOffscreenProperty', 'BoundingRectangleProperty', 'RuntimeIdProperty',
25
+ 'IsDockPatternAvailableProperty', 'IsExpandCollapsePatternAvailableProperty', 'IsGridItemPatternAvailableProperty',
26
+ 'IsGridPatternAvailableProperty', 'IsInvokePatternAvailableProperty', 'IsItemContainerPatternAvailableProperty',
27
+ 'IsMultipleViewPatternAvailableProperty', 'IsRangeValuePatternAvailableProperty', 'IsScrollItemPatternAvailableProperty',
28
+ 'IsScrollPatternAvailableProperty', 'IsSelectionItemPatternAvailableProperty', 'IsSelectionPatternAvailableProperty',
29
+ 'IsTableItemPatternAvailableProperty', 'IsTablePatternAvailableProperty', 'IsTextPatternAvailableProperty',
30
+ 'IsTogglePatternAvailableProperty', 'IsTransformPatternAvailableProperty', 'IsValuePatternAvailableProperty',
31
+ 'IsWindowPatternAvailableProperty'
32
+ )
33
+ $script:snapPatterns = @(
34
+ [System.Windows.Automation.ValuePattern]::Pattern,
35
+ [System.Windows.Automation.TogglePattern]::Pattern,
36
+ [System.Windows.Automation.RangeValuePattern]::Pattern,
37
+ [System.Windows.Automation.ExpandCollapsePattern]::Pattern,
38
+ # SelectionItem and Scroll are here for STATE, not for values: without their cached objects a
39
+ # node can only say "I support selection", never "I am the selected one" or "this list sits at
40
+ # 35%". Two extra pattern objects per cached element are cheap next to the property set.
41
+ [System.Windows.Automation.SelectionItemPattern]::Pattern,
42
+ [System.Windows.Automation.ScrollPattern]::Pattern
43
+ )
44
+ function New-SnapshotCacheRequest($scope) {
45
+ $req = New-Object System.Windows.Automation.CacheRequest
46
+ $req.TreeScope = $scope
47
+ $req.AutomationElementMode = [System.Windows.Automation.AutomationElementMode]::Full
48
+ foreach ($p in $script:snapProps) {
49
+ $req.Add([System.Windows.Automation.AutomationElement]::$p)
50
+ }
51
+ foreach ($pat in $script:snapPatterns) {
52
+ $req.Add($pat)
53
+ }
54
+ return $req
55
+ }
56
+ function Snapshot-CacheRequest {
57
+ if ($null -eq $script:snapReq) {
58
+ try {
59
+ $script:snapReq = New-SnapshotCacheRequest ([System.Windows.Automation.TreeScope]::Element)
60
+ } catch {
61
+ Log ('CacheRequest build failed, snapshot falls back to live reads: ' + $_.Exception.Message)
62
+ }
63
+ }
64
+ return $script:snapReq
65
+ }
66
+ function Subtree-CacheRequest {
67
+ # One-shot path: the same property list at TreeScope=Subtree. GetUpdatedCache(Subtree)
68
+ # materialises the WHOLE subtree in one cross-process call (measured 0.10-0.16 ms/node vs
69
+ # ~1.5 ms/node for the Activate+FindAll shape and ~4.4 ms/node for the per-child walker).
70
+ # Kept as its own request object so the walker fallback never changes scope under it.
71
+ if ($null -eq $script:subTreeReq) {
72
+ try {
73
+ $script:subTreeReq = New-SnapshotCacheRequest ([System.Windows.Automation.TreeScope]::Subtree)
74
+ } catch {
75
+ Log ('subtree CacheRequest build failed, snapshot falls back to the walker: ' + $_.Exception.Message)
76
+ }
77
+ }
78
+ return $script:subTreeReq
79
+ }
80
+ function Find-CacheRequest {
81
+ # find_text's own request object — deliberately NOT the shared $script:snapReq: the two callers
82
+ # must not fight over one request (find_text activates and pops within one command, and a
83
+ # snapshot in flight on the same thread would see its scope changed under it).
84
+ if ($null -eq $script:findReq) {
85
+ try {
86
+ $script:findReq = New-SnapshotCacheRequest ([System.Windows.Automation.TreeScope]::Element)
87
+ } catch {
88
+ Log ('find_text CacheRequest build failed, find_text falls back to live reads: ' + $_.Exception.Message)
89
+ }
90
+ }
91
+ return $script:findReq
92
+ }
93
+
94
+ # The walker used by the snapshot fallback path. One indirection so the test harness can walk a
95
+ # mock tree through the SAME code path (regression-worker.ps1 redefines this and feeds a mock
96
+ # walker); production always gets the ControlViewWalker by default.
97
+ #
98
+ # `view` is the one real breadth lever UIA offers: ControlView is the curated tree providers
99
+ # publish for assistive tech, RawView is EVERY element including the plumbing panes that ControlView
100
+ # hides (in a Chromium/Electron window that is often 3-10x more nodes), ContentView keeps only
101
+ # content elements. A tree that "stops at a Pane with nothing inside" is usually a ControlView
102
+ # answer, and switching to raw is how the model gets past it.
103
+ function Get-SnapshotWalker($view) {
104
+ switch ($view) {
105
+ 'raw' { return [System.Windows.Automation.TreeWalker]::RawViewWalker }
106
+ 'content' { return [System.Windows.Automation.TreeWalker]::ContentViewWalker }
107
+ default { return [System.Windows.Automation.TreeWalker]::ControlViewWalker }
108
+ }
109
+ }
110
+
111
+ # Builds ONE snapshot node (shared by the one-shot subtree path and the walker fallback): the emit
112
+ # filter, the node fields, the ref minting and the value read all live here, so the two paths
113
+ # cannot drift. $ctx is the shared mutable state hashtable (a script-scope function cannot see
114
+ # Build-Snapshot's locals). A per-node provider failure records nodeProviderError and lets the
115
+ # walk continue — the per-node fault-tolerance contract is unchanged.
116
+ function Build-SnapshotNode($el, $depth, $cp, $ctx) {
117
+ try {
118
+ $ctx.visited += 1
119
+ # Hoist each cross-process property read once; Current/Cached does not cache these reads.
120
+ $ctRaw = $cp.ControlType
121
+ $nm = [string]$cp.Name
122
+ $cls = [string]$cp.ClassName
123
+ $off = [bool]$cp.IsOffscreen
124
+ $ctn = ControlTypeName $ctRaw
125
+ $emit = $true
126
+ if ($ctx.fCtSet.Count -gt 0 -and -not $ctx.fCtSet.ContainsKey($ctn)) { $emit = $false }
127
+ # Literal, case-insensitive containment: -like treats * ? [ ] in a caller's text as
128
+ # wildcards, so a control whose name really contains brackets matched the wrong things.
129
+ if ($ctx.fClass -ne '' -and $cls.IndexOf($ctx.fClass, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $emit = $false }
130
+ if ($ctx.fName -ne '' -and $nm.IndexOf($ctx.fName, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $emit = $false }
131
+ if (-not $ctx.incOff -and $off -and $depth -gt 0) { $emit = $false }
132
+ $patterns = @()
133
+ if ($emit) {
134
+ if ($ctx.wantPatterns) { $patterns = PatternsOf $el }
135
+ $aid = [string]$cp.AutomationId
136
+ $enabled = [bool]$cp.IsEnabled
137
+ $rc = RectOf $cp
138
+ $node = [ordered]@{
139
+ ref = ('e' + ($script:W.refSeq + 1))
140
+ controlType = $ctn
141
+ name = (TruncStr $nm 160)
142
+ className = $cls
143
+ automationId = $aid
144
+ depth = $depth
145
+ patterns = @($patterns)
146
+ enabled = $enabled
147
+ isOffscreen = $off
148
+ rect = $rc
149
+ }
150
+ # Only when truncation happened: the untruncated name a saved recipe needs to re-resolve
151
+ # later (a 160-cut name with '~' can never satisfy a strict match). Short names carry no
152
+ # extra field, so the wire shape stays unchanged for the 99% case.
153
+ if ($nm.Length -gt 160) { $node['fullName'] = $nm }
154
+ if ($ctx.wantValues -and -not $off) {
155
+ $v = Read-Value $el $patterns $null $true
156
+ if ($v -ne '') {
157
+ $node['value'] = (TruncStr $v 200)
158
+ if ($v.Length -gt 200) { $node['valueTruncated'] = $true }
159
+ }
160
+ }
161
+ # State is what makes a tree answerable: "which row is selected", "is it expanded", "how far
162
+ # is the slider". The cached read is local; providers that hand back an empty cached struct
163
+ # (Explorer's shell items among them) get ONE live read, budgeted for the whole snapshot so a
164
+ # bridged window cannot turn state into hundreds of cross-process calls.
165
+ if ($ctx.wantState) {
166
+ $st = $null
167
+ try { $st = State-Of $el $patterns $true } catch { $st = $null }
168
+ if ($ctx.stateLiveBudget -gt 0 -and (State-Missing $patterns $st)) {
169
+ $ctx.stateLiveBudget -= 1
170
+ $st2 = $null
171
+ try { $st2 = State-Of $el $patterns $false } catch { $st2 = $null }
172
+ if ($null -ne $st2) { $st = $st2 }
173
+ }
174
+ if ($null -ne $st) { $node['state'] = $st }
175
+ }
176
+ # Depth cap, said per node instead of only in the header: this is where the walk stopped, so
177
+ # `computer_snapshot root=<this ref>` is the exact next call, without raising maxNodes over
178
+ # the whole window.
179
+ if ($depth -ge $ctx.maxDepth) { $node['cut'] = $true }
180
+ $null = New-Ref $ctx.entry $el $cp $node
181
+ $ctx.nodes.Add($node) | Out-Null
182
+ }
183
+ return $true
184
+ } catch {
185
+ $ctx.truncated = $true
186
+ $ctx.partialReasons['nodeProviderError'] = $true
187
+ $ctx.providerErrors += 1
188
+ return $true
189
+ }
190
+ }
191
+
192
+ function Build-Snapshot($entry, $A) {
193
+ $ae = Window-Ae $entry
194
+ if ($null -eq $ae) { Err 'window_not_found' ("window " + $entry.id + " (hwnd " + $entry.hwnd + ") is gone") }
195
+ $maxNodes = IntArg $A 'maxNodes' 300
196
+ if ($maxNodes -lt 1) { $maxNodes = 1 }
197
+ if ($maxNodes -gt $script:W.maxRefs) { $maxNodes = $script:W.maxRefs }
198
+ $wantPatterns = BoolArg $A 'patterns' $true
199
+ $wantValues = BoolArg $A 'values' $true
200
+ $wantState = BoolArg $A 'state' $true
201
+ $maxDepth = IntArg $A 'maxDepth' 30
202
+ # View and subtree root are the two ways to widen what the tree can show without re-reading the
203
+ # whole window. `view` only accepts the three real UIA views; anything else stays control, so a
204
+ # typo cannot silently produce a different tree than the caller asked for.
205
+ $viewArg = StrArg $A 'view' 'control'
206
+ $view = 'control'
207
+ if ($viewArg -eq 'raw' -or $viewArg -eq 'content') { $view = $viewArg }
208
+ # Resolve the subtree root BEFORE the revision bumps: the ref belongs to the CURRENT revision,
209
+ # and a subtree pass deliberately does NOT bump it (see below), so the caller's other refs stay
210
+ # valid while it digs.
211
+ $rootRef = StrArg $A 'root' ''
212
+ $rootEl = $null
213
+ if ($rootRef -ne '') {
214
+ $reRoot = Resolve-Ref $rootRef $null
215
+ $rootEl = $reRoot.ae
216
+ $ae = $rootEl
217
+ }
218
+ $filter = Dict (ArgOf $A 'filter')
219
+ $fCt = ''; $fCtSet = @{}; $fName = ''; $fClass = ''; $incOff = $true
220
+ if ($null -ne $filter) {
221
+ $fCt = [string](ArgOf $filter 'controlType')
222
+ # The tool contract advertises controlType as a comma-separated set ("Button,Edit"). Comparing
223
+ # the whole string against one node's type silently matched nothing, so a documented filter
224
+ # returned an empty tree. Split once and test membership.
225
+ foreach ($t in ($fCt -split ',')) {
226
+ $tt = $t.Trim()
227
+ if ($tt -ne '') { $fCtSet[$tt] = $true }
228
+ }
229
+ $fName = [string](ArgOf $filter 'nameContains')
230
+ $fClass = [string](ArgOf $filter 'className')
231
+ $io = ArgOf $filter 'includeOffscreen'
232
+ if ($null -eq $io) { $incOff = $false } else { $incOff = BoolArg $filter 'includeOffscreen' $false }
233
+ } else {
234
+ $incOff = BoolArg $A 'includeOffscreen' $true
235
+ }
236
+ $reserve = [Math]::Min($maxNodes, 900)
237
+ $evicted = Evict-ForReservation $reserve
238
+
239
+ # A subtree pass is a drill-down inside one revision: the refs it mints join the existing
240
+ # revision, so the shallow skeleton the caller just read is still usable afterwards. A whole-window
241
+ # pass IS a new revision, and says so by invalidating older refs.
242
+ if ($null -eq $rootEl) { $entry.revision += 1 }
243
+ $snap = @{ revision = $entry.revision; windowId = $entry.id; createdTick = TickNow; refs = (New-Object System.Collections.Generic.List[string]); started = (TickNow) }
244
+ $entry.snapshots.Add($snap)
245
+ $entry.lastSeen = (TickNow)
246
+ $script:W.stats.snapshots += 1
247
+
248
+ $walker = Get-SnapshotWalker $view
249
+ $req = Snapshot-CacheRequest
250
+ $nodes = New-Object System.Collections.Generic.List[object]
251
+ $siblingLimit = 512
252
+ $stack = New-Object System.Collections.Generic.Stack[object]
253
+ $stack.Push(@($ae, 0))
254
+ # Shared mutable walk state: one hashtable, because the node builder is a script-scope function
255
+ # and cannot see this function's locals. Same fields the old loop locals carried.
256
+ $ctx = @{
257
+ entry = $entry
258
+ nodes = $nodes
259
+ visited = 0
260
+ truncated = $false
261
+ partialReasons = @{}
262
+ providerErrors = 0
263
+ fCtSet = $fCtSet
264
+ fClass = $fClass
265
+ fName = $fName
266
+ incOff = $incOff
267
+ wantPatterns = $wantPatterns
268
+ wantValues = $wantValues
269
+ wantState = $wantState
270
+ maxDepth = $maxDepth
271
+ # A live state read is a cross-process round-trip. Thirty of them covers a tree's real controls
272
+ # without letting a 300-node bridged window spend a second on advisory fields.
273
+ stateLiveBudget = 30
274
+ }
275
+
276
+ # ---- one-shot subtree path ---------------------------------------------------------------
277
+ # ONE cross-process call (GetUpdatedCache at TreeScope=Subtree) materialises the whole subtree
278
+ # with every property, pattern availability and RuntimeId already cached; everything after it
279
+ # is in-memory (measured 0.10-0.16 ms/node vs ~1.5 ms/node for an Activate+FindAll shape and
280
+ # ~4.4 ms/node for the per-child walker). This is NOT a cost cap: the whole-tree materialisation
281
+ # is paid BEFORE any node cap is checked (a Chromium window materialises its full a11y tree in
282
+ # that one call and it cannot be interrupted) — the cap below only stops the in-memory walk from
283
+ # continuing on a pathological tree, and the walker fallback after it is loss control, not fee
284
+ # control. A provider that refuses the bulk cache (or any failure here) falls back to the
285
+ # per-child walker below, which carries the same emit contract.
286
+ $oneShot = $null
287
+ # GetUpdatedCache materialises the provider's OWN view at the requested scope; it cannot be told
288
+ # to walk RawView. So a non-control view goes through the walker, where the view is explicit.
289
+ # Measured on an Explorer window: control/depth 5 = 79 nodes in 679 ms (the up-front
290
+ # materialisation of the whole subtree dominates), raw/depth 5 = 89 nodes in 480 ms. The one-shot
291
+ # path is still the default because it wins per node on big trees, but raw is not a cost penalty
292
+ # on every window — the budget is what bounds either path.
293
+ $subReq = if ($view -eq 'control') { Subtree-CacheRequest } else { $null }
294
+ if ($null -ne $subReq) {
295
+ try {
296
+ $rootC = $ae.GetUpdatedCache($subReq)
297
+ if ($null -ne $rootC) {
298
+ $oneShot = New-Object System.Collections.Generic.List[object]
299
+ $nav = New-Object System.Collections.Generic.Stack[object]
300
+ $nav.Push(@($rootC, 0))
301
+ $hardCap = 3000
302
+ $tooBig = $false
303
+ while ($nav.Count -gt 0) {
304
+ $pair = $nav.Pop()
305
+ $oneShot.Add($pair) | Out-Null
306
+ if ($oneShot.Count -gt $hardCap) { $tooBig = $true; break }
307
+ $d = [int]$pair[1]
308
+ if ($d -ge $maxDepth) { $ctx.truncated = $true; $ctx.partialReasons['maxDepth'] = $true; continue }
309
+ try { $kids = $pair[0].CachedChildren } catch {
310
+ $ctx.truncated = $true; $ctx.partialReasons['childProviderError'] = $true; $ctx.providerErrors += 1
311
+ continue
312
+ }
313
+ for ($j = $kids.Count - 1; $j -ge 0; $j--) { $nav.Push(@($kids[$j], ($d + 1))) }
314
+ }
315
+ if ($tooBig) {
316
+ Log ('one-shot subtree exceeded ' + $hardCap + ' nodes; falling back to the walker path')
317
+ $oneShot = $null
318
+ }
319
+ }
320
+ } catch {
321
+ Log ('one-shot subtree cache failed, falling back to the walker: ' + $_.Exception.Message)
322
+ $oneShot = $null
323
+ }
324
+ }
325
+
326
+ if ($null -ne $oneShot) {
327
+ foreach ($pair in $oneShot) {
328
+ if ($nodes.Count -ge $maxNodes) { $ctx.truncated = $true; $ctx.partialReasons['maxNodes'] = $true; break }
329
+ Test-Deadline 'snapshot'
330
+ $el = $pair[0]; $depth = [int]$pair[1]
331
+ try {
332
+ # TreeScope=Subtree includes Element, so even the root carries its cache here — unlike the
333
+ # walker path below, where the depth-0 root is still read live.
334
+ $cp = $el.Cached
335
+ if ($null -eq $cp) { throw 'provider returned no Cached properties' }
336
+ } catch {
337
+ $ctx.truncated = $true; $ctx.partialReasons['nodeProviderError'] = $true; $ctx.providerErrors += 1
338
+ continue
339
+ }
340
+ [void](Build-SnapshotNode $el $depth $cp $ctx)
341
+ }
342
+ } else {
343
+ while ($stack.Count -gt 0) {
344
+ if ($nodes.Count -ge $maxNodes) { $ctx.truncated = $true; $ctx.partialReasons['maxNodes'] = $true; break }
345
+ Test-Deadline 'snapshot'
346
+ $pair = $stack.Pop()
347
+ $el = $pair[0]; $depth = [int]$pair[1]
348
+ # A single provider/property failure must not discard the rest of the snapshot. Keep
349
+ # walking this node's children as well: Current can fail while navigation still works.
350
+ try {
351
+ # Depth 0 is the live window element: the walker's cached overloads apply the request to the
352
+ # element they RETURN, so the root has no cached blob and one node's live reads are noise.
353
+ # Every node below it came back from GetFirstChild/GetNextSibling(el, request) and reads its
354
+ # seven properties from the cached blob with no cross-process round-trip. Same struct shape
355
+ # as Current, so the builder below is unchanged.
356
+ $cp = if ($null -ne $req -and $depth -gt 0) { $el.Cached } else { $el.Current }
357
+ if ($null -eq $cp) { throw 'provider returned no Current properties' }
358
+ [void](Build-SnapshotNode $el $depth $cp $ctx)
359
+ } catch {
360
+ $ctx.truncated = $true; $ctx.partialReasons['nodeProviderError'] = $true; $ctx.providerErrors += 1
361
+ }
362
+ if ($depth -ge $maxDepth) { $ctx.truncated = $true; $ctx.partialReasons['maxDepth'] = $true; continue }
363
+ $kids = New-Object System.Collections.Generic.List[object]
364
+ $c = $null
365
+ # The request overload returns the child WITH its properties already cached — one round-trip
366
+ # instead of one navigation call plus seven property reads (see Snapshot-CacheRequest).
367
+ try { $c = if ($null -ne $req) { $walker.GetFirstChild($el, $req) } else { $walker.GetFirstChild($el) } } catch {
368
+ $ctx.truncated = $true; $ctx.partialReasons['childProviderError'] = $true; $ctx.providerErrors += 1
369
+ }
370
+ while ($null -ne $c) {
371
+ if ($kids.Count -ge $siblingLimit) { $ctx.truncated = $true; $ctx.partialReasons['siblingLimit'] = $true; break }
372
+ $kids.Add($c) | Out-Null
373
+ try { $c = if ($null -ne $req) { $walker.GetNextSibling($c, $req) } else { $walker.GetNextSibling($c) } } catch {
374
+ $c = $null; $ctx.truncated = $true; $ctx.partialReasons['siblingProviderError'] = $true; $ctx.providerErrors += 1
375
+ }
376
+ }
377
+ for ($j = $kids.Count - 1; $j -ge 0; $j--) { $stack.Push(@($kids[$j], ($depth + 1))) }
378
+ }
379
+ }
380
+ $ms = MsFrom $snap.started
381
+ $result = [ordered]@{
382
+ revision = $entry.revision
383
+ windowId = $entry.id
384
+ view = $view
385
+ nodeCount = $nodes.Count
386
+ visited = $ctx.visited
387
+ truncated = [bool]$ctx.truncated
388
+ maxNodesApplied = $maxNodes
389
+ ceiling = [int]$script:W.maxRefs
390
+ totalRefs = $script:W.totalRefs
391
+ evictions = $evicted.Count
392
+ ms = $ms
393
+ msPerNode = if ($nodes.Count -gt 0) { [Math]::Round($ms / $nodes.Count, 3) } else { 0 }
394
+ nodes = $nodes
395
+ }
396
+ if ($ctx.partialReasons.Count -gt 0) { $result['partialReason'] = (($ctx.partialReasons.Keys | Sort-Object) -join ',') }
397
+ if ($rootRef -ne '') { $result['rootRef'] = $rootRef; $result['subtree'] = $true }
398
+ if ($ctx.providerErrors -gt 0) { $result['providerErrors'] = $ctx.providerErrors }
399
+ if ($evicted.Count -gt 0) { $result['evicted'] = $evicted }
400
+ if ($nodes.Count -eq 0) { $result['detail'] = 'no nodes matched; check filter or take an unfiltered snapshot' }
401
+ # Position metadata: what is foreground and where the focus sits right now. Advisory,
402
+ # try/catch-guarded — a probe failure just omits the fields, it never fails the snapshot.
403
+ try {
404
+ $obsHeader = Window-ObservationHeader $entry
405
+ if ($null -ne $obsHeader) {
406
+ foreach ($k in @($obsHeader.Keys)) { $result[$k] = $obsHeader[$k] }
407
+ }
408
+ } catch { }
409
+ return $result
410
+ }
411
+
412
+