dsh-native-uia 0.0.0-stage → 0.4.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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +663 -2
  3. package/client/client.js +269 -0
  4. package/cordis.patch.yml +10 -0
  5. package/icon.svg +11 -0
  6. package/locale/en.json +6 -0
  7. package/locale/zh.json +6 -0
  8. package/package.json +75 -4
  9. package/scripts/bench-live.mjs +157 -0
  10. package/scripts/check-lease.mjs +308 -0
  11. package/scripts/install.mjs +154 -0
  12. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  13. package/scripts/lib/load-tools-source.mjs +25 -0
  14. package/scripts/lib/sources.mjs +62 -0
  15. package/scripts/load-tools.mjs +74 -0
  16. package/scripts/measure-parse.mjs +77 -0
  17. package/scripts/regression-halt-latch.mjs +100 -0
  18. package/scripts/regression-quality.mjs +207 -0
  19. package/scripts/regression-tools.mjs +192 -0
  20. package/scripts/regression-worker.ps1 +1071 -0
  21. package/scripts/smoke.mjs +158 -0
  22. package/scripts/verify-capture-scale.mjs +37 -0
  23. package/scripts/verify-live-clipboard.mjs +108 -0
  24. package/scripts/verify-live-style.mjs +46 -0
  25. package/scripts/verify-live.mjs +104 -0
  26. package/scripts/verify-locator.mjs +52 -0
  27. package/scripts/verify.mjs +2110 -0
  28. package/src/activity-window.js +276 -0
  29. package/src/dashboard.js +103 -0
  30. package/src/guard.js +201 -0
  31. package/src/index.js +525 -0
  32. package/src/native-uia-remote.js +80 -0
  33. package/src/notes.js +83 -0
  34. package/src/state.js +267 -0
  35. package/src/themes.js +74 -0
  36. package/src/tools/defs/act.js +533 -0
  37. package/src/tools/defs/lifecycle.js +205 -0
  38. package/src/tools/defs/observe.js +309 -0
  39. package/src/tools/defs/pointer.js +298 -0
  40. package/src/tools/format.js +301 -0
  41. package/src/tools/index.js +128 -0
  42. package/src/tools/ocr.js +91 -0
  43. package/src/tools/recipes.js +44 -0
  44. package/src/tools/runtime.js +42 -0
  45. package/src/worker-client.js +268 -0
  46. package/worker/assets/dsh-whale.path +1 -0
  47. package/worker/bin/build-ocr.ps1 +41 -0
  48. package/worker/bin/ocr.cs +69 -0
  49. package/worker/bin/ocr.exe +0 -0
  50. package/worker/indicator-server.ps1 +2963 -0
  51. package/worker/lib/01-core.ps1 +64 -0
  52. package/worker/lib/02-uia.ps1 +221 -0
  53. package/worker/lib/03-window.ps1 +194 -0
  54. package/worker/lib/04-match.ps1 +435 -0
  55. package/worker/lib/05-value.ps1 +149 -0
  56. package/worker/lib/06-snapshot.ps1 +345 -0
  57. package/worker/lib/07-action.ps1 +291 -0
  58. package/worker/lib/08-command.ps1 +1485 -0
  59. package/worker/lib/09-pointer.ps1 +840 -0
  60. package/worker/lib/10-dispatch.ps1 +134 -0
  61. package/worker/ps-stdio.ps1 +173 -0
  62. package/worker/uia-worker.ps1 +599 -0
@@ -0,0 +1,435 @@
1
+ # 04-match.ps1 -- descriptor matching (name ladders, scoring)
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
+ # ---------------------------------------------------------------- descriptor matching
8
+ # Match ladder, strictly ordered and never silently fuzzy:
9
+ # 1. strict the caller's AND of exact UIA conditions (unchanged legacy behaviour)
10
+ # 2. id automationId (+controlType/className) only; the name is allowed to churn
11
+ # 3. normalizedName the name's dynamic tail normalised away, then compared exactly
12
+ # 4. prefix literal substring, ONLY for an explicit nameExact:false
13
+ # A level either resolves to exactly ONE element or records why it could not. Lower levels only
14
+ # run when every level above produced no decision, and none of them loosens a condition the caller
15
+ # did not loosen himself: nameExact:false is the only opt-in, and it selects the prefix level alone.
16
+ # The outcome of the last lookup is left in $script:W.lastMatch for the descriptor_match command.
17
+
18
+ # Normalisation rules. Deliberately narrow: only the TAIL is rewritten, and only shapes that are
19
+ # known to churn between two runs of the same recipe.
20
+ # 1. trim, then collapse every whitespace run to a single space (\s already covers U+3000 / NBSP)
21
+ # 2. drop a trailing relative-time token that is separated from the title by whitespace:
22
+ # 刚刚 刚才 今天 昨天 前天 / N秒[前] N分钟[前] N小时[前] N天[前] N周[前] N个月[前] / H:MM[:SS]
23
+ # 3. drop a trailing pure-count parenthetical: (3) (12)
24
+ # steps 2-3 repeat at most 3 times so "会话 A 刚刚 (2)" needs one call
25
+ # A tail glued to the title ("倒计时3分钟") is NOT touched: without a separator there is no way to
26
+ # tell a churning suffix from part of the title, and this level must not guess.
27
+ # Idempotent: Normalize(Normalize(x)) -eq Normalize(x).
28
+ #
29
+ # The tokens below are written as \uXXXX escapes ON PURPOSE. This file is UTF-8 without a BOM and
30
+ # Windows PowerShell 5.1 parses source as the ANSI code page (936 here), so a literal 刚刚 in a regex
31
+ # would arrive as mojibake and never match. \u521A etc. are interpreted by the regex engine, not by
32
+ # the parser, so they survive any code page.
33
+ function Normalize-NameText([string]$s) {
34
+ if ($null -eq $s) { return '' }
35
+ $t = [regex]::Replace($s, '\s+', ' ').Trim()
36
+ for ($i = 0; $i -lt 3; $i++) {
37
+ $before = $t
38
+ $t = [regex]::Replace($t, '(?<=\s|^)\d{1,2}:\d{2}(:\d{2})?\s*$', '')
39
+ $t = [regex]::Replace($t, '(?<=\s|^)(\u521A\u521A|\u521A\u624D|\u4ECA\u5929|\u6628\u5929|\u524D\u5929)\s*$', '')
40
+ $t = [regex]::Replace($t, '(?<=\s|^)\d{1,3}\s*(\u79D2\u524D|\u79D2|\u5206\u949F\u524D|\u5206\u949F|\u5206\u524D|\u5206|\u5C0F\u65F6\u524D|\u5C0F\u65F6|\u65F6|\u5929\u524D|\u5929|\u5468\u524D|\u5468|\u4E2A\u6708\u524D|\u4E2A\u6708|\u6708)\s*$', '')
41
+ $t = [regex]::Replace($t, '\s*[\(\uFF08]\s*\d{1,4}\s*[\)\uFF09]\s*$', '')
42
+ $t = $t.Trim()
43
+ if ($t -eq $before) { break }
44
+ }
45
+ return $t
46
+ }
47
+
48
+ # Deterministic 0..1 similarity, used ONLY to order the near-miss diagnostics of a failed lookup.
49
+ # It never decides whether something matches: that is always an exact (or explicitly substring)
50
+ # test. Length of the common prefix over the longer string, so it is cheap and stable.
51
+ function Get-NameSimilarity([string]$a, [string]$b) {
52
+ $x = [string]$a
53
+ $y = [string]$b
54
+ $max = [Math]::Max($x.Length, $y.Length)
55
+ if ($max -eq 0) { return 1.0 }
56
+ $n = [Math]::Min($x.Length, $y.Length)
57
+ $i = 0
58
+ while ($i -lt $n -and $x[$i] -eq $y[$i]) { $i += 1 }
59
+ return [Math]::Round(([double]$i / [double]$max), 3)
60
+ }
61
+
62
+ # A caller opts into substring matching with nameExact:false. JSON booleans arrive as [bool]; the
63
+ # string/number spellings are accepted too, because a hand-written recipe may quote the value and
64
+ # treating "false" as truthy would silently turn the prefix level into an exact one.
65
+ function Test-ExplicitFalse($dict, [string]$key) {
66
+ if ($null -eq $dict) { return $false }
67
+ if (-not $dict.Contains($key)) { return $false }
68
+ $v = $dict.Item($key)
69
+ if ($null -eq $v) { return $false }
70
+ if ($v -is [bool]) { return (-not $v) }
71
+ $s = ([string]$v).Trim().ToLowerInvariant()
72
+ return ($s -eq 'false' -or $s -eq '0' -or $s -eq 'no')
73
+ }
74
+
75
+ function Join-UiaCondition($conds) {
76
+ if ($null -eq $conds -or $conds.Count -eq 0) { return [System.Windows.Automation.Condition]::TrueCondition }
77
+ if ($conds.Count -eq 1) { return $conds[0] }
78
+ return New-Object System.Windows.Automation.AndCondition(($conds.ToArray()))
79
+ }
80
+
81
+ # Deterministic score for a successful resolution. The table is the whole rule:
82
+ # strict 1.00 | id 0.80 | normalizedName 0.70 | prefix 0.55
83
+ # chosen by nth -0.05 | chosen by nearPoint -0.03
84
+ # so a caller can tell "this is the element I described" from "this is a fallback that happened to
85
+ # be unique". Pinned by the regression script.
86
+ function Get-MatchScore([string]$ladder, [string]$selectedBy) {
87
+ $base = 0.0
88
+ switch ($ladder) {
89
+ 'strict' { $base = 1.00; break }
90
+ 'id' { $base = 0.80; break }
91
+ 'normalizedName' { $base = 0.70; break }
92
+ 'prefix' { $base = 0.55; break }
93
+ }
94
+ if ($selectedBy -eq 'nth') { $base = $base - 0.05 }
95
+ elseif ($selectedBy -eq 'nearPoint') { $base = $base - 0.03 }
96
+ if ($base -lt 0.0) { $base = 0.0 }
97
+ if ($base -gt 1.0) { $base = 1.0 }
98
+ return [Math]::Round($base, 3)
99
+ }
100
+
101
+ # Locator confidence as it goes onto a step descriptor (prepare_batch) and a step result
102
+ # (commit_batch). Returns $null when the record carries no decision — a ref step, or a lookup that
103
+ # never ran the ladder — so callers add the fields ONLY when they exist. An invented
104
+ # degraded=false / score=0 would be a claim about a lookup that never happened.
105
+ function Get-LocatorFields($lm) {
106
+ if ($null -eq $lm) { return $null }
107
+ if ([string]$lm.matchedBy -eq '') { return $null }
108
+ return [ordered]@{
109
+ matchedBy = [string]$lm.matchedBy
110
+ ladder = [string]$lm.ladder
111
+ score = [double]$lm.score
112
+ degraded = [bool]$lm.degraded
113
+ }
114
+ }
115
+
116
+ # One "closest candidate" record for a failed lookup: what it is, and why it is not the answer.
117
+ function New-MatchCandidate($cp, $wantName, $wantNorm, $wantCt, $wantCn, $wantAi, $reason) {
118
+ $candName = ''
119
+ $candCt = ''
120
+ $candCn = ''
121
+ $candAi = ''
122
+ try { $candName = [string]$cp.Name } catch { }
123
+ try { $candCt = ControlTypeName $cp.ControlType } catch { }
124
+ try { $candCn = [string]$cp.ClassName } catch { }
125
+ try { $candAi = [string]$cp.AutomationId } catch { }
126
+ $why = New-Object System.Collections.Generic.List[string]
127
+ if ($reason -ne '') { $why.Add($reason) | Out-Null }
128
+ if ($wantName -ne '' -and $candName -ne $wantName) {
129
+ if ($wantNorm -ne '' -and (Normalize-NameText $candName) -eq $wantNorm) { $why.Add('name-normalized-only') | Out-Null }
130
+ elseif ($candName.IndexOf($wantName, [StringComparison]::OrdinalIgnoreCase) -ge 0) { $why.Add('name-contains-only') | Out-Null }
131
+ else { $why.Add('name-differs') | Out-Null }
132
+ }
133
+ if ($wantCt -ne '' -and $candCt -ne $wantCt) { $why.Add('controlType-differs') | Out-Null }
134
+ if ($wantCn -ne '' -and $candCn -ne $wantCn) { $why.Add('className-differs') | Out-Null }
135
+ if ($wantAi -ne '' -and $candAi -ne $wantAi) { $why.Add('automationId-differs') | Out-Null }
136
+ return [ordered]@{
137
+ name = (TruncStr $candName 120)
138
+ automationId = $candAi
139
+ controlType = $candCt
140
+ className = (TruncStr $candCn 80)
141
+ reason = ([string]::Join(',', $why))
142
+ score = (Get-NameSimilarity $wantName $candName)
143
+ rect = (RectOf $cp)
144
+ }
145
+ }
146
+
147
+ # At most three candidates, in tree order, each tagged with the nth it would take to reach it —
148
+ # so a failure tells the model exactly how to fix the descriptor on the next attempt.
149
+ function New-MatchCandidateList($hits, $wantName, $wantNorm, $wantCt, $wantCn, $wantAi, $reason) {
150
+ $out = New-Object System.Collections.Generic.List[object]
151
+ $i = 0
152
+ foreach ($h in $hits) {
153
+ if ($i -ge 3) { break }
154
+ $i += 1
155
+ $c = New-MatchCandidate $h.cp $wantName $wantNorm $wantCt $wantCn $wantAi $reason
156
+ $c['nth'] = $i
157
+ $out.Add($c) | Out-Null
158
+ }
159
+ return ,$out
160
+ }
161
+
162
+ # Enumerate the descendants that satisfy $cond, keep the ones $keep accepts, then pick exactly one.
163
+ # $keep is $null for a pure condition lookup. $fallbackFirst preserves the historical "first match
164
+ # wins" behaviour of the strict and prefix levels; the newer levels pass $false so that a multiple
165
+ # hit is reported as ambiguity instead of being resolved by enumeration order.
166
+ function Select-DescriptorHit($ae, $cond, $keep, $keepArg, $nth, $near, $fallbackFirst) {
167
+ $hits = New-Object System.Collections.Generic.List[object]
168
+ $all = @()
169
+ try { $all = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, $cond)) } catch { return @{ hits = $hits; chosen = $null; selectedBy = ''; error = 'scan_failed' } }
170
+ foreach ($c in $all) {
171
+ if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) { break }
172
+ $cp = $null
173
+ try { $cp = $c.Current } catch { continue }
174
+ if ($null -eq $cp) { continue }
175
+ if ($null -ne $keep) {
176
+ $ok = $false
177
+ try { $ok = [bool](& $keep $cp $keepArg) } catch { $ok = $false }
178
+ if (-not $ok) { continue }
179
+ }
180
+ $hits.Add(@{ el = $c; cp = $cp }) | Out-Null
181
+ }
182
+ if ($hits.Count -eq 0) { return @{ hits = $hits; chosen = $null; selectedBy = ''; error = 'no_match' } }
183
+ # nearPoint wins over nth: a coordinate is the caller's strongest statement of intent.
184
+ if ($null -ne $near) {
185
+ $nx = 0.0; $ny = 0.0
186
+ try { $nx = [double](ArgOf $near 'x'); $ny = [double](ArgOf $near 'y') } catch { }
187
+ $best = $null; $bestD = [double]::MaxValue
188
+ foreach ($h in $hits) {
189
+ $r = RectOf $h.cp
190
+ if ($r.w -le 0 -or $r.h -le 0) { continue }
191
+ $cx = [double]$r.x + [double]$r.w / 2.0; $cy = [double]$r.y + [double]$r.h / 2.0
192
+ $d = [Math]::Sqrt(($cx - $nx) * ($cx - $nx) + ($cy - $ny) * ($cy - $ny))
193
+ if ($d -lt $bestD) { $bestD = $d; $best = $h }
194
+ }
195
+ if ($null -ne $best) { return @{ hits = $hits; chosen = $best.el; selectedBy = 'nearPoint'; error = '' } }
196
+ }
197
+ if ($nth -gt 0) {
198
+ if ($nth -gt $hits.Count) { return @{ hits = $hits; chosen = $null; selectedBy = ''; error = 'nth_out_of_range' } }
199
+ return @{ hits = $hits; chosen = $hits[$nth - 1].el; selectedBy = 'nth'; error = '' }
200
+ }
201
+ if ($hits.Count -eq 1) { return @{ hits = $hits; chosen = $hits[0].el; selectedBy = ''; error = '' } }
202
+ if ($fallbackFirst) { return @{ hits = $hits; chosen = $hits[0].el; selectedBy = ''; error = '' } }
203
+ return @{ hits = $hits; chosen = $null; selectedBy = ''; error = 'ambiguous' }
204
+ }
205
+
206
+ function Find-ByDescriptor($entry, $by) {
207
+ # Returns the element (unchanged contract: Resolve-Ref / Wait-Condition / prepare+commit all rely
208
+ # on getting the UIA element itself) or $null, and always leaves the explanation in lastMatch.
209
+ $script:W.lastMatch = @{
210
+ found = $false; matchedBy = ''; ladder = ''; score = 0.0; degraded = $false
211
+ candidateCount = 0; scanned = 'all'; nameExact = $true; reason = ''
212
+ tried = @(); candidates = @(); ambiguityAt = ''; diagnosticTruncated = $false
213
+ # candidateCountKnown=false marks the one record that cannot know the real count (the strict
214
+ # FindFirst fast path below); every other record is written from a full enumeration.
215
+ candidateCountKnown = $true
216
+ # The exact condition the fast path ran, kept so the read-only descriptor_match diagnostic can
217
+ # re-enumerate it and recover the true same-name count. Reset on every lookup.
218
+ fastCond = $null
219
+ }
220
+ $lm = $script:W.lastMatch
221
+ $ae = Window-Ae $entry
222
+ if ($null -eq $ae) { $lm.reason = 'window_gone'; return $null }
223
+ $by = Dict $by
224
+ if ($null -eq $by) { $lm.reason = 'empty_descriptor'; return $null }
225
+ $wantName = [string]$by.Item('name')
226
+ $wantCt = [string]$by.Item('controlType')
227
+ $wantCn = [string]$by.Item('className')
228
+ $wantAi = [string]$by.Item('automationId')
229
+ $exact = -not (Test-ExplicitFalse $by 'nameExact')
230
+ $lm.nameExact = $exact
231
+ # Disambiguators for a descriptor that matches several elements. Without them the provider's
232
+ # enumeration order decides, so a window with three "复制" buttons can only ever reach the first
233
+ # one — the model asks for the third, gets the first, and reports "点不准" while every coordinate
234
+ # was correct.
235
+ # nth : 1-based index among the matches (in tree order)
236
+ # nearPoint : pick the match whose centre is closest to this {x,y}
237
+ $nth = 0
238
+ $near = $null
239
+ try {
240
+ $nthRaw = $by.Item('nth')
241
+ if ($null -ne $nthRaw) { $nth = [int]$nthRaw }
242
+ $near = $by.Item('nearPoint')
243
+ } catch { }
244
+ # The structural half of the descriptor. Every level starts from exactly this and may only ADD
245
+ # constraints, never drop one that the caller supplied.
246
+ $baseConds = New-Object System.Collections.Generic.List[object]
247
+ if ($wantCt -ne '') {
248
+ try {
249
+ $field = [System.Windows.Automation.ControlType].GetField($wantCt)
250
+ if ($null -ne $field) {
251
+ $ctObj = $field.GetValue($null)
252
+ $baseConds.Add((New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ControlTypeProperty, $ctObj))) | Out-Null
253
+ }
254
+ } catch { }
255
+ }
256
+ if ($wantCn -ne '') { $baseConds.Add((New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ClassNameProperty, $wantCn))) | Out-Null }
257
+ if ($wantAi -ne '') { $baseConds.Add((New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::AutomationIdProperty, $wantAi))) | Out-Null }
258
+ if ($baseConds.Count -eq 0 -and $wantName -eq '') { $lm.reason = 'empty_descriptor'; return $null }
259
+
260
+ $wantNorm = Normalize-NameText $wantName
261
+ $tiers = New-Object System.Collections.Generic.List[string]
262
+ if (-not $exact -and $wantName -ne '') {
263
+ # nameExact:false is an explicit request for substring matching. It selects that level alone:
264
+ # running the exact levels first could resolve a *different*, exactly-named element.
265
+ $tiers.Add('prefix') | Out-Null
266
+ } else {
267
+ $tiers.Add('strict') | Out-Null
268
+ # id: only worth trying when the strict level had a name to lose (a name-less strict lookup
269
+ # already used every structural condition, so a second pass could not find anything new).
270
+ if ($wantName -ne '' -and $wantAi -ne '') { $tiers.Add('id') | Out-Null }
271
+ if ($wantName -ne '' -and $wantNorm -ne '') { $tiers.Add('normalizedName') | Out-Null }
272
+ }
273
+ $nameCond = $null
274
+ if ($exact -and $wantName -ne '') {
275
+ $nameCond = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::NameProperty, $wantName)
276
+ }
277
+ $tried = New-Object System.Collections.Generic.List[string]
278
+ $blockers = New-Object System.Collections.Generic.List[object]
279
+ foreach ($tier in $tiers) {
280
+ $tried.Add($tier) | Out-Null
281
+ $conds = New-Object System.Collections.Generic.List[object]
282
+ foreach ($c in $baseConds) { $conds.Add($c) | Out-Null }
283
+ $keep = $null
284
+ $keepArg = $null
285
+ $fallbackFirst = $true
286
+ if ($tier -eq 'strict') {
287
+ if ($null -ne $nameCond) { $conds.Add($nameCond) | Out-Null }
288
+ } elseif ($tier -eq 'id') {
289
+ $fallbackFirst = $false
290
+ } elseif ($tier -eq 'normalizedName') {
291
+ $fallbackFirst = $false
292
+ $keep = { param($cp, $w) return ((Normalize-NameText ([string]$cp.Name)) -eq $w) }
293
+ $keepArg = $wantNorm
294
+ } elseif ($tier -eq 'prefix') {
295
+ $keep = { param($cp, $w) return (([string]$cp.Name).IndexOf($w, [StringComparison]::OrdinalIgnoreCase) -ge 0) }
296
+ $keepArg = $wantName
297
+ }
298
+ $cond = Join-UiaCondition $conds
299
+ # Fast path: the legacy code used FindFirst whenever nothing had to be disambiguated and the
300
+ # name stayed exact. Keeping that identical shape means a recipe that resolved before resolves
301
+ # the same way, and the common case does not pay for a full descendant enumeration.
302
+ if ($tier -eq 'strict' -and $null -eq $keep -and $nth -le 1 -and $null -eq $near) {
303
+ $hit = $null
304
+ try { $hit = $ae.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $cond) } catch { $hit = $null }
305
+ if ($null -ne $hit) {
306
+ $lm.found = $true
307
+ $lm.ladder = 'strict'; $lm.matchedBy = 'strict'
308
+ $lm.score = (Get-MatchScore 'strict' '')
309
+ $lm.degraded = $false
310
+ # FindFirst stops at the first hit, so the REAL number of same-named candidates is unknown
311
+ # here. Writing 1 used to fake a uniqueness this scan never established (descriptor_match
312
+ # read exactly that lie, and a same-name ambiguity was invisible in every report). Say what
313
+ # is true instead: the count is unknown, and the condition is kept so the read-only
314
+ # descriptor_match diagnostic can re-enumerate it and recover the real number.
315
+ $lm.candidateCountKnown = $false
316
+ $lm.fastCond = $cond
317
+ $lm.scanned = 'first'
318
+ $lm.tried = $tried
319
+ return $hit
320
+ }
321
+ $blockers.Add(@{ ladder = 'strict'; reason = 'no_match'; count = 0; hits = @() }) | Out-Null
322
+ continue
323
+ }
324
+ $r = Select-DescriptorHit $ae $cond $keep $keepArg $nth $near $fallbackFirst
325
+ if ($null -ne $r.chosen) {
326
+ $lm.found = $true
327
+ $lm.ladder = $tier
328
+ $lm.matchedBy = $tier
329
+ if ($r.selectedBy -ne '') { $lm.matchedBy = $r.selectedBy }
330
+ $lm.score = (Get-MatchScore $tier $r.selectedBy)
331
+ $lm.degraded = ($tier -ne 'strict')
332
+ $lm.candidateCount = $r.hits.Count
333
+ $lm.scanned = 'all'
334
+ $lm.tried = $tried
335
+ return $r.chosen
336
+ }
337
+ if ($r.error -eq 'nth_out_of_range' -or $r.error -eq 'scan_failed') {
338
+ # The descriptor DID match elements; the caller's own disambiguator is what failed. Falling
339
+ # through to a looser level here would silently pick a different element than the recipe
340
+ # asked for, so this is terminal.
341
+ $lm.reason = $r.error
342
+ $lm.candidateCount = $r.hits.Count
343
+ $lm.tried = $tried
344
+ $lm.candidates = (New-MatchCandidateList $r.hits $wantName $wantNorm $wantCt $wantCn $wantAi $r.error)
345
+ return $null
346
+ }
347
+ if ($r.error -eq 'ambiguous' -and $lm.ambiguityAt -eq '') { $lm.ambiguityAt = $tier }
348
+ $blockers.Add(@{ ladder = $tier; reason = $r.error; count = $r.hits.Count; hits = $r.hits }) | Out-Null
349
+ }
350
+
351
+ $lm.tried = $tried
352
+ $best = $null
353
+ foreach ($b in $blockers) { if ($b.count -ge 1) { $best = $b; break } }
354
+ if ($null -ne $best) {
355
+ $lm.reason = $best.reason
356
+ if ($lm.reason -eq '') { $lm.reason = 'ambiguous' }
357
+ $lm.candidateCount = $best.count
358
+ $lm.candidates = (New-MatchCandidateList $best.hits $wantName $wantNorm $wantCt $wantCn $wantAi $best.reason)
359
+ return $null
360
+ }
361
+ $lm.reason = 'no_match'
362
+ if ($wantName -eq '') { return $null }
363
+ # Not even one level matched structurally: report the closest NAMES instead of only $null. Bounded
364
+ # so a pathological tree cannot turn a miss into a long scan, and only within the request budget.
365
+ if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) { return $null }
366
+ $scan = @()
367
+ try { $scan = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, (Join-UiaCondition $baseConds))) } catch { $scan = @() }
368
+ $ranked = New-Object System.Collections.Generic.List[object]
369
+ $i = 0
370
+ foreach ($c in $scan) {
371
+ $i += 1
372
+ if ($i -gt 400) { $lm.diagnosticTruncated = $true; break }
373
+ $cp = $null
374
+ try { $cp = $c.Current } catch { continue }
375
+ if ($null -eq $cp) { continue }
376
+ $cn = ''
377
+ try { $cn = [string]$cp.Name } catch { $cn = '' }
378
+ if ($cn -eq '') { continue }
379
+ $sim = Get-NameSimilarity $wantName $cn
380
+ if ($sim -le 0) { continue }
381
+ $ranked.Add(@{ cp = $cp; name = $cn; sim = $sim }) | Out-Null
382
+ }
383
+ $sorted = @($ranked | Sort-Object -Property @{ Expression = { $_.sim }; Descending = $true }, @{ Expression = { $_.name }; Descending = $false })
384
+ $cands = New-Object System.Collections.Generic.List[object]
385
+ $k = 0
386
+ foreach ($s in $sorted) {
387
+ if ($k -ge 3) { break }
388
+ $k += 1
389
+ $cands.Add((New-MatchCandidate $s.cp $wantName $wantNorm $wantCt $wantCn $wantAi '')) | Out-Null
390
+ }
391
+ $lm.candidates = $cands
392
+ return $null
393
+ }
394
+
395
+ function Resolve-Ref($ref, $opts) {
396
+ if ($null -eq $ref -or [string]$ref -eq '') { Err 'missing_ref' 'a ref is required' }
397
+ $re = $script:W.refs.Item([string]$ref)
398
+ if ($null -eq $re) { Err 'unknown_ref' ("ref " + $ref + " is not in the ref table (evicted, never issued, or its window was closed)") }
399
+ $entry = $script:W.windows.Item($re.windowId)
400
+ if ($null -eq $entry) { Err 'unknown_window' ("window " + $re.windowId + " is gone") }
401
+ if ($re.revision -ne $entry.revision) {
402
+ $script:W.stats.refused += 1
403
+ Err 'stale_revision' ("ref " + $ref + " belongs to revision " + $re.revision + " of " + $re.windowId + " but the current revision is " + $entry.revision + '; take a fresh snapshot')
404
+ }
405
+ if ($null -ne $opts) {
406
+ $o = Dict $opts
407
+ if ($null -ne $o) {
408
+ $want = $o.Item('revision')
409
+ if ($null -ne $want -and [int]$want -ne $entry.revision) {
410
+ $script:W.stats.refused += 1
411
+ Err 'revision_mismatch' ("caller supplied revision " + $want + " but " + $re.windowId + ' is at ' + $entry.revision)
412
+ }
413
+ }
414
+ }
415
+ $live = $null
416
+ try { $null = $re.ae.Current.Name; $live = $re.ae } catch { $live = $null }
417
+ if ($null -eq $live) {
418
+ $reb = Find-ByDescriptor $entry @{ automationId = $re.automationId; className = $re.className; name = $re.name; controlType = $re.controlType }
419
+ if ($null -eq $reb) { Err 'element_gone' ("ref " + $ref + ' no longer resolves in the tree of ' + $entry.id) }
420
+ $cpb = $null
421
+ try { $cpb = $reb.Current } catch { Err 'element_gone' ("ref " + $ref + ' cannot be read anymore') }
422
+ $ridNew = RuntimeIdKey $reb
423
+ if ($re.runtimeId -ne '' -and $ridNew -ne '' -and $ridNew -ne $re.runtimeId) {
424
+ Err 'element_gone' ("ref " + $ref + " would resolve to a different element (runtimeId " + $re.runtimeId + ' -> ' + $ridNew + ')')
425
+ }
426
+ $re.ae = $reb
427
+ $re.rebound = $true
428
+ # Cached pattern objects belong to the OLD element; after a rebind they would read the dead
429
+ # element (or nothing) forever. Drop them so the next read re-fetches on the new element.
430
+ $re.patCache = @{}
431
+ }
432
+ return $re
433
+ }
434
+
435
+
@@ -0,0 +1,149 @@
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
+ function SupportedActionOf($patterns) {
76
+ if ($null -eq $patterns) { return 'focus' }
77
+ if ($patterns -contains 'Invoke') { return 'invoke' }
78
+ if ($patterns -contains 'Toggle') { return 'toggle' }
79
+ if ($patterns -contains 'SelectionItem') { return 'select' }
80
+ if ($patterns -contains 'ExpandCollapse') { return 'expand' }
81
+ if ($patterns -contains 'Value') { return 'set_value' }
82
+ if ($patterns -contains 'Scroll') { return 'scroll_down' }
83
+ # LegacyIAccessible is NOT actionable from the managed UIA client (there is no
84
+ # System.Windows.Automation.LegacyIAccessiblePattern type in UIAutomationClient), so it is
85
+ # reported but never advertised as an action.
86
+ return 'focus'
87
+ }
88
+
89
+ function DescriptorOf($re, $live) {
90
+ $cp = $null
91
+ $patterns = $re.patterns
92
+ $name = $re.name
93
+ # The UNtruncated name, when the snapshot recorded one: a saved recipe needs it because a
94
+ # 160-cut name with '~' can never satisfy a strict re-match (F: recipe save quality).
95
+ $full = ''
96
+ if ($re.ContainsKey('fullName')) { $full = [string]$re.fullName }
97
+ $enabled = $re.enabled
98
+ $off = $re.isOffscreen
99
+ $rect = $re.rect
100
+ if ($live) {
101
+ try { $cp = $re.ae.Current } catch { $cp = $null }
102
+ if ($null -ne $cp) {
103
+ $name = [string]$cp.Name
104
+ $full = $name
105
+ $enabled = [bool]$cp.IsEnabled
106
+ $off = [bool]$cp.IsOffscreen
107
+ $rect = RectOf $cp
108
+ $p2 = PatternsOf $re.ae
109
+ if ($null -ne $p2 -and $p2.Count -gt 0) { $patterns = $p2 }
110
+ }
111
+ }
112
+ $d = [ordered]@{
113
+ ref = $re.ref
114
+ windowId = $re.windowId
115
+ revision = $re.revision
116
+ name = (TruncStr ([string]$name) 160)
117
+ controlType = $re.controlType
118
+ className = $re.className
119
+ automationId = $re.automationId
120
+ availablePatterns = @($patterns)
121
+ supportedAction = (SupportedActionOf $patterns)
122
+ enabled = $enabled
123
+ isOffscreen = $off
124
+ rect = $rect
125
+ depth = $re.depth
126
+ runtimeId = $re.runtimeId
127
+ }
128
+ # Attach only when truncation actually happened, so the common short-name descriptor keeps the
129
+ # old wire shape and no caller can mistake fullName for an always-present field.
130
+ if ($full -ne '' -and $full -ne [string]$d['name']) { $d['fullName'] = $full }
131
+ if ($live -and $null -ne $cp) {
132
+ $v = Read-Value $re.ae $patterns
133
+ if ($v -ne '') {
134
+ $d['value'] = (TruncStr $v 200)
135
+ if ($v.Length -gt 200) { $d['valueTruncated'] = $true }
136
+ }
137
+ }
138
+ # Attach the owning window so a saved recipe can rebind to it later. tools.js reads
139
+ # descriptors[0].ownerWindow to populate recipe.window; without it the recipe falls back to
140
+ # the store's window list, which is empty for a batch taken before any computer_windows call,
141
+ # and the recipe then replays with no windowId.
142
+ $we = $script:W.windows.Item([string]$re.windowId)
143
+ if ($null -ne $we) {
144
+ $d['ownerWindow'] = [ordered]@{ windowId = $re.windowId; hwnd = $we.hwnd; pid = $we.pid; revision = $we.revision }
145
+ }
146
+ return $d
147
+ }
148
+
149
+