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/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "dsh-native-uia",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "displayName": "御屏 · 桌面操控",
5
+ "description": "以 Windows UI Automation 控件树为主观测通道的桌面操控插件:纯文本模型即可操控桌面,后台投递动作(不动鼠标、不抢焦点),一次调用批量执行并逐步校验,成功批次自动存为可回放配方。",
6
+ "type": "module",
7
+ "icon": "./icon.svg",
8
+ "main": "./src/panel-face.js",
9
+ "exports": {
10
+ ".": "./src/panel-face.js",
11
+ "./desktop": "./src/index.js",
12
+ "./client": "./client/client.js",
13
+ "./package.json": "./package.json",
14
+ "./locale/*.json": "./locale/*.json",
15
+ "./desktop/locale/*.json": "./locale/desktop/*.json"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "worker",
20
+ "web",
21
+ "client",
22
+ "scripts",
23
+ "locale",
24
+ "icon.svg",
25
+ "cordis.patch.yml",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "scripts": {
30
+ "check": "node scripts/verify.mjs",
31
+ "install-plugin": "node scripts/install.mjs install",
32
+ "uninstall-plugin": "node scripts/install.mjs remove",
33
+ "status": "node scripts/install.mjs status",
34
+ "worker:ping": "node scripts/smoke.mjs"
35
+ },
36
+ "keywords": [
37
+ "deepseek-harness",
38
+ "dsh",
39
+ "dsh-bundle",
40
+ "cordis",
41
+ "plugin",
42
+ "computer-use",
43
+ "ui-automation",
44
+ "uia",
45
+ "windows"
46
+ ],
47
+ "license": "MIT",
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/xiaobaga281/dsh-native-uia.git"
51
+ },
52
+ "homepage": "https://github.com/xiaobaga281/dsh-native-uia#readme",
53
+ "bugs": {
54
+ "url": "https://github.com/xiaobaga281/dsh-native-uia/issues"
55
+ },
56
+ "author": "xiaobaga281",
57
+ "dsh": {
58
+ "bundle": {
59
+ "patch": "./cordis.patch.yml"
60
+ },
61
+ "client": {
62
+ "platform": "web",
63
+ "inject": [
64
+ "@deepseek-ai/dsh-api-remotes",
65
+ "@deepseek-ai/dsh-client-ui-renderer",
66
+ "@deepseek-ai/dsh-client-ui-slots",
67
+ "@deepseek-ai/dsh-client-ui-conversation"
68
+ ]
69
+ }
70
+ },
71
+ "dependencies": {
72
+ "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2"
73
+ },
74
+ "peerDependencies": {
75
+ "@deepseek-ai/cordis": "*",
76
+ "@deepseek-ai/dsh-tools": "*",
77
+ "@deepseek-ai/dsh-typert-protocol": "*"
78
+ },
79
+ "engines": {
80
+ "node": ">=18.0.0"
81
+ }
82
+ }
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Read-only live benchmark. Drives the production CuaWorker client exactly like
4
+ * scripts/smoke.mjs does (spawn / JSON-lines framing / shutdown all live in
5
+ * src/worker-client.js) and sends NOTHING but observations:
6
+ * ping, list_windows, snapshot (default args) ×5, find_text ×3, shutdown.
7
+ * No act, no capture, no pointer/keyboard command, no mouse or touch of the desktop.
8
+ *
9
+ * stdout carries exactly ONE JSON line (the benchmark record); every diagnostic
10
+ * goes to stderr, so `node scripts/bench-live.mjs 2>/dev/null` yields the record alone.
11
+ */
12
+ import { CuaWorker, WorkerCommandError } from '../src/worker-client.js';
13
+
14
+ // 宿主/终端侧进程不算被测窗口:本脚本自身(node)、worker(powershell)、宿主应用。
15
+ const HOST_APP = /powershell|pwsh|cmd|node|conhost|windowsterminal|openconsole|zcode|koishi/i;
16
+ const WATCHDOG_MS = 60000;
17
+
18
+ const worker = new CuaWorker({ logger: (m) => console.error(` . ${m}`) });
19
+ const t0 = Date.now();
20
+ const log = (m) => console.error(`[bench] ${m}`);
21
+
22
+ function percentile(sorted, p) {
23
+ // 线性插值(与常见分位数定义一致);调用前先升序排序。
24
+ if (sorted.length === 0) return 0;
25
+ const idx = (sorted.length - 1) * p;
26
+ const lo = Math.floor(idx);
27
+ const hi = Math.ceil(idx);
28
+ if (lo === hi) return sorted[lo];
29
+ return sorted[lo] + (sorted[hi] - sorted[lo]) * (idx - lo);
30
+ }
31
+ const median = (arr) => percentile([...arr].sort((a, b) => a - b), 0.5);
32
+
33
+ // 硬性总时长闸门:超过 60s 视为卡死,清进程后以失败退出,绝不硬造数字。
34
+ let done = false;
35
+ const watchdog = setTimeout(() => {
36
+ if (done) return;
37
+ log(`超过 ${WATCHDOG_MS} ms 未完成,强制退出`);
38
+ void worker.shutdown({ killMs: 2000 }).finally(() => process.exit(3));
39
+ }, WATCHDOG_MS);
40
+
41
+ async function main() {
42
+ // 预热 = spawn + 握手(worker 冷启动约 1s 就绪),不计入采样。
43
+ const ping = await worker.call('ping', {}, { timeoutMs: 30000 });
44
+ log(`worker 就绪 (${Date.now() - t0} ms) powershell ${ping?.psVersion ?? '?'}`);
45
+
46
+ const lw = await worker.call('list_windows', { onlyVisible: true }, { timeoutMs: 30000 });
47
+ const all = lw.windows ?? [];
48
+ log(`可见窗口 ${all.length} 个`);
49
+
50
+ // 选窗:排除宿主/终端侧进程;优先前台窗口;选不出就退回任意可见窗口。
51
+ const candidates = all.filter((w) => !HOST_APP.test(String(w.appName ?? '')));
52
+ const pool = candidates.length > 0 ? candidates : all;
53
+ if (pool.length === 0) throw new Error('list_windows 没有返回任何可见窗口,无法采样');
54
+ const picked =
55
+ pool.find((w) => w.isForeground === true && w.isMinimized !== true) ??
56
+ pool.find((w) => w.isForeground === true) ??
57
+ pool.find((w) => w.isMinimized !== true && (w.rect?.w ?? 0) > 0 && (w.rect?.h ?? 0) > 0) ??
58
+ pool[0];
59
+ log(`选中窗口 id=${picked.windowId} app=${picked.appName} fg=${picked.isForeground} title="${picked.title}"`);
60
+ const windowId = picked.windowId;
61
+ const windowLabel = String(picked.title ?? '').trim() !== ''
62
+ ? String(picked.title).slice(0, 120)
63
+ : `${picked.appName ?? ''}:${windowId}`;
64
+
65
+ // 取针词:窗口标题里的一个常见字(有 CJK 取第一个汉字,否则取第一个字母/数字;
66
+ // find_text 是大小写不敏感的字面包含匹配,uia-worker.ps1:2723)。标题为空则从
67
+ // 第一次 snapshot 的节点名里取,再取不到就失败退出——不造数字。
68
+ let needle = '';
69
+ const title = String(picked.title ?? '');
70
+ const cjk = title.match(/[\u4e00-\u9fff]/);
71
+ const ascii = title.match(/[A-Za-z0-9]/);
72
+ if (cjk) needle = cjk[0];
73
+ else if (ascii) needle = ascii[0].toLowerCase();
74
+
75
+ const snaps = [];
76
+ for (let i = 0; i < 5; i++) {
77
+ const w0 = performance.now();
78
+ const r = await worker.call('snapshot', { windowId }, { timeoutMs: 30000 });
79
+ const wallMs = Math.round(performance.now() - w0);
80
+ const nodeCount = r?.nodeCount ?? (Array.isArray(r?.nodes) ? r.nodes.length : 0);
81
+ if (nodeCount === 0) throw new Error(`snapshot 第 ${i + 1} 次返回 0 节点,窗口树为空,无法采样`);
82
+ snaps.push({
83
+ msPerNode: Number(r.msPerNode),
84
+ ms: Number.isFinite(Number(r.ms)) ? Number(r.ms) : wallMs, // 返回值自带耗时;缺失才退回墙钟
85
+ nodeCount,
86
+ wallMs,
87
+ truncated: r.truncated === true,
88
+ visited: r.visited,
89
+ partialReason: r.partialReason ?? '',
90
+ });
91
+ log(`snapshot#${i + 1}: ${nodeCount} 节点, ms=${r.ms}, msPerNode=${r.msPerNode}, wall=${wallMs}ms, visited=${r.visited}${r.partialReason ? ', partial=' + r.partialReason : ''}`);
92
+ if (needle === '') {
93
+ const named = (r.nodes ?? []).find((n) => String(n.name ?? '').trim().length > 0);
94
+ if (named) {
95
+ const s = String(named.name).trim();
96
+ const c = s.match(/[\u4e00-\u9fff]/) ?? s.match(/[A-Za-z0-9]/);
97
+ if (c) needle = c[0].toLowerCase();
98
+ }
99
+ }
100
+ }
101
+ if (needle === '') throw new Error('标题与节点名都取不出针词,find_text 无法采样');
102
+
103
+ // 一次性子树路径的节点数对照(评审⑤):快照的 visited(全树遍历数,无 maxNodes 截断时)
104
+ // 与 find_text 的 scanned(FindAll 全量数)应一致;FindAll(TrueCondition) 与 ControlViewWalker
105
+ // 的节点集合是 provider 特定行为,这里只对照记录,不做硬断言。
106
+ let nodesFull = 0;
107
+ try {
108
+ const full = await worker.call('snapshot', { windowId, maxNodes: 4000 }, { timeoutMs: 30000 });
109
+ nodesFull = Number(full?.nodeCount ?? 0);
110
+ log(`snapshot#full(maxNodes=4000): ${nodesFull} 节点, ms=${full?.ms}, msPerNode=${full?.msPerNode}, truncated=${full?.truncated}`);
111
+ } catch (e) {
112
+ log(`snapshot#full 失败(不影响主采样): ${e?.message ?? e}`);
113
+ }
114
+
115
+ const findMs = [];
116
+ let findMatches = 0;
117
+ let findScanned = 0;
118
+ for (let i = 0; i < 3; i++) {
119
+ const w0 = performance.now();
120
+ const r = await worker.call('find_text', { windowId, text: needle }, { timeoutMs: 30000 });
121
+ findMs.push(Math.round(performance.now() - w0));
122
+ findMatches = r?.count ?? 0;
123
+ findScanned = r?.scanned ?? 0;
124
+ log(`find_text#${i + 1} "${needle}": count=${r?.count} scanned=${r?.scanned} wall=${findMs[i]}ms`);
125
+ }
126
+
127
+ const record = {
128
+ window: windowLabel,
129
+ nodes: Math.round(median(snaps.map((s) => s.nodeCount))),
130
+ msPerNodeP50: percentile(snaps.map((s) => s.msPerNode).sort((a, b) => a - b), 0.5),
131
+ msPerNodeP95: percentile(snaps.map((s) => s.msPerNode).sort((a, b) => a - b), 0.95),
132
+ snapshotMsP50: percentile(snaps.map((s) => s.ms).sort((a, b) => a - b), 0.5),
133
+ findTextMsP50: percentile(findMs.slice().sort((a, b) => a - b), 0.5),
134
+ // 一次性子树路径对照(见上方注释)
135
+ nodesFull,
136
+ visited: snaps[snaps.length - 1]?.visited,
137
+ findScanned,
138
+ partialReasons: [...new Set(snaps.map((s) => s.partialReason).filter((x) => x !== ''))],
139
+ ts: new Date().toISOString(),
140
+ };
141
+ log(`针词="${needle}" find命中=${findMatches} snapshot截断=${snaps.some((s) => s.truncated)} 总时长=${Date.now() - t0}ms`);
142
+ console.log(JSON.stringify(record)); // stdout 只有这一行
143
+ }
144
+
145
+ try {
146
+ await main();
147
+ done = true;
148
+ process.exitCode = 0;
149
+ } catch (error) {
150
+ done = true;
151
+ const detail = error instanceof WorkerCommandError ? `${error.code}: ${error.message}` : String(error?.message ?? error);
152
+ console.error(`[bench] 失败: ${detail}`);
153
+ process.exitCode = 1;
154
+ } finally {
155
+ clearTimeout(watchdog);
156
+ try { await worker.shutdown({ killMs: 5000 }); } catch { /* exit handler 已覆盖 */ }
157
+ }
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Focused check of the overlay lease fix (no real indicator, no desktop):
3
+ *
4
+ * 1. a run that only observes keeps its lease — the bug was that the lease renewed only on the
5
+ * next *mutating* action, so a long think gap dropped the capsule mid-run;
6
+ * 2. the heartbeat beats on its own while a run is active;
7
+ * 3. observation before any action never claims (a read-only session must not light the screen);
8
+ * 4. end() stops the lease and the heartbeat.
9
+ *
10
+ * Run: node scripts/check-lease.mjs
11
+ */
12
+ import assert from 'node:assert';
13
+ import { ActivityWindow } from '../src/activity-window.js';
14
+
15
+ function fakeIndicator() {
16
+ const calls = [];
17
+ return {
18
+ calls,
19
+ async call(cmd, args) {
20
+ calls.push({ cmd, args });
21
+ return { ok: true };
22
+ },
23
+ };
24
+ }
25
+
26
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27
+
28
+ // --- 1 + 2: observation-only run survives a gap far longer than the old 90 s lease -------------
29
+ {
30
+ const indicator = fakeIndicator();
31
+ // Tiny timings so the test runs in milliseconds: lease 300 ms, beat 60 ms — the same ratios as
32
+ // production (300 s / 30 s) with the same code path.
33
+ const activity = new ActivityWindow({ indicator, leaseMs: 300, beatMs: 60 });
34
+ activity.claim();
35
+ assert.equal(activity.active, true, 'claim did not activate the window');
36
+ assert.equal(indicator.calls[0].cmd, 'show', 'claim did not show the overlay');
37
+
38
+ // Observed steps only (what computer_snapshot / computer_windows do inside a run).
39
+ for (let i = 0; i < 8; i++) {
40
+ await sleep(50);
41
+ activity.observe(); // renews the lease...
42
+ }
43
+ await sleep(120); // ...and the heartbeat covers the gaps between them
44
+
45
+ assert.equal(activity.active, true, 'a long observation-only stretch dropped the run (the bug)');
46
+ const beats = indicator.calls.filter((c) => c.cmd === 'beat').length;
47
+ assert(beats >= 3, `heartbeat did not fire: only ${beats} beat(s)`);
48
+ assert(!indicator.calls.some((c) => c.cmd === 'phase' && c.args.phase === 'stopped'), 'the run was收尾 while it was still observing');
49
+
50
+ await activity.end({ reason: 'test' });
51
+ const stopped = indicator.calls.find((c) => c.cmd === 'phase' && c.args.phase === 'stopped');
52
+ assert(stopped !== undefined, 'end() did not send the stopped phase');
53
+ const after = indicator.calls.length;
54
+ await sleep(150);
55
+ assert.equal(indicator.calls.length, after, 'end() left a timer running (heartbeat or lease)');
56
+ console.log('✅ 观察期不再掉租约:心跳持续、end() 收尾后无残留定时器');
57
+ }
58
+
59
+ // --- 3: pure observation must not light the overlay -------------------------------------------
60
+ {
61
+ const indicator = fakeIndicator();
62
+ const activity = new ActivityWindow({ indicator, leaseMs: 200, beatMs: 50 });
63
+ activity.observe();
64
+ activity.observe();
65
+ await sleep(80);
66
+ assert.equal(activity.active, false, 'observe() claimed a run that never acted');
67
+ assert.equal(indicator.calls.length, 0, 'observe() talked to the overlay before any action');
68
+ console.log('✅ 只读会话不点亮指示层(observe 前无 action 时静默)');
69
+ }
70
+
71
+ // --- 4: an unclaimed end() is a no-op (never sends a stray phase) ------------------------------
72
+ {
73
+ const indicator = fakeIndicator();
74
+ const activity = new ActivityWindow({ indicator, leaseMs: 200, beatMs: 50 });
75
+ await activity.end({ reason: 'nothing was running' });
76
+ assert.equal(indicator.calls.length, 0, 'end() on an inactive window still sent a command');
77
+ console.log('✅ 未激活时 end() 不发命令');
78
+ }
79
+
80
+ // --- 5: kill stops the run, and the next action restarts the same capsule -----------------------
81
+ {
82
+ const indicator = fakeIndicator();
83
+ const activity = new ActivityWindow({ indicator, leaseMs: 300, beatMs: 60 });
84
+ activity.claim();
85
+ await activity.end({ reason: 'kill' }); // control-page 终止
86
+ assert.equal(activity.active, false, 'end() left the window active');
87
+ assert.equal(activity.phase, 'stopped', 'the window does not report stopped after a kill');
88
+ const stopped = indicator.calls.find((c) => c.cmd === 'phase' && c.args.phase === 'stopped');
89
+ assert(stopped !== undefined, 'end() did not paint the stopped phase');
90
+ assert(indicator.calls.filter((c) => c.cmd === 'phase').length === 1, 'a stop painted more than the one phase it should');
91
+
92
+ activity.claim(); // the documented restart path
93
+ assert.equal(activity.active, true, 'the next action did not restart the capsule');
94
+ assert.equal(activity.phase, 'acting', 'the window does not report acting after the restart');
95
+ // `end()` left the window inactive, so the restart goes through `show` (which carries
96
+ // phase:'acting'), not through a second `phase` command. Either way the pill must come
97
+ // back as acting with a fresh label, never sit on the stale "stopped" wording.
98
+ const phases = indicator.calls
99
+ .filter((c) => c.cmd === 'phase')
100
+ .map((c) => c.args.phase);
101
+ assert.deepEqual(phases, ['stopped'], `the stop painted ${JSON.stringify(phases)}`);
102
+ const showsAfter = indicator.calls.slice(indicator.calls.indexOf(stopped) + 1).filter((c) => c.cmd === 'show');
103
+ assert.equal(showsAfter.length, 1, `expected one show for the restart, got ${showsAfter.length}`);
104
+ assert.equal(showsAfter[0].args.phase, 'acting', 'the restart did not come back as acting');
105
+ assert(typeof showsAfter[0].args.subtext === 'string', 'the restart did not carry the subtext, so the second line went stale');
106
+ assert(showsAfter[0].args.idleHideMs !== undefined, 'the restart did not re-arm the idle watchdog');
107
+ console.log('✅ 终止→「御屏 · 已停止」→ 下一次动作重新点亮胶囊(show + acting + 新 subtext)');
108
+ }
109
+
110
+ // --- 6: no third state exists (the paused state was removed from the product) ---------------------
111
+ {
112
+ const indicator = fakeIndicator();
113
+ const activity = new ActivityWindow({ indicator, leaseMs: 200, beatMs: 50 });
114
+ assert.equal(typeof activity.waiting, 'undefined', 'waiting() is back: a state no switch can reach is dead code');
115
+ assert.equal(typeof activity.resume, 'undefined', 'resume() is back: nothing can resume a run that cannot pause');
116
+ activity.claim();
117
+ activity.claim(); // two claims in a row must stay in acting
118
+ const phases = indicator.calls.filter((c) => c.cmd === 'phase').map((c) => c.args.phase);
119
+ assert.deepEqual(phases, [], `a claim produced a phase change: ${JSON.stringify(phases)}`);
120
+
121
+ // The one remaining `phase: 'acting'` sender: a claim on a live window that is not acting
122
+ // (defensive — nothing sets that today, but the branch must not go untested and drift).
123
+ const indicator2 = fakeIndicator();
124
+ const activity2 = new ActivityWindow({ indicator: indicator2, leaseMs: 300, beatMs: 60 });
125
+ activity2.claim();
126
+ activity2.phase = 'stopped'; // simulate a stale non-acting phase
127
+ activity2.claim();
128
+ const phases2 = indicator2.calls.filter((c) => c.cmd === 'phase').map((c) => c.args.phase);
129
+ assert.deepEqual(phases2, ['acting'], `the stale phase was not repainted: ${JSON.stringify(phases2)}`);
130
+ const flip = indicator2.calls.find((c) => c.cmd === 'phase');
131
+ assert(typeof flip.args.subtext === 'string' && typeof flip.args.mode === 'string', 'the phase flip did not carry subtext+mode');
132
+ console.log('✅ 只有 acting/stopped 两态;连点动作不产生多余相位切换;陈旧相位会被重绘');
133
+ }
134
+
135
+ // --- 7: an unclaimed claim lights the screen; an unclaimed end() does not -------------------------
136
+ {
137
+ const indicator = fakeIndicator();
138
+ const activity = new ActivityWindow({ indicator, leaseMs: 200, beatMs: 50 });
139
+ await activity.end({ reason: 'nothing was running' });
140
+ assert.equal(activity.active, false, 'end() on an inactive window activated it');
141
+ assert.equal(indicator.calls.length, 0, 'end() on an inactive window still sent a command');
142
+ activity.claim();
143
+ assert.equal(activity.active, true, 'a real claim did not start the overlay');
144
+ assert.equal(indicator.calls[0].cmd, 'show', 'a claim did not show the overlay');
145
+ console.log('✅ 未激活时 end() 静默;真 claim 才点亮(show)');
146
+ }
147
+
148
+ // --- 8: the choke point classifies commands, and internal probes stay silent ---------------------
149
+ // This is the flicker regression: the Esc watchdog polls `escape_pressed` every 40 ms. When the
150
+ // client inferred "observation = not an action", each poll renewed the lease and beat the overlay
151
+ // ~8×/s, which interleaved with the 100 ms pulse and made the ring visibly flicker.
152
+ {
153
+ const { CuaWorker } = await import('../src/worker-client.js');
154
+ const fired = { action: [], observe: [] };
155
+ const worker = new CuaWorker({
156
+ logger: () => {},
157
+ onActionStart: (cmd) => fired.action.push(cmd),
158
+ onObserve: (cmd) => fired.observe.push(cmd),
159
+ });
160
+ // Never spawn PowerShell: the classification runs before the request is written, and the
161
+ // returned promise is deliberately left pending (we only assert which hook fired).
162
+ worker.start = () => {};
163
+ worker.proc = { stdin: { write: () => {} }, exitCode: null, killed: false };
164
+
165
+ const fire = (cmd) => { worker.call(cmd, {}, { timeoutMs: 5 }).catch(() => {}); };
166
+
167
+ for (let i = 0; i < 20; i++) fire('escape_pressed'); // the 40 ms watchdog
168
+ fire('ping');
169
+ fire('set_pointer_mode');
170
+ fire('snapshot');
171
+ fire('list_windows');
172
+ fire('describe');
173
+ fire('capture');
174
+ fire('ocr');
175
+ fire('wait');
176
+ fire('prepare_batch');
177
+ fire('find_text');
178
+ fire('resolve_window');
179
+ fire('pointer_target');
180
+ fire('act');
181
+ fire('pointer_click');
182
+ await sleep(30);
183
+
184
+ assert.deepEqual(fired.observe.filter((c) => c === 'escape_pressed'), [],
185
+ 'escape_pressed renewed the lease: the Esc watchdog would beat the overlay ~8×/s and the ring would flicker');
186
+ // Only the two real input commands fired here may reach the action hook; the probes must not.
187
+ assert.deepEqual([...fired.action].sort(), ['act', 'pointer_click'],
188
+ `the action hook saw ${JSON.stringify(fired.action)}: a probe leaked into it`);
189
+ assert.deepEqual([...fired.observe].sort(), ['capture', 'describe', 'find_text', 'list_windows', 'ocr', 'pointer_target', 'prepare_batch', 'resolve_window', 'snapshot', 'wait'],
190
+ `observation whitelist drifted: ${JSON.stringify(fired.observe)}`);
191
+ console.log('✅ 咽喉点分类正确:内部探针(escape_pressed/ping/set_pointer_mode)静默,10 个观测命令续租');
192
+ }
193
+
194
+ // --- 9: the heartbeat renders, but a SILENT run still goes out (the 用完不停止 regression) -------
195
+ // The immortal-capsule bug: the heartbeat re-armed the lease every 30 s, so a run the model never
196
+ // closed with computer_done beat forever and the overlay never stopped. The lease must expire on
197
+ // real-activity silence alone — while the beat keeps the renderer fed up to that moment.
198
+ {
199
+ const indicator = fakeIndicator();
200
+ const activity = new ActivityWindow({ indicator, leaseMs: 150, beatMs: 40 });
201
+ activity.claim(); // one action starts the run…
202
+ await sleep(520); // …then total silence: >3 lease periods
203
+ assert.equal(activity.active, false, 'a silent run is still alive: the heartbeat renewed the lease again (immortal capsule)');
204
+ const stopped = indicator.calls.find((c) => c.cmd === 'phase' && c.args.phase === 'stopped');
205
+ assert(stopped !== undefined, 'the expired run did not paint 已停止 on the way out');
206
+ const beats = indicator.calls.filter((c) => c.cmd === 'beat').length;
207
+ assert(beats >= 3, `the heartbeat stopped feeding the renderer before expiry: only ${beats} beat(s)`);
208
+ const after = indicator.calls.length;
209
+ await sleep(150);
210
+ assert.equal(indicator.calls.length, after, 'a dead run is still beating');
211
+
212
+ // Expiry must defer, not fire, while one command is genuinely in flight.
213
+ const ind2 = fakeIndicator();
214
+ let busy = true;
215
+ const activity2 = new ActivityWindow({ indicator: ind2, canEnd: () => !busy, leaseMs: 100, beatMs: 40 });
216
+ activity2.claim();
217
+ await sleep(250); // two lease periods… but busy
218
+ assert.equal(activity2.active, true, 'the lease expired mid-action and dropped the capsule during real work');
219
+ busy = false;
220
+ await sleep(250); // …then silence: it must go out
221
+ assert.equal(activity2.active, false, 'after busy cleared, the deferred lease never ended the run');
222
+ console.log('✅ 心跳只喂渲染不续租:静默 run 在租约内必熄灭;动作在飞时过期推迟而非硬收');
223
+ }
224
+
225
+ // --- 10: the subtext carries batch progress (appName · last step label (N steps)) ----------------
226
+ // The pill's second line used to be just the target app name: store.step recorded every step's
227
+ // label and the stepsRun counter, but none of it reached the overlay, so the person watching the
228
+ // screen could not tell how far the batch had gotten. The composition lives in composeSubtext()
229
+ // (activity-window.js, beside the palette — index.js only wires store into it via resolveLabel)
230
+ // and the result must reach the overlay through EVERY send site: claim's show, a claim on a live
231
+ // window (beat), observe's beat, the heartbeat beat, the stale-phase repaint, and the
232
+ // withoutIndicator restore.
233
+ {
234
+ const { composeSubtext } = await import('../src/activity-window.js');
235
+ const { Store } = await import('../src/state.js');
236
+
237
+ const store = new Store();
238
+ assert.equal(composeSubtext(store), '', 'a session with no target must keep the empty subtext');
239
+ store.setTarget({ windowId: 'w1', appName: '记事本', title: 't' });
240
+ assert.equal(composeSubtext(store), '记事本', 'with no steps yet the subtext stays the bare app name');
241
+ store.step({ label: '点击 确定', status: 'passed' });
242
+ store.step({ label: '输入 御屏', status: 'passed' });
243
+ assert.equal(composeSubtext(store), '记事本 · 输入 御屏(2 步)', 'the subtext must name the last step and the step count');
244
+
245
+ // The count is the RUN counter, not steps.length: the store trims steps at 200, so a long run
246
+ // would freeze the display at exactly 200 forever if the length were read instead.
247
+ for (let i = 0; i < 201; i++) store.step({ label: `s${i}`, status: 'passed' });
248
+ assert.equal(store.steps.length, 200, 'the store should have trimmed steps to its cap');
249
+ assert.equal(composeSubtext(store), '记事本 · s200(203 步)', 'the count must come from counters.stepsRun, not the trimmed steps.length');
250
+
251
+ // Real chain end to end: real Store → real composeSubtext → ActivityWindow's subtext at all
252
+ // six send sites. Timings: lease 600 ms keeps expiry out of the way, beat 40 ms fires one
253
+ // heartbeat inside the 50 ms pause below.
254
+ const composed = composeSubtext(store);
255
+ const indicator = fakeIndicator();
256
+ const activity = new ActivityWindow({ indicator, leaseMs: 600, beatMs: 40, resolveLabel: () => composeSubtext(store) });
257
+ activity.claim(); // show
258
+ activity.claim(); // beat (claim on a live acting window)
259
+ activity.observe(); // beat (observation renew)
260
+ await sleep(50); // beat (heartbeat)
261
+ activity.phase = 'stopped';
262
+ activity.claim(); // phase acting (stale-phase repaint)
263
+ await activity.withoutIndicator(async () => {}); // phase hidden + acting (restore branch)
264
+ const sent = indicator.calls.filter((c) => c.cmd === 'show' || c.cmd === 'beat' || (c.cmd === 'phase' && c.args.phase === 'acting'));
265
+ const kinds = { show: 0, beat: 0, acting: 0 };
266
+ for (const c of sent) {
267
+ kinds[c.cmd === 'show' ? 'show' : c.cmd === 'beat' ? 'beat' : 'acting']++;
268
+ assert.equal(c.args.subtext, composed, `${c.cmd} did not carry the progress subtext`);
269
+ }
270
+ assert(kinds.show >= 1 && kinds.beat >= 3 && kinds.acting >= 2, `a send site was not exercised: ${JSON.stringify(kinds)}`);
271
+ console.log('✅ 指示层 subtext 携带批次进度「appName · 最近一步(N 步)」:show/beat×3/相位重绘/恢复分支全透传,计数用 stepsRun');
272
+ }
273
+
274
+ // --- 11: read-only observation mode refuses input at the choke point and never lights the overlay
275
+ // P-10: with readOnly, every ACTION_COMMANDS member is refused one layer ABOVE the halt latch —
276
+ // before busy()/claim() — so a read-only session (unattended evaluation/demo, DSH_NATIVE_UIA_
277
+ // READ_ONLY=1) cannot light the indicator at all, while the observation whitelist keeps working.
278
+ {
279
+ const { CuaWorker } = await import('../src/worker-client.js');
280
+ const fired = { action: [], observe: [] };
281
+ const worker = new CuaWorker({
282
+ readOnly: true,
283
+ logger: () => {},
284
+ onActionStart: (cmd) => fired.action.push(cmd),
285
+ onObserve: (cmd) => fired.observe.push(cmd),
286
+ });
287
+ worker.start = () => {};
288
+ worker.proc = { stdin: { write: () => {} }, exitCode: null, killed: false };
289
+
290
+ // Every command that can put input on the desktop must answer read_only_mode…
291
+ const inputs = ['act', 'commit_batch', 'launch', 'close_window', 'pointer_click', 'pointer_drag', 'pointer_scroll', 'type_text', 'key'];
292
+ for (const cmd of inputs) {
293
+ await assert.rejects(worker.call(cmd, {}), (error) => error.code === 'read_only_mode',
294
+ `${cmd} was not refused in read-only mode`);
295
+ }
296
+ assert.equal(worker.stats.readOnlyRefused, inputs.length, 'read-only refusals are not counted in stats');
297
+ // …and none of them may reach the claim hook: 只读会话不点亮指示层(拒绝发生在 claim 之前)。
298
+ assert.equal(fired.action.length, 0, 'a read-only refusal claimed the overlay: 只读会话点亮了指示层');
299
+ // 观察照常:懒派生 worker(此处 stub 掉)后走 observe 分支,续租通道不受只读影响。
300
+ // fire-and-forget(同第 8 节):stub 管道永不回包,await 会挂满 30 s 的 unref 超时;
301
+ // onObserve 在 call() 内同步触发,短超时让 promise 以可捕获的方式落定。
302
+ worker.call('snapshot', {}, { timeoutMs: 5 }).catch(() => {});
303
+ await sleep(20);
304
+ assert.deepEqual(fired.observe, ['snapshot'], 'an observation command did not ride the normal observe path in read-only mode');
305
+ console.log('✅ 只读观察模式:投递类动作在咽喉点拒绝(read_only_mode)且不点亮指示层,观察命令照常');
306
+ }
307
+
308
+ console.log('\n全部通过:租约/心跳/观察续租/终止与重启/探针静默/静默自熄/进度 subtext/只读咽喉点行为符合预期(两态)');