dsh-native-uia 0.4.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.
@@ -1,8 +1,8 @@
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
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
6
  # any function from any other part: neighbour order is not a dependency.
7
7
  # ---------------------------------------------------------------- snapshot
8
8
  # One CacheRequest shared by every snapshot walk, handed to the walker's cached overloads
@@ -34,7 +34,12 @@ $script:snapPatterns = @(
34
34
  [System.Windows.Automation.ValuePattern]::Pattern,
35
35
  [System.Windows.Automation.TogglePattern]::Pattern,
36
36
  [System.Windows.Automation.RangeValuePattern]::Pattern,
37
- [System.Windows.Automation.ExpandCollapsePattern]::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
38
43
  )
39
44
  function New-SnapshotCacheRequest($scope) {
40
45
  $req = New-Object System.Windows.Automation.CacheRequest
@@ -88,9 +93,19 @@ function Find-CacheRequest {
88
93
 
89
94
  # The walker used by the snapshot fallback path. One indirection so the test harness can walk a
90
95
  # mock tree through the SAME code path (regression-worker.ps1 redefines this and feeds a mock
91
- # walker); production always gets the ControlViewWalker.
92
- function Get-SnapshotWalker {
93
- return [System.Windows.Automation.TreeWalker]::ControlViewWalker
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
+ }
94
109
  }
95
110
 
96
111
  # Builds ONE snapshot node (shared by the one-shot subtree path and the walker fallback): the emit
@@ -143,6 +158,25 @@ function Build-SnapshotNode($el, $depth, $cp, $ctx) {
143
158
  if ($v.Length -gt 200) { $node['valueTruncated'] = $true }
144
159
  }
145
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 }
146
180
  $null = New-Ref $ctx.entry $el $cp $node
147
181
  $ctx.nodes.Add($node) | Out-Null
148
182
  }
@@ -163,7 +197,24 @@ function Build-Snapshot($entry, $A) {
163
197
  if ($maxNodes -gt $script:W.maxRefs) { $maxNodes = $script:W.maxRefs }
164
198
  $wantPatterns = BoolArg $A 'patterns' $true
165
199
  $wantValues = BoolArg $A 'values' $true
200
+ $wantState = BoolArg $A 'state' $true
166
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
+ }
167
218
  $filter = Dict (ArgOf $A 'filter')
168
219
  $fCt = ''; $fCtSet = @{}; $fName = ''; $fClass = ''; $incOff = $true
169
220
  if ($null -ne $filter) {
@@ -185,13 +236,16 @@ function Build-Snapshot($entry, $A) {
185
236
  $reserve = [Math]::Min($maxNodes, 900)
186
237
  $evicted = Evict-ForReservation $reserve
187
238
 
188
- $entry.revision += 1
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 }
189
243
  $snap = @{ revision = $entry.revision; windowId = $entry.id; createdTick = TickNow; refs = (New-Object System.Collections.Generic.List[string]); started = (TickNow) }
190
244
  $entry.snapshots.Add($snap)
191
245
  $entry.lastSeen = (TickNow)
192
246
  $script:W.stats.snapshots += 1
193
247
 
194
- $walker = Get-SnapshotWalker
248
+ $walker = Get-SnapshotWalker $view
195
249
  $req = Snapshot-CacheRequest
196
250
  $nodes = New-Object System.Collections.Generic.List[object]
197
251
  $siblingLimit = 512
@@ -212,6 +266,11 @@ function Build-Snapshot($entry, $A) {
212
266
  incOff = $incOff
213
267
  wantPatterns = $wantPatterns
214
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
215
274
  }
216
275
 
217
276
  # ---- one-shot subtree path ---------------------------------------------------------------
@@ -225,7 +284,13 @@ function Build-Snapshot($entry, $A) {
225
284
  # control. A provider that refuses the bulk cache (or any failure here) falls back to the
226
285
  # per-child walker below, which carries the same emit contract.
227
286
  $oneShot = $null
228
- $subReq = Subtree-CacheRequest
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 }
229
294
  if ($null -ne $subReq) {
230
295
  try {
231
296
  $rootC = $ae.GetUpdatedCache($subReq)
@@ -316,6 +381,7 @@ function Build-Snapshot($entry, $A) {
316
381
  $result = [ordered]@{
317
382
  revision = $entry.revision
318
383
  windowId = $entry.id
384
+ view = $view
319
385
  nodeCount = $nodes.Count
320
386
  visited = $ctx.visited
321
387
  truncated = [bool]$ctx.truncated
@@ -328,6 +394,7 @@ function Build-Snapshot($entry, $A) {
328
394
  nodes = $nodes
329
395
  }
330
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 }
331
398
  if ($ctx.providerErrors -gt 0) { $result['providerErrors'] = $ctx.providerErrors }
332
399
  if ($evicted.Count -gt 0) { $result['evicted'] = $evicted }
333
400
  if ($nodes.Count -eq 0) { $result['detail'] = 'no nodes matched; check filter or take an unfiltered snapshot' }
@@ -1,8 +1,8 @@
1
- # 07-action.ps1 -- element actions and wait conditions
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
1
+ # 07-action.ps1 -- element actions and wait conditions
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
6
  # any function from any other part: neighbour order is not a dependency.
7
7
  # ---------------------------------------------------------------- actions
8
8
  function Is-ForegroundHwnd($hwnd) {
@@ -116,6 +116,44 @@ function Invoke-UiaAction($re, $action, $value, $step) {
116
116
  if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support SelectionItem") }
117
117
  $p.Select(); return $via
118
118
  }
119
+ 'deselect' {
120
+ $p = Get-RefPattern $re 'SelectionItem'
121
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support SelectionItem") }
122
+ $p.RemoveFromSelection(); return $via
123
+ }
124
+ 'add_to_selection' {
125
+ $p = Get-RefPattern $re 'SelectionItem'
126
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support SelectionItem") }
127
+ $p.AddToSelection(); return $via
128
+ }
129
+ 'scroll_to' {
130
+ # ScrollItem.ScrollIntoView is the provider's own "bring me into the viewport", which is
131
+ # cheaper and more correct than the wheel: it moves the exact container that owns the item and
132
+ # never overshoots. Ensure-InView (the wheel path used before every act) stays as the fallback
133
+ # for items whose provider has no ScrollItem.
134
+ $p = Get-RefPattern $re 'ScrollItem'
135
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support ScrollItem") }
136
+ try { $p.ScrollIntoView() } catch { Err 'action_failed' ('ScrollIntoView threw: ' + $_.Exception.Message) }
137
+ return $via
138
+ }
139
+ 'set_range' {
140
+ # A slider/spinner was a pointer target only: the model had to drag it and hope. RangeValue has
141
+ # SetValue(value); clamp to the provider's own Min/Max instead of letting it throw.
142
+ $p = Get-RefPattern $re 'RangeValue'
143
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support RangeValue") }
144
+ $num = 0.0
145
+ $txt = [string]$value
146
+ if (-not [double]::TryParse($txt, [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$num)) {
147
+ Err 'bad_arg' ('set_range needs a numeric value, got "' + (TruncStr $txt 40) + '"')
148
+ }
149
+ try {
150
+ $cur = $p.Current
151
+ if ($num -lt $cur.Minimum) { $num = $cur.Minimum }
152
+ if ($num -gt $cur.Maximum) { $num = $cur.Maximum }
153
+ } catch { }
154
+ try { $p.SetValue($num) } catch { Err 'action_failed' ('RangeValue.SetValue threw: ' + $_.Exception.Message) }
155
+ return $via
156
+ }
119
157
  'expand' {
120
158
  $p = Get-RefPattern $re 'ExpandCollapse'
121
159
  if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support ExpandCollapse") }
@@ -150,7 +188,7 @@ function Invoke-UiaAction($re, $action, $value, $step) {
150
188
  return $via
151
189
  }
152
190
  default {
153
- Err 'unknown_action' ("unsupported action '" + $action + "' (invoke|set_value|toggle|select|expand|collapse|scroll_up|scroll_down|focus|text_append)")
191
+ Err 'unknown_action' ("unsupported action '" + $action + "' (invoke|set_value|toggle|select|deselect|add_to_selection|expand|collapse|scroll_up|scroll_down|scroll_to|set_range|focus|text_append)")
154
192
  }
155
193
  }
156
194
  }
@@ -644,7 +644,8 @@ function Cmd-CommitBatch($A) {
644
644
  }) | Out-Null
645
645
  }
646
646
  }
647
- # The Node side reads "no stop" as stoppedAt === null (see tools.js allPassed check), so a
647
+ # The Node side reads "no stop" as stoppedAt === null (see the allPassed check in
648
+ # src/tools/defs/act.js), so a
648
649
  # sentinel of -1 here would be mistaken for a stop at step -1 and would suppress the recipe
649
650
  # save on an otherwise clean batch. Emit the real index, or an explicit JSON null (DBNull, so
650
651
  # the generic serializer keeps the key instead of dropping it) when every step passed.
@@ -1035,6 +1036,14 @@ function Cmd-FindText($A) {
1035
1036
  $max = IntArg $A 'max' 60
1036
1037
  $ae = Window-Ae $entry
1037
1038
  if ($null -eq $ae) { Err 'window_not_found' ("window " + $entry.id + " is gone") }
1039
+ # Scoped search: the documented rhythm "find_text INTO the container you located" had no way to
1040
+ # say which container, so every search re-enumerated the whole window (1-3 ms per element on a
1041
+ # Chromium tree). With a ref the scan starts at that element, which is both narrower and faster.
1042
+ $within = StrArg $A 'within' ''
1043
+ if ($within -ne '') {
1044
+ $reWithin = Resolve-Ref $within $null
1045
+ $ae = $reWithin.ae
1046
+ }
1038
1047
  # ---- cached scan: Activate a PRIVATE request (same property/pattern shape as the snapshot
1039
1048
  # request, incl. pattern availability + RuntimeId), so FindAll returns elements that already
1040
1049
  # carry their cache and the per-element loop reads $c.Cached with no per-node round-trips
@@ -1170,6 +1179,7 @@ function Cmd-FindText($A) {
1170
1179
  $out.Add($item) | Out-Null
1171
1180
  }
1172
1181
  $r = [ordered]@{ windowId = $entry.id; revision = $entry.revision; text = $text; matches = $out; count = $out.Count; scanned = $all.Count; matchedTotal = $matchedTotal; truncated = [bool]$truncated; ms = (MsFrom $st) }
1182
+ if ($within -ne '') { $r['within'] = $within }
1173
1183
  # Position metadata, same contract as snapshot's: advisory fields, omitted on failure.
1174
1184
  try {
1175
1185
  $obsHeader = Window-ObservationHeader $entry
@@ -15,7 +15,6 @@ $handlers = @{
15
15
  act = 'Cmd-Act'
16
16
  set_pointer_mode = 'Cmd-SetPointerMode'
17
17
  escape_pressed = 'Cmd-EscapePressed'
18
-
19
18
  prepare_batch = 'Cmd-PrepareBatch'
20
19
  commit_batch = 'Cmd-CommitBatch'
21
20
  wait = 'Cmd-Wait'
@@ -53,7 +52,6 @@ $defaultBudget = @{
53
52
  act = 15000
54
53
  set_pointer_mode = 3000
55
54
  escape_pressed = 2000
56
-
57
55
  list_windows = 8000
58
56
  pointer_click = 5000
59
57
  pointer_drag = 8000
@@ -1,100 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * The kill latch must refuse only the command that was in flight at the stop instant.
4
- *
5
- * Measured bug (2026-11-21): Esc armed the latch, the next mutating call consumed it and was
6
- * refused, and the model — reading "本轮已被终止" — never retried. `killed` stayed true, the run
7
- * could not light again, and the person saw an unresponsive overlay. A second Esc re-armed it,
8
- * so every stop kept poisoning one more action.
9
- *
10
- * This exercises the real halt callback from src/index.js against a fake store: no desktop input,
11
- * no worker spawn.
12
- */
13
- import assert from 'node:assert/strict';
14
- import { readFileSync } from 'node:fs';
15
- import { dirname, join } from 'node:path';
16
- import { fileURLToPath } from 'node:url';
17
-
18
- const root = dirname(dirname(fileURLToPath(import.meta.url)));
19
- const source = readFileSync(join(root, 'src/index.js'), 'utf8');
20
-
21
- // Pull the production halt callback and its window constant out of index.js so the test cannot
22
- // drift from the shipped logic.
23
- const latchMs = Number(source.match(/const HALT_LATCH_MS = (\d+);/)?.[1]);
24
- const haltBody = source.match(/halt: \(\) => \{([\s\S]*?)\n \},/)?.[1];
25
-
26
- let passed = 0;
27
- function test(name, fn) {
28
- try { fn(); passed++; console.log(`PASS ${name}`); }
29
- catch (error) { console.log(`FAIL ${name}: ${error.message}`); process.exitCode = 1; }
30
- }
31
-
32
- test('the latch window and the halt callback are present in the shipped source', () => {
33
- assert.ok(Number.isFinite(latchMs) && latchMs > 0, 'HALT_LATCH_MS is missing or not a number');
34
- assert.ok(typeof haltBody === 'string' && haltBody.length > 0, 'the halt callback was not found in index.js');
35
- assert.match(haltBody, /killedAt/, 'the halt callback no longer considers when the latch was armed');
36
- });
37
-
38
- // Build a store shaped like src/state.js and run the production halt body against it.
39
- function makeHalt() {
40
- const logged = [];
41
- const store = { killed: false, killedAt: 0, setKilled(v) { this.killed = v; if (v) this.killedAt = Date.now(); } };
42
- const logger = (m) => logged.push(m);
43
- const halt = new Function('store', 'logger', 'HALT_LATCH_MS', `return () => {${haltBody}\n};`)(store, logger, latchMs);
44
- return { store, halt, logged };
45
- }
46
-
47
- test('a stopped command is refused inside the latch window', () => {
48
- const { store, halt, logged } = makeHalt();
49
- store.setKilled(true); // Esc fired
50
- const message = halt(); // the in-flight command arrives immediately
51
- assert.equal(typeof message, 'string', 'the command in flight at the stop was allowed through');
52
- assert.match(message, /本轮已被终止/);
53
- assert.equal(store.killed, false, 'the one-shot latch was not cleared after refusing');
54
- assert.equal(logged.length, 1);
55
- });
56
-
57
- test('the next instruction after the window is delivered, not refused', () => {
58
- const { store, halt, logged } = makeHalt();
59
- store.setKilled(true);
60
- store.killedAt = Date.now() - (latchMs + 500); // the person asked for something new
61
- const message = halt();
62
- assert.equal(message, null, 'a fresh instruction was refused because of an old stop');
63
- assert.equal(store.killed, false, 'the stale latch was left armed');
64
- assert.equal(logged.length, 0, 'a stale latch logged a stop that did not apply to this action');
65
- });
66
-
67
- test('an unarmed latch never blocks anything', () => {
68
- const { halt, logged } = makeHalt();
69
- assert.equal(halt(), null);
70
- assert.equal(logged.length, 0);
71
- });
72
-
73
- test('a latch with no timestamp is treated as stale, not as fresh', () => {
74
- // Defensive: a store restored from an older build has no killedAt. Reading it as age 0 would
75
- // make the very first action after an upgrade look like the stopped command.
76
- const { store, halt } = makeHalt();
77
- store.killed = true;
78
- store.killedAt = 0;
79
- assert.equal(halt(), null, 'a timestamp-less latch blocked a new instruction');
80
- });
81
-
82
- test('Esc clears the latch even when no command ever consumes it', () => {
83
- // The overlay is dismissed by Esc, so nothing else would ever clear a latch nobody read: the
84
- // panel kept showing 已终止. index.js schedules a clear after the window.
85
- assert.match(source, /clearAt/, 'index.js does not schedule a latch clear after Esc');
86
- assert.match(source, /HALT_LATCH_MS \+ 250/, 'the scheduled clear does not wait for the latch window to pass');
87
- });
88
-
89
- test('Esc is sampled while the run is live, not only while the overlay is painted', () => {
90
- // The overlay self-closes after DSH_NATIVE_UIA_IDLE_MS (20 s default) of tool silence, so a
91
- // model thinking pause set activity.active=false. Gating the watchdog on that made Esc dead
92
- // exactly when a person watches the agent work — the reported "运行中按 ESC 没反应".
93
- const esc = source.match(/const escTimer = setInterval\(\(\) => \{([\s\S]*?)\n \}, (\d+)\)/)?.[1] ?? '';
94
- assert.ok(esc !== '', 'the Esc watchdog block was not found');
95
- assert.doesNotMatch(esc, /!activity\.active/, 'the watchdog still gates on the rendered overlay');
96
- assert.match(esc, /store\.running !== true && store\.busy !== true/,
97
- 'the watchdog does not gate on the live run plus in-flight commands');
98
- });
99
-
100
- console.log(`\n${passed}/7 halt-latch regressions passed (no desktop input)`);
@@ -1,80 +0,0 @@
1
- import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
2
-
3
- /**
4
- * Plain JS has no decorator syntax, so the shipped decorator factory is invoked
5
- * with a standard-decorators context the way TypeScript's __esDecorate does.
6
- * This is the one step with no shipped precedent for a hand-written contribution.
7
- */
8
- const PENDING = [];
9
- let decorated = false;
10
- function mark(Ctor, method, options) {
11
- const queued = [];
12
- Remote(options ?? method)(Ctor.prototype[method], {
13
- kind: 'method',
14
- name: method,
15
- private: false,
16
- static: false,
17
- addInitializer: (fn) => queued.push(fn),
18
- });
19
- PENDING.push(queued);
20
- }
21
-
22
- function decorateMethods() {
23
- if (decorated) return;
24
- mark(NativeUiaRemote, 'state');
25
- mark(NativeUiaRemote, 'action');
26
- mark(NativeUiaRemote, 'subscribe', { mode: 'stream' });
27
- decorated = true;
28
- }
29
-
30
- export class NativeUiaRemote extends TypertRemoteService {
31
- constructor(ctx, { store, commands, policy }) {
32
- super(ctx, 'nativeUia');
33
- decorateMethods();
34
- this.store = store;
35
- this.commands = commands;
36
- this.policy = policy;
37
- for (const queued of PENDING) {
38
- for (const fn of queued) fn.call(this);
39
- }
40
- }
41
-
42
- state() {
43
- return this.store.snapshot(this.policy);
44
- }
45
-
46
- async action(body) {
47
- return this.commands.action(body);
48
- }
49
-
50
- async *subscribe(signal) {
51
- this.store.line('御屏面板经宿主通道订阅(ctx.remote.nativeUia.subscribe)');
52
- const queue = [];
53
- let wake = null;
54
- const bump = (kind) => (payload) => {
55
- queue.push({ kind, payload });
56
- if (wake !== null) { const run = wake; wake = null; run(); }
57
- };
58
- const handlers = [
59
- ['step', bump('step')],
60
- ['blocked', bump('blocked')],
61
- ['log', bump('log')],
62
- ['state', bump('state')],
63
- ['screenshot', bump('screenshot')],
64
- ];
65
- for (const [event, handler] of handlers) this.store.on(event, handler);
66
- try {
67
- yield { kind: 'snapshot', payload: this.store.snapshot(this.policy) };
68
- while (signal === undefined || signal.aborted !== true) {
69
- while (queue.length > 0) {
70
- const item = queue.shift();
71
- if (item.kind === 'state' || item.kind === 'step') item.payload = this.store.snapshot(this.policy);
72
- yield item;
73
- }
74
- await new Promise((resolve) => { wake = resolve; });
75
- }
76
- } finally {
77
- for (const [event, handler] of handlers) this.store.off(event, handler);
78
- }
79
- }
80
- }