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
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Read-only worker smoke: it drives the production CuaWorker client (so stdio
4
+ * framing, ASCII escaping, timeouts and noise detection are all exercised) and
5
+ * never sends an action. The negative test is mandatory: a worker that answers
6
+ * an unknown command is not speaking this protocol.
7
+ */
8
+ import { writeFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { homedir } from 'node:os';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { CuaWorker, WorkerCommandError } from '../src/worker-client.js';
13
+
14
+ const DATA = join(homedir(), '.dsh', 'native-uia');
15
+ const INDICATOR_SCRIPT = fileURLToPath(new URL('../worker/indicator-server.ps1', import.meta.url));
16
+ const worker = new CuaWorker({ logger: (m) => console.log(` . ${m}`) });
17
+ const rows = [];
18
+ let failures = 0;
19
+
20
+ async function step(name, fn) {
21
+ const t0 = Date.now();
22
+ try {
23
+ const detail = await fn();
24
+ rows.push({ name, ok: true, ms: Date.now() - t0, detail });
25
+ console.log(`[PASS] ${name} (${Date.now() - t0} ms) ${detail ?? ''}`);
26
+ } catch (error) {
27
+ failures++;
28
+ const detail = error instanceof WorkerCommandError ? `${error.code}: ${error.message}` : String(error?.message ?? error);
29
+ rows.push({ name, ok: false, ms: Date.now() - t0, detail });
30
+ console.log(`[FAIL] ${name} (${Date.now() - t0} ms) ${detail}`);
31
+ }
32
+ }
33
+
34
+ await step('ping (spawn + handshake)', async () => {
35
+ const r = await worker.call('ping', {}, { timeoutMs: 30000 });
36
+ if (!r?.psVersion) throw new WorkerCommandError('no psVersion in result', 'bad_result', r);
37
+ return `powershell ${r.psVersion} workerPid=${r.station ? r.workerPid : '?'}`;
38
+ });
39
+
40
+ let windowId = null;
41
+ await step('list_windows', async () => {
42
+ const r = await worker.call('list_windows', {});
43
+ const windows = r.windows ?? r ?? [];
44
+ if (windows.length === 0) throw new WorkerCommandError('zero windows', 'empty', r);
45
+ const candidate = windows.find((w) => /explorer|Chrome|msedge|Firefox|Notepad|This PC|File Explorer|Program Manager/i.test(`${w.title} ${w.appName}`)) ?? windows[0];
46
+ windowId = candidate.windowId;
47
+ return `${windows.length} windows, using ${windowId} "${String(candidate.title).slice(0, 40)}"`;
48
+ });
49
+
50
+ await step('unknown command is refused (MUST FIRE)', async () => {
51
+ try {
52
+ const r = await worker.call('this_cmd_does_not_exist', {}, { timeoutMs: 10000 });
53
+ throw new WorkerCommandError(`worker accepted a command outside the contract: ${JSON.stringify(r).slice(0, 80)}`, 'protocol_violation', r);
54
+ } catch (error) {
55
+ if (error instanceof WorkerCommandError && error.code === 'protocol_violation') throw error;
56
+ if (error.code !== 'unknown_cmd') throw new WorkerCommandError(`refused with the wrong code: ${error.code}`, 'wrong_code', error);
57
+ return 'code=unknown_cmd, loop survived';
58
+ }
59
+ });
60
+
61
+ await step('loop still serves after the refusal', async () => {
62
+ const r = await worker.call('list_windows', {});
63
+ const n = (r.windows ?? r ?? []).length;
64
+ if (n === 0) throw new WorkerCommandError('worker went silent after a bad request', 'dead_after_noise', null);
65
+ return `${n} windows`;
66
+ });
67
+
68
+ let snapshotBytes = 0;
69
+ await step('snapshot (tree channel)', async () => {
70
+ const r = await worker.call('snapshot', { windowId, maxNodes: 200 }, { timeoutMs: 30000 });
71
+ const nodes = r.nodes ?? [];
72
+ if (nodes.length === 0) throw new WorkerCommandError('snapshot returned no nodes', 'empty_tree', null);
73
+ if (typeof r.revision !== 'number') throw new WorkerCommandError('snapshot has no revision', 'no_revision', r);
74
+ snapshotBytes = JSON.stringify(r).length;
75
+ const withPatterns = nodes.filter((n) => (n.patterns ?? []).length > 0).length;
76
+ const interactive = nodes.filter((n) => /Button|Edit|MenuItem|ListItem|ComboBox|TabItem|CheckBox|Hyperlink/.test(n.controlType ?? '')).length;
77
+ return `${nodes.length} nodes rev=${r.revision} ${snapshotBytes} bytes (~${Math.round(snapshotBytes / 4)} tok) interactive=${interactive} withPatterns=${withPatterns} truncated=${r.truncated === true}`;
78
+ });
79
+
80
+ await step('stale revision is rejected (MUST FIRE)', async () => {
81
+ const first = await worker.call('snapshot', { windowId, maxNodes: 40 }, { timeoutMs: 30000 });
82
+ const ref = (first.nodes ?? [])[0]?.ref;
83
+ if (ref === undefined) throw new WorkerCommandError('no ref to test with', 'empty_tree', null);
84
+ await worker.call('snapshot', { windowId, maxNodes: 40 }, { timeoutMs: 30000 });
85
+ const stale = first.revision - 0;
86
+ try {
87
+ await worker.call('describe', { ref, revision: stale - 1 }, { timeoutMs: 15000 });
88
+ } catch (error) {
89
+ if (error.code === 'stale_revision' || error.code === 'revision_mismatch') return `code=${error.code}`;
90
+ return `refused early with ${error.code} (acceptable if refs are revision-scoped)`;
91
+ }
92
+ throw new WorkerCommandError('describe accepted a stale revision', 'protocol_violation', null);
93
+ });
94
+
95
+ await step('describe resolves one ref', async () => {
96
+ const snap = await worker.call('snapshot', { windowId, maxNodes: 120 }, { timeoutMs: 30000 });
97
+ const node = (snap.nodes ?? []).find((n) => (n.patterns ?? []).length > 0) ?? (snap.nodes ?? [])[0];
98
+ if (node === undefined) throw new WorkerCommandError('nothing to describe', 'empty_tree', null);
99
+ const d = await worker.call('describe', { ref: node.ref }, { timeoutMs: 15000 });
100
+ if (!d?.controlType) throw new WorkerCommandError('descriptor has no controlType', 'bad_result', d);
101
+ return `${node.ref} -> ${d.controlType} "${String(d.name ?? '').slice(0, 24)}" patterns=${(d.patterns ?? d.availablePatterns ?? []).join('|') || 'none'}`;
102
+ });
103
+
104
+ await step('capture a background window as PNG', async () => {
105
+ const r = await worker.call('capture', { windowId }, { timeoutMs: 45000 });
106
+ if (!r?.pngBase64) throw new WorkerCommandError('no pngBase64 returned', 'bad_result', r);
107
+ const bytes = Buffer.from(r.pngBase64, 'base64');
108
+ writeFileSync(join(DATA, 'smoke-capture.png'), bytes);
109
+ if (r.blank === true) throw new WorkerCommandError(`capture came back blank via ${r.method}`, 'blank_capture', r);
110
+ return `${r.width}x${r.height} via ${r.method} = ${bytes.length} bytes -> smoke-capture.png`;
111
+ });
112
+
113
+ await step('find_text locates text and returns a click-ready center', async () => {
114
+ // A permanent live check for the command behind computer_find_text: the tool, the
115
+ // observation whitelist, and the click guidance all reference find_text — none of them
116
+ // means anything if the worker command drifts.
117
+ const snap = await worker.call('snapshot', { windowId, maxNodes: 60 }, { timeoutMs: 30000 });
118
+ const named = (snap.nodes ?? []).find((n) => String(n.name ?? '').trim().length >= 4);
119
+ if (named === undefined) throw new WorkerCommandError('no named node to search for', 'empty_tree', null);
120
+ const needle = String(named.name).trim().slice(0, 6);
121
+ const hit = await worker.call('find_text', { windowId, text: needle, max: 10 }, { timeoutMs: 15000 });
122
+ if (!Array.isArray(hit.matches)) throw new WorkerCommandError('no matches array', 'bad_result', hit);
123
+ const m = hit.matches.find((x) => String(x.name).includes(needle)) ?? hit.matches[0];
124
+ if (m === undefined) throw new WorkerCommandError(`find_text did not find "${needle}" it should have`, 'miss', hit);
125
+ if (!Number.isFinite(m.center?.x) || !Number.isFinite(m.center?.y)) throw new WorkerCommandError('match has no numeric center', 'bad_result', m);
126
+ if (!m.by?.name || !m.by?.controlType) throw new WorkerCommandError('match has no by descriptor', 'bad_result', m);
127
+ return `"${needle}" scanned=${hit.scanned} count=${hit.count} center=(${m.center.x},${m.center.y})`;
128
+ });
129
+
130
+ await step('indicator answers escape_pressed (the host Esc channel)', async () => {
131
+ // The overlay process is the PRIMARY Esc watchdog channel: the worker can sit inside a long
132
+ // OCR/batch for tens of seconds, where a tapped Esc is gone before the queue drains. A read of
133
+ // key state must cost milliseconds and never light the screen (this spawns no capsule).
134
+ const indicator = new CuaWorker({ script: INDICATOR_SCRIPT, logger: (m) => console.log(` . ${m}`) });
135
+ try {
136
+ const ping = await indicator.call('ping', {}, { timeoutMs: 25000 });
137
+ if ((ping.screens ?? []).length === 0) throw new WorkerCommandError('indicator sees no screen', 'bad_result', ping);
138
+ const t0 = Date.now();
139
+ const e = await indicator.call('escape_pressed', {}, { timeoutMs: 4000 });
140
+ if (typeof e?.pressed !== 'boolean') throw new WorkerCommandError('escape_pressed did not answer with a boolean', 'bad_result', e);
141
+ return `screens=${(ping.screens ?? []).length} pressed=${e.pressed} rt=${Date.now() - t0}ms`;
142
+ } finally {
143
+ await indicator.shutdown({ killMs: 5000 });
144
+ }
145
+ });
146
+
147
+ await step('shutdown exits cleanly', async () => {
148
+ await worker.shutdown({ killMs: 5000 });
149
+ if (worker.running) throw new WorkerCommandError('worker still alive after shutdown', 'not_stopped', null);
150
+ return `requests=${worker.stats.requests} noiseLines=${worker.stats.noise}`;
151
+ });
152
+
153
+ console.log(`\n${rows.filter((r) => r.ok).length}/${rows.length} passed`);
154
+ if (failures > 0) {
155
+ console.log('failures:');
156
+ for (const r of rows.filter((x) => !x.ok)) console.log(` ${r.name}: ${r.detail}`);
157
+ }
158
+ process.exit(failures > 0 ? 1 : 0);
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Live proof that a downscaled window capture is the WHOLE window, not its top-left crop.
4
+ * Before the fix Capture() painted PrintWindow into an already-shrunk bitmap, so the picture
5
+ * showed only the top-left corner at native scale while claiming to be the full window (and
6
+ * every OCR coordinate taken from it was displaced).
7
+ */
8
+ import { CuaWorker } from '../src/worker-client.js';
9
+ import { writeFileSync } from 'node:fs';
10
+
11
+ const worker = new CuaWorker({ logger: (m) => console.log(` . ${m}`) });
12
+ function pngSize(buf) { return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) }; }
13
+
14
+ let code = 0;
15
+ try {
16
+ const list = await worker.call('list_windows', {});
17
+ const windows = list.windows ?? list ?? [];
18
+ const target = windows.find((w) => w.rect.w > 900 && w.rect.h > 600) ?? windows[0];
19
+ const windowId = target.windowId;
20
+ console.log(`window ${windowId} ${target.rect.w}x${target.rect.h}`);
21
+ const native = await worker.call('capture', { windowId, maxDim: 0 }, { timeoutMs: 45000 });
22
+ const small = await worker.call('capture', { windowId, maxDim: 800 }, { timeoutMs: 45000 });
23
+ const nSize = pngSize(Buffer.from(native.pngBase64, 'base64'));
24
+ const sSize = pngSize(Buffer.from(small.pngBase64, 'base64'));
25
+ console.log(`native ${nSize.w}x${nSize.h} scale=${native.scaleX} | small ${sSize.w}x${sSize.h} scale=${small.scaleX}`);
26
+ writeFileSync('smoke-capture-small.png', Buffer.from(small.pngBase64, 'base64'));
27
+ writeFileSync('smoke-capture-native.png', Buffer.from(native.pngBase64, 'base64'));
28
+ if (sSize.w !== 800) { console.log(`[FAIL] maxDim=800 produced ${sSize.w}px wide`); code = 1; }
29
+ const expectH = Math.round((nSize.h * 800) / nSize.w);
30
+ if (Math.abs(sSize.h - expectH) > 1) { console.log(`[FAIL] aspect ${sSize.h} vs expected ${expectH}`); code = 1; }
31
+ if (Math.abs(small.scaleX - nSize.w / sSize.w) > 0.02) { console.log(`[FAIL] reported scaleX ${small.scaleX} but real ${(nSize.w / sSize.w).toFixed(3)}`); code = 1; }
32
+ if (code === 0) console.log('[PASS] downscaled capture keeps the full frame geometry');
33
+ } catch (error) {
34
+ console.log(`[FAIL] ${error.code ?? ''} ${error.message}`);
35
+ code = 1;
36
+ } finally { await worker.shutdown({ killMs: 5000 }); }
37
+ process.exit(code);
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * OPT-IN live check for computer_type's clipboard channel (P-05 ②, 真机项).
4
+ *
5
+ * 默认不跑:必须显式设 DSH_TEST_CLIPBOARD=1。它不是只读的(与 smoke/bench 的契约不同):
6
+ * - 会 LAUNCH 一个记事本窗口并 CLOSE 它(本脚本启动、本脚本负责关闭);
7
+ * - 会覆盖用户剪贴板(脚本结束时尽力恢复原文本内容,图形内容不恢复);
8
+ * - 会发送一次 ctrl+v(SendInput,落点=刚启动的记事本编辑区)。
9
+ *
10
+ * 受控用例:启动记事本 → 找 Edit ref → type_text via="clipboard" 投递短文本 →
11
+ * wait value_equals 校验落盘 → set_value 清空 → close_window。任何一步失败都以非零码退出,
12
+ * 并尽力关闭窗口。
13
+ *
14
+ * 跑法: DSH_TEST_CLIPBOARD=1 node scripts/verify-live-clipboard.mjs
15
+ */
16
+ import { execFileSync } from 'node:child_process';
17
+ import { CuaWorker } from '../src/worker-client.js';
18
+
19
+ const MARKER = process.env.DSH_TEST_CLIPBOARD;
20
+ if (MARKER !== '1') {
21
+ console.log('verify-live-clipboard 是 opt-in 真机项:会启动/关闭记事本、覆盖剪贴板并发送一次 ctrl+v。');
22
+ console.log('确认后用 DSH_TEST_CLIPBOARD=1 node scripts/verify-live-clipboard.mjs 运行;默认什么都不做。');
23
+ process.exit(0);
24
+ }
25
+
26
+ const worker = new CuaWorker({ logger: (m) => console.log(` . ${m}`) });
27
+ const failures = [];
28
+ const step = (name, fn) => {
29
+ const t0 = Date.now();
30
+ try {
31
+ const detail = fn();
32
+ console.log(`[PASS] ${name} (${Date.now() - t0} ms) ${detail ?? ''}`);
33
+ return detail;
34
+ } catch (error) {
35
+ failures.push(`${name}: ${error?.message ?? error}`);
36
+ console.log(`[FAIL] ${name} (${Date.now() - t0} ms) ${error?.code ? error.code + ': ' : ''}${error?.message ?? error}`);
37
+ return null;
38
+ }
39
+ };
40
+
41
+ // 剪贴板原文(尽力恢复;图形/多格式内容不恢复,脚本头已声明)。
42
+ const savedClipboard = (() => {
43
+ try {
44
+ return execFileSync('powershell.exe', ['-NoProfile', '-Command', 'Get-Clipboard -Raw'], { encoding: 'utf8', timeout: 10000 });
45
+ } catch {
46
+ return null;
47
+ }
48
+ })();
49
+ if (savedClipboard !== null) console.log(` . 已暂存原剪贴板文本(${savedClipboard.replace(/\s+$/, '').length} 字符),结束时恢复`);
50
+
51
+ const TEXT = `御屏剪贴板投递测试 ${Date.now()}`;
52
+ let windowId = null;
53
+
54
+ try {
55
+ const launch = await worker.call('launch', { app: 'notepad', timeoutMs: 12000 }, { timeoutMs: 30000 });
56
+ windowId = launch?.windowId ?? null;
57
+ step('启动记事本', () => `pid=${launch?.pid} window=${windowId} matchedBy=${launch?.matchedBy}`);
58
+
59
+ // Win11 多标签记事本的编辑区是 Document(带 Value),老版是 Edit——两者都按「有 Value pattern」
60
+ // 定位,不钉 ControlType。launch 必须是真正的新窗口(title-hint-reuse 会命中用户已开窗口,
61
+ // 那种情况宁可中止也不能往用户的文档里投递)。
62
+ if (/reuse/.test(String(launch?.matchedBy ?? ''))) {
63
+ throw new Error(`launch 复用了已有窗口(matchedBy=${launch.matchedBy}),为避免误投递中止`);
64
+ }
65
+ const snap = await worker.call('snapshot', { windowId, maxNodes: 60 }, { timeoutMs: 30000 });
66
+ const edit = (snap.nodes ?? []).find((n) => (n.patterns ?? []).includes('Value'));
67
+ if (!edit?.ref) throw new Error('记事本里没找到带 Value pattern 的编辑区元素,无法投递');
68
+ step('定位编辑区', () => `ref=${edit.ref} type=${edit.controlType} name="${edit.name}"`);
69
+
70
+ // ctrl+v 是「在光标处插入」而非替换:Win11 记事本会恢复上次会话的标签内容,先把编辑区清空
71
+ // (UIA set_value,后台动作),让 value_equals 的全等判据成立。
72
+ await worker.call('act', { ref: edit.ref, action: 'set_value', value: '', revision: snap.revision }, { timeoutMs: 20000 });
73
+ step('清空编辑区', () => 'set_value ""(ctrl+v 是插入不是替换,先给一个确定起点)');
74
+
75
+ const typed = await worker.call('type_text', { text: TEXT, via: 'clipboard', windowId }, { timeoutMs: 30000 });
76
+ step('via=clipboard 投递', () => `chars=${typed.chars} via=${typed.via} ms=${typed.ms}`);
77
+ if (typed.via !== 'clipboard') throw new Error(`worker 回报 via=${typed.via},clipboard 通道没有生效`);
78
+
79
+ const wait = await worker.call(
80
+ 'wait',
81
+ { windowId, condition: { type: 'value_equals', ref: edit.ref, expect: TEXT }, timeoutMs: 5000 },
82
+ { timeoutMs: 15000 },
83
+ );
84
+ step('value_equals 校验', () => `matched=${wait.matched} observed="${wait.observed}"`);
85
+ if (wait.matched !== true) throw new Error(`剪贴板投递后校验未命中:observed="${wait.observed}"`);
86
+
87
+ await worker.call('act', { ref: edit.ref, action: 'set_value', value: '', revision: snap.revision }, { timeoutMs: 20000 });
88
+ step('清空编辑区', () => 'set_value ""(避免关闭时弹保存对话框)');
89
+
90
+ console.log(failures.length === 0 ? '\n✅ 剪贴板通道真机用例通过(投递→校验→清理→关窗)' : `\n❌ ${failures.length} 步失败`);
91
+ } catch (error) {
92
+ failures.push(String(error?.message ?? error));
93
+ console.log(`[FAIL] ${error?.code ? error.code + ': ' : ''}${error?.message ?? error}`);
94
+ } finally {
95
+ if (windowId !== null) {
96
+ try { await worker.call('close_window', { windowId, timeoutMs: 3000 }, { timeoutMs: 15000 }); } catch { /* 尽力关闭 */ }
97
+ }
98
+ if (savedClipboard !== null && savedClipboard.trim() !== '') {
99
+ try {
100
+ // base64 中转:直接 stdin 传文本会在 powershell 参数里被代码页改写。
101
+ const b64 = Buffer.from(savedClipboard, 'utf8').toString('base64');
102
+ execFileSync('powershell.exe', ['-NoProfile', '-Command', 'Set-Clipboard -Value ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($args[0])))', b64], { timeout: 10000, stdio: ['ignore', 'ignore', 'pipe'] });
103
+ console.log(' . 原剪贴板文本已恢复');
104
+ } catch { console.log(' . 原剪贴板恢复失败'); }
105
+ }
106
+ try { await worker.shutdown({ killMs: 3000 }); } catch { /* exit 覆盖 */ }
107
+ }
108
+ process.exitCode = failures.length === 0 ? 0 : 1;
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Live gate: proves the plugin activated inside the running desktop app by
4
+ * asking the plugin's own loopback server. Nothing here passes on the strength
5
+ * of a file existing — the answer has to come from the loaded process.
6
+ */
7
+ import { get, request } from 'node:http';
8
+
9
+ const BASE = process.env.UIA_CONTROL ?? 'http://127.0.0.1:3099';
10
+ const WAIT_MS = Number(process.env.WAIT_MS ?? 90000);
11
+
12
+ function httpJson(path, options = {}) {
13
+ return new Promise((resolve, reject) => {
14
+ const req = request(`${BASE}${path}`, options, (res) => {
15
+ let body = '';
16
+ res.setEncoding('utf8');
17
+ res.on('data', (chunk) => (body += chunk));
18
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body, headers: res.headers }));
19
+ });
20
+ req.setTimeout(4000, () => req.destroy(new Error('timed out')));
21
+ req.on('error', reject);
22
+ if (options.body !== undefined) req.end(options.body);
23
+ else req.end();
24
+ });
25
+ }
26
+
27
+ const started = Date.now();
28
+ let snapshot = null;
29
+ let lastError = '';
30
+ while (snapshot === null) {
31
+ try {
32
+ const res = await httpJson('/api/state');
33
+ if (res.status !== 200) throw new Error(`HTTP ${res.status}`);
34
+ snapshot = JSON.parse(res.body);
35
+ var headers = res.headers;
36
+ } catch (error) {
37
+ lastError = String(error?.message ?? error);
38
+ if (Date.now() - started > WAIT_MS) {
39
+ console.log(`[FAIL] no control server at ${BASE} after ${Math.round((Date.now() - started) / 1000)}s: ${lastError}`);
40
+ console.log(' the plugin never activated, or DeepSeek Harness has not been restarted since the install');
41
+ process.exit(1);
42
+ }
43
+ await new Promise((done) => setTimeout(done, 2000));
44
+ }
45
+ }
46
+
47
+ const checks = [];
48
+ const check = (name, ok, detail = '') => checks.push({ name, ok, detail });
49
+
50
+ check('control server answers', true, BASE);
51
+ check('session block present', snapshot.session !== undefined, JSON.stringify(snapshot.session?.stats ?? {}));
52
+ check('policy names the blocked categories', Array.isArray(snapshot.session?.policy?.deniedCategories), (snapshot.session?.policy?.deniedCategories ?? []).join(','));
53
+ check('policy refusals are marked non-approvable', snapshot.session?.policy?.approvable === false, `approvable=${snapshot.session?.policy?.approvable}`);
54
+ check('vision route reported as a measured fact', typeof snapshot.session?.stats?.visionRoute === 'boolean', `visionRoute=${snapshot.session?.stats?.visionRoute}`);
55
+ check('target starts unclaimed', snapshot.session?.target === null, JSON.stringify(snapshot.session?.target));
56
+
57
+ const page = await httpJson('/control.html');
58
+ check('control page is served', page.status === 200 && page.body.length > 20000, `${page.status} ${page.body.length} bytes`);
59
+
60
+ const approve = await httpJson('/api/action', {
61
+ method: 'POST',
62
+ headers: { 'content-type': 'application/json', 'x-dsh-cua': '1' },
63
+ body: JSON.stringify({ kind: 'approve', blockedId: 'b1' }),
64
+ });
65
+ check('approve on a policy refusal is refused (MUST FIRE)', /"ok"\s*:\s*false/.test(approve.body), `${approve.status} ${approve.body.slice(0, 110)}`);
66
+
67
+ const unheadered = await httpJson('/api/action', {
68
+ method: 'POST',
69
+ headers: { 'content-type': 'application/json' },
70
+ body: JSON.stringify({ kind: 'setTarget', windowId: 'w1' }),
71
+ });
72
+ check('POST without the plugin header is refused (MUST FIRE)', unheadered.status === 403, `${unheadered.status} ${unheadered.body.slice(0, 90)}`);
73
+
74
+ check('no CORS header, so other local pages cannot read state', headers?.['access-control-allow-origin'] === undefined, `access-control-allow-origin=${headers?.['access-control-allow-origin'] ?? 'none'}`);
75
+
76
+ const liveState = JSON.parse((await httpJson('/api/state')).body);
77
+ check('the snapshot publishes the kill latch and no pause state', liveState.session.killed === false && liveState.session.paused === undefined, `killed=${liveState.session.killed} paused=${liveState.session.paused}`);
78
+
79
+ const pauseGone = await httpJson('/api/action', {
80
+ method: 'POST',
81
+ headers: { 'content-type': 'application/json', 'x-dsh-cua': '1' },
82
+ body: JSON.stringify({ kind: 'pause' }),
83
+ });
84
+ check('the pause switch is gone (unknown kind, MUST FIRE)', /"ok"\s*:\s*false/.test(pauseGone.body), `${pauseGone.status} ${pauseGone.body.slice(0, 110)}`);
85
+
86
+ const sse = await new Promise((resolve) => {
87
+ const req = get(`${BASE}/api/stream`, (res) => {
88
+ let body = '';
89
+ res.setEncoding('utf8');
90
+ const timer = setTimeout(() => {
91
+ req.destroy();
92
+ resolve(body);
93
+ }, 1200);
94
+ timer.unref?.();
95
+ res.on('data', (chunk) => (body += chunk));
96
+ });
97
+ req.on('error', () => resolve(''));
98
+ });
99
+ check('stream endpoint opens and announces a state frame', /^event: state/m.test(sse), `${sse.length} bytes before close`);
100
+
101
+ // Code-generation gate: the running process must carry the lease/Esc/find_text contract fixes.
102
+ // A restart is the only way the loaded build changes, so this answers "did it really happen?".
103
+ const banner = (liveState.log ?? []).some((l) => String(l.text).includes('心跳只喂渲染不续租'));
104
+ check('loaded build carries the lease/Esc/find_text contract banner', banner,
105
+ banner ? 'seen in activation log' : 'the host still runs an older plugin generation: restart DeepSeek Harness');
106
+
107
+ for (const c of checks) console.log(`[${c.ok ? 'PASS' : 'FAIL'}] ${c.name}${c.detail ? ` — ${c.detail}` : ''}`);
108
+ const failed = checks.filter((c) => !c.ok).length;
109
+ console.log(`\n${checks.length - failed}/${checks.length} live checks passed`);
110
+ process.exit(failed > 0 ? 1 : 0);
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Locator round trip, no desktop input: a `by` descriptor that find_text hands back must be
4
+ * resolvable by prepare_batch (the same path computer_run/computer_replay take). This is the
5
+ * contract that used to break silently — nth/nearPoint dropped the id/exact conditions, and
6
+ * descriptors were built from truncated display names.
7
+ */
8
+ import { CuaWorker } from '../src/worker-client.js';
9
+
10
+ const worker = new CuaWorker({ logger: (m) => console.log(` . ${m}`) });
11
+ let code = 0;
12
+ const fail = (m) => { console.log(`[FAIL] ${m}`); code = 1; };
13
+
14
+ try {
15
+ const list = await worker.call('list_windows', {});
16
+ const windows = list.windows ?? list ?? [];
17
+ const target = windows.find((w) => w.rect.w > 600) ?? windows[0];
18
+ const windowId = target.windowId;
19
+
20
+ // 1. a documented comma-separated controlType filter must not empty the tree
21
+ const filtered = await worker.call('snapshot', { windowId, maxNodes: 120, filter: { controlType: 'Button,Edit' } });
22
+ const fNodes = filtered.nodes ?? [];
23
+ if (fNodes.length === 0) fail('controlType="Button,Edit" returned 0 elements');
24
+ else if (fNodes.some((n) => n.controlType !== 'Button' && n.controlType !== 'Edit')) fail('controlType filter let an unrelated type through');
25
+ else console.log(`[PASS] controlType set filter: ${fNodes.length} nodes, only Button/Edit`);
26
+
27
+ // 2. every descriptor find_text returns must resolve through prepare_batch
28
+ const searched = await worker.call('find_text', { windowId, text: target.title.slice(0, 4) || 'e', max: 5 });
29
+ const matches = (searched.matches ?? []).filter((m) => m.by);
30
+ if (matches.length === 0) fail('find_text returned no by-descriptor to check');
31
+ else {
32
+ const steps = matches.map((m) => ({ by: m.by, action: 'focus' }));
33
+ const prep = await worker.call('prepare_batch', { steps, windowId });
34
+ const unresolved = (prep.descriptors ?? []).filter((d) => d.error || d.code);
35
+ if (prep.allResolved !== true) fail(`prepare_batch allResolved=${prep.allResolved}: ${JSON.stringify(unresolved).slice(0, 300)}`);
36
+ else console.log(`[PASS] ${steps.length}/${steps.length} find_text descriptors resolve, allResolved=true`);
37
+ }
38
+
39
+ // 3. an exact name must stay exact when a sibling only shares a prefix
40
+ const anyName = matches[0]?.name;
41
+ if (anyName) {
42
+ const exact = await worker.call('find_text', { windowId, text: anyName, exact: true, max: 20 });
43
+ const bad = (exact.matches ?? []).filter((m) => m.name !== anyName);
44
+ if (bad.length > 0) fail(`exact search returned ${bad.length} non-identical names`);
45
+ else console.log(`[PASS] exact search stays exact (${(exact.matches ?? []).length} hit)`);
46
+ }
47
+ } catch (error) {
48
+ fail(`${error.code ?? ''} ${error.message}`);
49
+ } finally {
50
+ await worker.shutdown({ killMs: 5000 });
51
+ }
52
+ process.exit(code);