dsh-native-uia 0.0.0-stage → 0.2.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +431 -2
  3. package/client/client.js +81 -0
  4. package/cordis.patch.yml +11 -0
  5. package/icon.svg +11 -0
  6. package/locale/desktop/en.json +6 -0
  7. package/locale/desktop/zh.json +6 -0
  8. package/locale/en.json +6 -0
  9. package/locale/zh.json +6 -0
  10. package/package.json +80 -4
  11. package/scripts/bench-live.mjs +157 -0
  12. package/scripts/check-lease.mjs +308 -0
  13. package/scripts/install.mjs +154 -0
  14. package/scripts/lib/load-tools-source.mjs +24 -0
  15. package/scripts/measure-parse.mjs +77 -0
  16. package/scripts/regression-halt-latch.mjs +100 -0
  17. package/scripts/regression-quality.mjs +207 -0
  18. package/scripts/regression-tools.mjs +88 -0
  19. package/scripts/regression-worker.ps1 +1042 -0
  20. package/scripts/smoke.mjs +158 -0
  21. package/scripts/verify-capture-scale.mjs +37 -0
  22. package/scripts/verify-live-clipboard.mjs +108 -0
  23. package/scripts/verify-live.mjs +110 -0
  24. package/scripts/verify-locator.mjs +52 -0
  25. package/scripts/verify.mjs +1459 -0
  26. package/src/activity-window.js +212 -0
  27. package/src/dashboard.js +145 -0
  28. package/src/guard.js +191 -0
  29. package/src/index.js +377 -0
  30. package/src/native-uia-remote.js +80 -0
  31. package/src/panel-face.js +14 -0
  32. package/src/state.js +177 -0
  33. package/src/tools.js +1482 -0
  34. package/src/worker-client.js +246 -0
  35. package/web/control.html +1413 -0
  36. package/worker/bin/build-ocr.ps1 +41 -0
  37. package/worker/bin/ocr.cs +69 -0
  38. package/worker/bin/ocr.exe +0 -0
  39. package/worker/indicator-server.ps1 +1928 -0
  40. package/worker/ps-stdio.ps1 +168 -0
  41. package/worker/uia-worker.ps1 +4220 -0
package/src/index.js ADDED
@@ -0,0 +1,377 @@
1
+ import { homedir } from 'node:os';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { CuaWorker } from './worker-client.js';
4
+ import { ActivityWindow, composeSubtext } from './activity-window.js';
5
+ import { Store } from './state.js';
6
+ import { Dashboard } from './dashboard.js';
7
+ import { registerTools, POLICY } from './tools.js';
8
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+
11
+ export const name = 'dsh-native-uia/desktop';
12
+ export const inject = ['tools', 'systemPrompt'];
13
+
14
+ const INDICATOR_SCRIPT = fileURLToPath(new URL('../worker/indicator-server.ps1', import.meta.url));
15
+
16
+ /**
17
+ * How long a kill (Esc / control page) keeps refusing input.
18
+ *
19
+ * The latch exists to stop the command that was ALREADY in flight when the person hit stop —
20
+ * killing the worker is what surfaces that pending commit as WorkerDeadError. It must not
21
+ * outlive that purpose: a person who presses Esc and then immediately asks for something else
22
+ * is issuing a new instruction, not repeating the stopped one. 1.5 s covers a mid-flight commit
23
+ * being torn down (the worker shutdown resolves in ms) while staying far below the time it takes
24
+ * a model to plan and emit its next tool call.
25
+ */
26
+ const HALT_LATCH_MS = 1500;
27
+
28
+ const GUIDANCE = `Native UIA computer-use tools operate this Windows desktop. Observe with the element tree, not with pictures: computer_windows to find a window, computer_snapshot to read its interactive elements as refs (e1, e2, ...) with a revision number, then act on those refs. Refs belong to one revision: after a newer snapshot of that window the older refs are rejected, so re-snapshot rather than guessing. To locate one control in a big window without pulling the whole tree, computer_find_text searches by text and returns click-ready centers and by descriptors.
29
+
30
+ Prefer computer_run with a planned batch over one call per click; the batch is policy-checked and verified step by step inside the machine, and it reports performedCount, which is how many actions actually reached the desktop. A delivered click does not prove the outcome: verify from fresh state, and after any cancellation inspect the tree again before retrying because completed input is not rolled back.
31
+
32
+ Actions are delivered in the background: the cursor does not move and focus is not taken. Do not retry a refused foreground action by forcing the window up. Other sessions and applications may change the same desktop underneath you.
33
+
34
+ computer_parse exists for surfaces the element tree cannot describe (canvas, games, some Electron and Chromium content, custom-drawn controls): it fuses the UIA tree with OCR of the rendered pixels and returns clickable screen coordinates for any on-screen text UIA did not already expose — this is how you drive a self-drawn app when you cannot see the screen. Use those x,y with computer_click; use a ref with computer_act for real UIA elements. computer_capture returns a raw PNG path instead, for a model that can look at pictures.
35
+
36
+ Policy is enforced before input, by this plugin and not by you: OS power or sign-out actions, application exit, and destructive deletes are refused outright, are not approvable, and the refusal names the step that triggered it. Remove that step and continue with an undoable route, or ask the user to perform it.
37
+
38
+ When the desktop task is finished (or you decide to stop), call computer_done as your final step: it dismisses the on-screen control overlay immediately. Do not rely on the overlay timing out on its own. The person at the keyboard can press Esc at any time to stop the run and hide the overlay.`;
39
+
40
+ export function apply(ctx, config = {}) {
41
+ const dataDir = config.dataDir ?? join(homedir(), '.dsh', 'native-uia');
42
+ const host = config.dashboardHost ?? '127.0.0.1';
43
+ const port = config.dashboardPort ?? 3099;
44
+ mkdirSync(join(dataDir, 'recipes'), { recursive: true });
45
+
46
+ const store = new Store();
47
+ // The chosen action-delivery mode must survive an app restart; without this the store resets to
48
+ // its hardcoded default ('background') every launch, so the control-page toggle looked like it
49
+ // forgot the user's pick.
50
+ const settingsPath = join(dataDir, 'settings.json');
51
+ const saveSettings = () => { try { writeFileSync(settingsPath, JSON.stringify({ pointerMode: store.pointerMode })); } catch { /* best-effort */ } };
52
+ try {
53
+ const saved = JSON.parse(readFileSync(settingsPath, 'utf8'));
54
+ if (saved && (saved.pointerMode === 'auto' || saved.pointerMode === 'foreground' || saved.pointerMode === 'background')) {
55
+ store.setPointerMode(saved.pointerMode);
56
+ }
57
+ } catch { /* no settings file yet */ }
58
+ const owned = new Map();
59
+ // Optional services: the desktop profile mounts neither `computerUse` nor
60
+ // `attachments`, and reading an unmounted service throws rather than returning
61
+ // undefined, which would fail activation for the whole plugin.
62
+ const optional = (name) => {
63
+ try {
64
+ return typeof ctx.get === 'function' ? ctx.get(name) : undefined;
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ };
69
+ const logger = (text, level = 'info') => store.line(text, level);
70
+
71
+ const indicator = new CuaWorker({
72
+ script: INDICATOR_SCRIPT,
73
+ logger,
74
+ // The overlay process dying used to be nearly silent (a WPF composition-thread COM crash was
75
+ // observed in the wild: WER event 1001, DUCE.Channel.SyncFlush, Node only saw "exit 2"). The
76
+ // exit handler logs one info line; this warn-level event makes the crash readable from the
77
+ // control page. Recovery needs no new code: the lazy start in CuaWorker.call respawns the
78
+ // process on the next indicator command, and Cmd-Beat/Cmd-Show re-light an invisible window.
79
+ onEvent: (kind, payload) => {
80
+ if (kind === 'worker' && payload?.started === false) {
81
+ logger(`指示层进程已退出(第 ${payload.epoch} 代):${payload.reason ?? ''};下一次指示层命令会自动重新派生`, 'warn');
82
+ }
83
+ },
84
+ });
85
+ const activity = new ActivityWindow({
86
+ indicator,
87
+ logger,
88
+ resolveBounds: () => store.target?.rect ?? null,
89
+ // subtext = 「目标应用名 · 最近一步 label(N 步)」:store.step 一直在记步骤与 stepsRun
90
+ // 计数,屏幕上的人此前只看得到应用名。claim(每个动作触发)即时刷新,beat(30 s)补
91
+ // think gap;渲染端把 subtext 当自由字符串,无需改动。见 activity-window.js composeSubtext。
92
+ resolveLabel: () => composeSubtext(store),
93
+ resolveMode: () => store.pointerMode,
94
+ // The lease IS the auto-stop backstop, and it renews only on real tool traffic (actions claim,
95
+ // observations observe) — the plugin's own heartbeat feeds the renderer but cannot extend it.
96
+ // A think gap under leaseMs keeps the capsule lit; a run the model forgot to close with
97
+ // computer_done goes out within leaseMs instead of beating forever. Expiry defers while one
98
+ // command is still in flight. DSH_NATIVE_UIA_LEASE_MS overrides both ends.
99
+ leaseMs: Number(config.leaseMs ?? process.env.DSH_NATIVE_UIA_LEASE_MS ?? 300000) || 300000,
100
+ canEnd: () => store.busy !== true,
101
+ onState: (running) => {
102
+ store.running = running;
103
+ store.emit('state', { reason: 'running', running: running === true });
104
+ },
105
+ });
106
+
107
+ const worker = new CuaWorker({
108
+ logger,
109
+ // 只读观察模式(DSH_NATIVE_UIA_READ_ONLY=1,Store 激活时置位):投递类动作在 worker-client
110
+ // 的 call() 咽喉点被拒(read_only_mode),观察命令照常——一刀切在咽喉点,不逐工具加开关。
111
+ readOnly: store.readOnly === true,
112
+ // The kill latch refuses the ONE command that was already in flight when the run was stopped.
113
+ // It is not a session-wide block: a stop the person asked for must not cost them the next
114
+ // action too.
115
+ //
116
+ // Measured failure this fixes (2026-11-21): the latch was armed by Esc, consumed by the next
117
+ // mutating call, and that call was then refused with HaltedError. The model reads "本轮已被
118
+ // 终止" as a dead session and does not retry, so `killed` stayed true and the run could never
119
+ // light again — the overlay looked unresponsive and every later action was rejected once.
120
+ // A second Esc re-armed it, so each stop kept poisoning one more action.
121
+ //
122
+ // The latch now has a deadline: it covers only the stop instant. Anything after that window
123
+ // is a NEW instruction from the person and must be delivered normally, respawning the worker.
124
+ halt: () => {
125
+ if (!store.killed) return null;
126
+ const ageMs = Date.now() - (store.killedAt ?? 0);
127
+ if (ageMs > HALT_LATCH_MS) {
128
+ // Stale: this is a fresh instruction, not the in-flight command the stop was meant for.
129
+ store.setKilled(false);
130
+ return null;
131
+ }
132
+ store.setKilled(false);
133
+ logger('上一轮已被终止:本次动作被拦下,闩锁已清除,下一次桌面操作将重新派生 worker');
134
+ return '本轮已被终止:本次没有在桌面上执行任何动作。再发起一次桌面操作即可重新派生 worker。';
135
+ },
136
+ busy: (value) => {
137
+ store.busy = value;
138
+ store.emit('state', { reason: 'busy', busy: value === true });
139
+ },
140
+ // Single owner of the overlay: input claims it, observation (already-lit runs only) renews
141
+ // its lease. Both fire from the worker client's one choke point, so no tool drives it.
142
+ onActionStart: (cmd) => {
143
+ activity.claim(cmd.startsWith('pointer_') ? { visible: true } : undefined);
144
+ },
145
+ onObserve: () => activity.observe(),
146
+ onEvent: (kind, payload) => {
147
+ if (kind === 'worker') store.line(payload.started ? `worker 已启动(第 ${payload.epoch} 代)` : `worker 已停止:${payload.reason ?? ''}(第 ${payload.epoch} 代)`);
148
+ },
149
+ });
150
+
151
+ const commands = {
152
+ async action(body) {
153
+ const kind = String(body?.kind ?? '');
154
+ if (kind === 'mode') {
155
+ const m = String(body?.mode ?? '');
156
+ if (!store.setPointerMode(m)) return { ok: false, error: `未知模式 "${m}"(background|auto|foreground)` };
157
+ // Push to a live worker now; if it is not running, the mode rides on every act/commit_batch
158
+ // call's `mode` arg, so a lazily-respawned worker still picks it up on the next action.
159
+ if (worker.running) { try { await worker.call('set_pointer_mode', { mode: store.pointerMode }, { timeoutMs: 5000 }); } catch { /* next act carries it */ } }
160
+ saveSettings();
161
+ logger(`桌面动作模式已切换为 ${store.pointerMode}`);
162
+ return { ok: true, mode: store.pointerMode };
163
+ }
164
+ if (kind === 'kill') {
165
+ store.setKilled(true);
166
+ await activity.end({ reason: '已在控制页终止' });
167
+ await worker.shutdown();
168
+ logger('已在控制页终止:worker 停止,在飞动作中断', 'error');
169
+ return { ok: true };
170
+ }
171
+ if (kind === 'setTarget') {
172
+ const win = store.windows.find((w) => w.windowId === String(body?.windowId));
173
+ if (win === undefined) return { ok: false, error: `windowId ${body?.windowId} 不在当前窗口列表里` };
174
+ store.setTarget(win);
175
+ return { ok: true };
176
+ }
177
+ if (kind === 'deny') {
178
+ const index = store.blocked.findIndex((b) => b.id === body?.blockedId);
179
+ if (index < 0) return { ok: false, error: '这条拦截记录已经不在了' };
180
+ store.blocked.splice(index, 1);
181
+ store.emit('state', { reason: 'blocked' });
182
+ return { ok: true };
183
+ }
184
+ if (kind === 'rescan') {
185
+ // 控制页「重扫」:对当前目标窗口重跑一次 snapshot 并写回 store.tree —— 与
186
+ // computer_snapshot 同一条观察通道(observe 续租,不会点亮新的 run)。
187
+ const win = store.target;
188
+ if (!win?.windowId) return { ok: false, error: '当前没有目标窗口,无法重扫' };
189
+ const result = await worker.call('snapshot', { windowId: win.windowId, maxNodes: 200 });
190
+ store.setTree(result.nodes ?? [], { windowId: win.windowId, revision: result.revision });
191
+ return { ok: true, revision: result.revision, count: (result.nodes ?? []).length };
192
+ }
193
+ if (kind === 'approve') {
194
+ return { ok: false, error: '策略拒绝不可批准;只能用「忽略」清掉这条记录' };
195
+ }
196
+ return { ok: false, error: `未知操作 "${kind}"` };
197
+ },
198
+ };
199
+
200
+ const dashboard = new Dashboard({ host, port, store, policy: POLICY, commands, dataDir });
201
+ // The native client channel: the panel component calls ctx.remote.nativeUia.*
202
+ // instead of fetching a loopback port, so it inherits host theme tokens and locale.
203
+ // Imported lazily and guarded: a resolution or decorator failure must not take
204
+ // the plugin down, and the reason has to be readable from the panel's own log.
205
+ store.remoteChannel = 'pending';
206
+ const mountRemoteChannel = async () => {
207
+ try {
208
+ const { NativeUiaRemote } = await import('./native-uia-remote.js');
209
+ // The instance self-registers inside the base constructor (TypertRemoteService mounts it on
210
+ // ctx.remote); nothing reads the handle afterwards — the mount-state carrier is
211
+ // store.remoteChannel, so a bare `new` keeps the guard shape without a dead variable.
212
+ new NativeUiaRemote(ctx, { store, commands, policy: POLICY });
213
+ store.remoteChannel = 'mounted';
214
+ logger('宿主通道已挂载:ctx.remote.nativeUia');
215
+ } catch (error) {
216
+ store.remoteChannel = { failed: true, reason: String(error?.message ?? error) };
217
+ logger(`宿主通道挂载失败,面板回退回环页:${store.remoteChannel.reason}`, 'error');
218
+ // Control experiment: both specifiers sit at the same level of the app's own
219
+ // node_modules. If one resolves and the other does not, the host resolver is
220
+ // composition-scoped, not Node-scoped, and a plugin cannot import a library
221
+ // that no bundle depends on.
222
+ const probed = [];
223
+ for (const spec of ['@deepseek-ai/dsh-tools', '@deepseek-ai/dsh-typert-protocol', '@deepseek-ai/cordis']) {
224
+ try {
225
+ await import(spec);
226
+ probed.push(`${spec}=ok`);
227
+ } catch (probeError) {
228
+ probed.push(`${spec}=${String(probeError?.code ?? probeError?.message ?? 'fail')}`);
229
+ }
230
+ }
231
+ logger(`解析对照:${probed.join(' ')}`, 'warn');
232
+ }
233
+ store.emit('state', { reason: 'remote' });
234
+ };
235
+ const unregisterTools = registerTools(ctx, {
236
+ worker,
237
+ store,
238
+ dataDir,
239
+ owned,
240
+ activity,
241
+ // The tool says "the run is over"; the overlay's owner decides what that looks like. The
242
+ // reason distinguishes WHO ended it: an idle-timeout teardown (reason:'idle') is not the
243
+ // model declaring completion — logging it as 模型宣告完成 misread a silent run as a done one.
244
+ // The outcome (from computer_done) distinguishes HOW it ended: only outcome:'done' may be
245
+ // logged as 模型宣告完成 — a blocked/failed declaration logged as completion reads the panel
246
+ // and the log as a run that succeeded.
247
+ finishRun: ({ summary = '', reason = 'done', outcome = 'done' } = {}) => {
248
+ const verdict = outcome === 'blocked'
249
+ ? '模型宣告受阻未完成'
250
+ : outcome === 'failed'
251
+ ? '模型宣告失败放弃'
252
+ : '模型宣告完成';
253
+ return activity.end({
254
+ reason: reason === 'idle'
255
+ ? `静默超时自动收尾${summary ? `:${summary}` : ''}`
256
+ : summary ? `${verdict}:${summary}` : verdict,
257
+ });
258
+ },
259
+ });
260
+
261
+ return ctx.effect(async () => {
262
+ await dashboard.listen();
263
+ logger(`控制页地址:${dashboard.url}`);
264
+ // Code-generation banner: every contract fix lives in the plugin process, and the running
265
+ // host only carries it after a restart. Logging it at activation makes "did the loaded
266
+ // build really change?" answerable from /api/state instead of from memory (verify-live
267
+ // asserts this line); if a fix seems missing, restart the host first.
268
+ logger('契约:心跳只喂渲染不续租,静默 run 在租约内自动收尾;Esc 主通道=指示层进程;find_text 已暴露为工具');
269
+ void mountRemoteChannel();
270
+ const reservation = optional('computerUse');
271
+ if (reservation !== undefined && reservation !== null) {
272
+ try {
273
+ reservation.register('native-uia');
274
+ logger('已占用宿主共享的 computer-use provider 槽位');
275
+ } catch (error) {
276
+ logger(`computer-use 槽位已被其它 provider 占用:${error?.message ?? error}`, 'error');
277
+ }
278
+ }
279
+ store.visionRoute = optional('attachments') !== undefined;
280
+
281
+ const unregisterPrompt = ctx.systemPrompt.section({
282
+ name: 'computer-use:native-uia',
283
+ order: 3000,
284
+ text: GUIDANCE,
285
+ });
286
+
287
+ // Cold-start handshake must NOT gate activation: it pays a full powershell spawn + Add-Type
288
+ // compile (~0.9 s measured on the review machine) before the effect could return, and a
289
+ // port/environment failure used to fail the whole plugin activation. worker-client already
290
+ // starts lazily and self-heals, so the first real desktop command waits for the same worker
291
+ // anyway. The handshake now warms the worker in the background; a failure is only logged
292
+ // (warn) and the next command retries the spawn.
293
+ void worker.call('ping', {}, { timeoutMs: 20000 })
294
+ .then(() => logger('worker 握手成功'))
295
+ .catch((error) => logger(`worker 握手失败(激活不受影响,下一次桌面命令会自动重试派生):${error?.message ?? error}`, 'warn'));
296
+
297
+ try {
298
+ const screens = await indicator.call('ping', {}, { timeoutMs: 20000 });
299
+ logger(`屏幕指示层就绪(${(screens.screens ?? []).length} 块屏)`);
300
+ } catch (error) {
301
+ logger(`屏幕指示层不可用,桌面动作照常执行:${error?.message ?? error}`, 'warn');
302
+ }
303
+
304
+ // Global Esc-to-stop: the control-page keydown only fires when the browser has focus, so while
305
+ // the overlay is up the host also polls for a physically-held VK_ESCAPE and ends the run.
306
+ // The INDICATOR process is the primary channel: it is idle by design and answers in ms, while
307
+ // the worker may sit inside a 40 s OCR or a long batch, where a queued probe cannot even run —
308
+ // a tapped Esc is released long before that queue drains. The worker stays as fallback for
309
+ // when the overlay itself is down. A batch already mid-flight gets NO help from the worker's
310
+ // own per-step Esc check: that one reads "held right now" only at step boundaries, so a tap
311
+ // released mid-step is invisible to it and the batch would run to completion, come back
312
+ // "all passed" and save a recipe for a run the user just stopped. That is why the handler
313
+ // below shuts the worker down exactly like the control-page kill — the pending commit comes
314
+ // back as WorkerDeadError, which computer_run reports as "user stopped, nothing rolled back".
315
+ let escBusy = false;
316
+ const escTimer = setInterval(() => {
317
+ // 40 ms, not 120: the probe is one user32 call on an idle process, and the latch (low bit)
318
+ // only helps if something reads it soon after the tap. The old 120 ms interval plus queueing
319
+ // is what made "点 ESC 停止" feel slow even when the press was caught. Keep this a literal
320
+ // number: verify.mjs pins the interval digits directly.
321
+ //
322
+ // Probe while the RUN is live, not while the overlay happens to be lit. Measured failure
323
+ // (2026-11-21): the overlay self-closes after 20 s without a tool call, so any model thinking
324
+ // pause set activity.active=false and this gate skipped every tick — a person watching the
325
+ // agent work and pressing Esc got no response at all, even though the run was still open and
326
+ // the next tool call would have landed on their screen. activity.active is a RENDERING fact;
327
+ // store.running is the run. Gate on the run, and also while a command is in flight.
328
+ if (escBusy) return;
329
+ if (store.running !== true && store.busy !== true) return;
330
+ // Never queue a probe behind real work on both channels: a probe stuck behind an OCR on the
331
+ // worker (or behind a beat on the indicator) reports the key long after the press, which is
332
+ // how quick Esc taps went unseen. Both queues empty → probe the always-fast indicator;
333
+ // indicator busy but worker idle → the worker; both busy → skip this 40 ms tick.
334
+ const probe = indicator.pending.size === 0
335
+ ? indicator
336
+ : (worker.pending.size === 0 ? worker : null);
337
+ if (probe === null) return;
338
+ escBusy = true;
339
+ probe.call('escape_pressed', {}, { timeoutMs: 1200 })
340
+ .then((r) => {
341
+ if (r && r.pressed === true) {
342
+ store.setKilled(true);
343
+ void activity.end({ reason: '用户按下 Esc' });
344
+ // Same closing sequence as the control-page kill above: a batch already mid-flight
345
+ // cannot see a tap (its per-step check needs the key held across a boundary), so
346
+ // without the shutdown it runs to completion and saves a recipe. Killing the worker
347
+ // surfaces the pending commit as WorkerDeadError. The latch is armed WITH a timestamp
348
+ // and expires (see HALT_LATCH_MS), so it refuses only that in-flight command and the
349
+ // person's next instruction still reaches the desktop.
350
+ void worker.shutdown();
351
+ logger('检测到 Esc:已停止本轮并收起指示层', 'warn');
352
+ // The overlay is gone, so nothing else will ever clear a latch nobody consumed: if the
353
+ // stopped command never came back (the common case — the model just stops), the panel
354
+ // kept showing 已终止 and the next session inherited a dead-looking run. Clearing after
355
+ // the latch window makes the state match reality: stopped, and ready for new work.
356
+ const clearAt = setTimeout(() => {
357
+ if (store.killed && Date.now() - (store.killedAt ?? 0) >= HALT_LATCH_MS) store.setKilled(false);
358
+ }, HALT_LATCH_MS + 250);
359
+ clearAt.unref?.();
360
+ }
361
+ })
362
+ .catch(() => { /* channel died or timed out; its exit is logged and the next poll retargets */ })
363
+ .finally(() => { escBusy = false; });
364
+ }, 40);
365
+ escTimer.unref?.();
366
+
367
+ return async () => {
368
+ clearInterval(escTimer);
369
+ await activity.dispose();
370
+ unregisterTools();
371
+ if (typeof unregisterPrompt === 'function') unregisterPrompt();
372
+ await worker.shutdown();
373
+ await indicator.shutdown();
374
+ dashboard.close();
375
+ };
376
+ }, 'dsh-native-uia');
377
+ }
@@ -0,0 +1,80 @@
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
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * 御屏裸包名行的宿主半边(面板 face):什么都不注册。
3
+ *
4
+ * 一个包两行组件(与灵犀同构):
5
+ * · 裸名行(本入口)= 卡片 + 会话面板 —— client-modules 只从已挂载 loader 条目上发现
6
+ * `dsh.client`,且强制一包一个 client 源,所以面板必须挂这一行;它的存在就是页签开关。
7
+ * · /desktop 行(src/index.js)= 桌面操控工具,可单独关。
8
+ */
9
+ export const name = 'dsh-native-uia';
10
+ export const inject = [];
11
+
12
+ export function apply() {
13
+ console.log('[dsh-native-uia] 面板行已挂载(页签由 client/client.js 注册,数据来自本机控制页服务)');
14
+ }
package/src/state.js ADDED
@@ -0,0 +1,177 @@
1
+ import { EventEmitter } from 'node:events';
2
+
3
+ const LIMITS = { steps: 200, log: 300, blocked: 120, windows: 80, tree: 900 };
4
+
5
+ function trim(list, max) {
6
+ while (list.length > max) list.shift();
7
+ }
8
+
9
+ export class Store extends EventEmitter {
10
+ windows = [];
11
+ tree = [];
12
+ steps = [];
13
+ blocked = [];
14
+ log = [];
15
+ screenshot = null;
16
+ target = null;
17
+ killed = false;
18
+ // When the kill latch was armed (ms epoch). index.js uses the age to decide whether a mutating
19
+ // command is the one the person stopped or their next instruction — see HALT_LATCH_MS there.
20
+ killedAt = 0;
21
+ // Read-only observation mode: read once at activation from DSH_NATIVE_UIA_READ_ONLY=1. The
22
+ // desktop worker refuses every ACTION_COMMANDS delivery at the call() choke point (error code
23
+ // read_only_mode); the observation whitelist (snapshot/find_text/parse/ocr) stays available.
24
+ // guard.POLICY.note names the mode from the same env switch.
25
+ readOnly = process.env.DSH_NATIVE_UIA_READ_ONLY === '1';
26
+ pointerMode = 'background';
27
+ running = false;
28
+ visionRoute = false;
29
+ counters = { stepsRun: 0, actions: 0, blocked: 0, refused: 0, stepMsTotal: 0, stepSamples: 0 };
30
+
31
+ /* Views shared by snapshot() and the state-class SSE frames: a partial frame must carry
32
+ the same mapped shape a full snapshot delivers, or the panel would render two dialects.
33
+ The emits used to carry {reason} only — the live stream kept the panel "fresh"
34
+ (refreshing lastEventAt and suppressing the polling fallback) while delivering nothing
35
+ the page could render, so windows/tree/target/killed/busy/pointerMode froze during live. */
36
+ #targetView() {
37
+ return this.target === null ? null : {
38
+ windowId: this.target.windowId,
39
+ appName: this.target.appName,
40
+ title: this.target.title,
41
+ };
42
+ }
43
+
44
+ #windowsView() {
45
+ return this.windows.map((w) => ({
46
+ windowId: w.windowId,
47
+ appName: w.appName,
48
+ title: w.title,
49
+ pid: w.pid,
50
+ rect: w.rect,
51
+ isForeground: w.isForeground === true,
52
+ }));
53
+ }
54
+
55
+ #treeView() {
56
+ return this.tree.map((n) => ({
57
+ ref: n.ref,
58
+ controlType: n.controlType,
59
+ name: n.name ?? '',
60
+ className: n.className ?? '',
61
+ depth: n.depth ?? 0,
62
+ patterns: n.patterns ?? [],
63
+ enabled: n.enabled !== false,
64
+ isOffscreen: n.isOffscreen === true,
65
+ rect: n.rect ?? null,
66
+ }));
67
+ }
68
+
69
+ setTarget(window) {
70
+ this.target = window ?? null;
71
+ this.emit('state', { reason: 'target', target: this.#targetView() });
72
+ }
73
+
74
+ setWindows(windows) {
75
+ this.windows = windows.slice(0, LIMITS.windows);
76
+ this.emit('state', { reason: 'windows', windows: this.#windowsView() });
77
+ }
78
+
79
+ setTree(nodes, meta) {
80
+ this.tree = nodes.slice(0, LIMITS.tree);
81
+ this.treeMeta = meta ?? null;
82
+ this.emit('state', { reason: 'tree', tree: this.#treeView() });
83
+ }
84
+
85
+ setScreenshot(entry) {
86
+ this.screenshot = { ...entry, at: Date.now() };
87
+ this.emit('screenshot', this.screenshot);
88
+ }
89
+
90
+ step(step) {
91
+ this.steps.push({ id: `s${this.steps.length + 1}`, at: Date.now(), ...step });
92
+ trim(this.steps, LIMITS.steps);
93
+ this.counters.stepsRun++;
94
+ if (typeof step.ms === 'number') {
95
+ this.counters.stepMsTotal += step.ms;
96
+ this.counters.stepSamples++;
97
+ }
98
+ this.emit('step', this.steps[this.steps.length - 1]);
99
+ return this.steps[this.steps.length - 1];
100
+ }
101
+
102
+ actionDone(n = 1) {
103
+ this.counters.actions += n;
104
+ }
105
+
106
+ block(entry) {
107
+ this.blocked.push({ id: `b${this.blocked.length + 1}`, at: Date.now(), ...entry });
108
+ trim(this.blocked, LIMITS.blocked);
109
+ this.counters.blocked++;
110
+ this.emit('blocked', this.blocked[this.blocked.length - 1]);
111
+ return this.blocked[this.blocked.length - 1];
112
+ }
113
+
114
+ line(text, level = 'info') {
115
+ this.log.push({ at: Date.now(), level, text });
116
+ trim(this.log, LIMITS.log);
117
+ this.emit('log', this.log[this.log.length - 1]);
118
+ }
119
+
120
+ setKilled(value) {
121
+ this.killed = value;
122
+ // Arming records WHEN. The kill latch refuses only the command that was in flight at the
123
+ // stop instant; index.js reads this age to tell "the stopped command" from "the person's next
124
+ // instruction". Without the timestamp every arm looked infinitely old or brand new.
125
+ if (value === true) this.killedAt = Date.now();
126
+ this.emit('state', { reason: 'killed', killed: this.killed });
127
+ }
128
+
129
+ setPointerMode(value) {
130
+ if (value !== 'background' && value !== 'auto' && value !== 'foreground') return false;
131
+ this.pointerMode = value;
132
+ this.emit('state', { reason: 'pointerMode', pointerMode: value });
133
+ return true;
134
+ }
135
+
136
+ snapshot(policy) {
137
+ const c = this.counters;
138
+ return {
139
+ session: {
140
+ busy: this.busy === true,
141
+ running: this.running === true,
142
+ killed: this.killed,
143
+ pointerMode: this.pointerMode,
144
+ target: this.#targetView(),
145
+ policy,
146
+ remoteChannel: this.remoteChannel ?? 'pending',
147
+ stats: {
148
+ stepsRun: c.stepsRun,
149
+ actions: c.actions,
150
+ blocked: c.blocked,
151
+ refused: c.refused,
152
+ avgStepMs: c.stepSamples > 0 ? Math.round(c.stepMsTotal / c.stepSamples) : 0,
153
+ visionRoute: this.visionRoute,
154
+ },
155
+ },
156
+ windows: this.#windowsView(),
157
+ tree: this.#treeView(),
158
+ steps: this.steps.map((s) => ({
159
+ id: s.id,
160
+ label: s.label,
161
+ kind: s.kind ?? 'action',
162
+ status: s.status,
163
+ ms: s.ms ?? null,
164
+ verify: s.verify ?? null,
165
+ detail: s.detail ?? null,
166
+ screenshotUrl: s.screenshotUrl ?? null,
167
+ })),
168
+ blocked: this.blocked.map((b) => ({
169
+ id: b.id,
170
+ reason: b.reason,
171
+ raw: b.raw ?? null,
172
+ at: new Date(b.at).toISOString().slice(11, 19),
173
+ })),
174
+ log: this.log.map((l) => ({ at: new Date(l.at).toISOString().slice(11, 19), level: l.level, text: l.text })),
175
+ };
176
+ }
177
+ }