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,154 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Register or unregister this plugin in a DeepSeek Harness desktop profile.
4
+ * Only two keys of the profile package.json are touched: `dsh.profile.bundles`
5
+ * and `dependencies`. Both edits are derived from the file as it is on disk,
6
+ * never from a copied-out list, and every run leaves a timestamped backup.
7
+ */
8
+ import { readFileSync, writeFileSync, copyFileSync, existsSync, mkdirSync } from 'node:fs';
9
+ import { dirname, join, resolve, isAbsolute } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { homedir } from 'node:os';
12
+
13
+ // The plugin is registered wherever THIS COPY lives, derived from the script's own location and
14
+ // never from a fixed path. A distribution handed to another person lands in a different folder
15
+ // (different user name, different drive), and a hardcoded root made `install` write a link: to a
16
+ // directory that does not exist on their machine — the profile then failed to resolve the bundle.
17
+ const CORE_NAME = 'dsh-native-uia';
18
+ const CORE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
19
+ // Informational only (status output / docs). DSH_PLUGIN_ROOT still overrides the displayed root for
20
+ // people who keep plugins somewhere unusual.
21
+ const PLUGIN_ROOT = process.env.DSH_PLUGIN_ROOT ?? join(homedir(), '.dsh', 'plugins');
22
+ /**
23
+ * One package, multiple components — the WorkBuddy shape. The single package is
24
+ * the only bundle and the only profile dependency; the panel is its client half
25
+ * (`dsh.client` in the same manifest), so there are no component packages to
26
+ * link and no rows beyond the one bare-name row the patch inserts.
27
+ */
28
+ import { readdirSync } from 'node:fs';
29
+ const ALL = [{ name: CORE_NAME, dir: CORE_DIR }];
30
+ // DSH_PROFILE is often a bare profile NAME ("desktop"), not a path — the host exports it that way.
31
+ // Joining it directly produced "desktop\package.json" relative to the cwd and status failed with
32
+ // "profile manifest not found" even though the plugin was correctly registered. Accept both forms.
33
+ const PROFILE_HOME = join(homedir(), '.dsh', 'profiles');
34
+ function resolveProfile(value) {
35
+ if (value === undefined || value === '') return join(PROFILE_HOME, 'desktop');
36
+ return isAbsolute(value) ? value : join(PROFILE_HOME, value);
37
+ }
38
+ const PROFILE = resolveProfile(process.env.DSH_PROFILE);
39
+ const MANIFEST = join(PROFILE, 'package.json');
40
+ const mode = process.argv[2] ?? 'status';
41
+
42
+ if (!existsSync(join(CORE_DIR, 'client', 'client.js'))) {
43
+ console.error(`FAIL ${CORE_DIR}/client/client.js is missing; the manifest declares dsh.client but the panel bundle is gone`);
44
+ process.exit(1);
45
+ }
46
+ for (const pkg of ALL) {
47
+ if (!existsSync(join(pkg.dir, 'package.json'))) {
48
+ console.error(`FAIL component ${pkg.name} is not on disk at ${pkg.dir}`);
49
+ process.exit(1);
50
+ }
51
+ }
52
+
53
+ function fail(message) {
54
+ console.error(`FAIL ${message}`);
55
+ process.exit(1);
56
+ }
57
+
58
+ function readManifest() {
59
+ if (!existsSync(MANIFEST)) fail(`profile manifest not found: ${MANIFEST}`);
60
+ let json;
61
+ try {
62
+ json = JSON.parse(readFileSync(MANIFEST, 'utf8'));
63
+ } catch (error) {
64
+ fail(`profile manifest is not valid JSON (${error.message}); refusing to rewrite it`);
65
+ }
66
+ if (json.dsh?.profile?.bundles === undefined || !Array.isArray(json.dsh.profile.bundles)) {
67
+ fail('dsh.profile.bundles is missing or is not an array; refusing to invent it');
68
+ }
69
+ json.dependencies ??= {};
70
+ return json;
71
+ }
72
+
73
+ function writeManifest(json) {
74
+ const text = `${JSON.stringify(json, null, 2)}\n`;
75
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
76
+ copyFileSync(MANIFEST, `${MANIFEST}.bak-${stamp}`);
77
+ const tmp = `${MANIFEST}.tmp-${process.pid}`;
78
+ writeFileSync(tmp, text, 'utf8');
79
+ JSON.parse(readFileSync(tmp, 'utf8'));
80
+ writeFileSync(MANIFEST, text, 'utf8');
81
+ return `${MANIFEST}.bak-${stamp}`;
82
+ }
83
+
84
+ function status(json) {
85
+ const bundles = json.dsh.profile.bundles;
86
+ const asBundle = bundles.includes(CORE_NAME);
87
+ const asDep = json.dependencies?.[CORE_NAME] !== undefined;
88
+ const panel = json.dependencies?.['dsh-native-uia-ui'] !== undefined;
89
+ console.log([
90
+ `profile ${PROFILE}`,
91
+ `bundles ${bundles.length}`,
92
+ `${CORE_NAME.padEnd(22)} bundle=${asBundle ? 'yes' : 'NO '} dep=${asDep ? 'yes' : 'NO '} panel=client-half`,
93
+ ...(panel ? [`dsh-native-uia-ui${' '.repeat(5)} still a profile dependency (stale: the panel now lives inside ${CORE_NAME})`] : []),
94
+ ].join('\n'));
95
+ return asBundle && asDep && !panel;
96
+ }
97
+
98
+ if (mode === 'status') {
99
+ process.exit(status(readManifest()) ? 0 : 1);
100
+ }
101
+
102
+ if (mode === 'install') {
103
+ const json = readManifest();
104
+ const added = [];
105
+ if (!json.dsh.profile.bundles.includes(CORE_NAME)) {
106
+ json.dsh.profile.bundles.push(CORE_NAME);
107
+ added.push(`${CORE_NAME} (bundle)`);
108
+ }
109
+ for (const pkg of ALL) {
110
+ if (json.dependencies[pkg.name] !== `link:${pkg.dir}`) {
111
+ json.dependencies[pkg.name] = `link:${pkg.dir}`;
112
+ added.push(`${pkg.name} (dependency)`);
113
+ }
114
+ }
115
+ // The panel used to be its own package; its dependency (and any stray bundle
116
+ // entry) is stale now that it lives inside this one package.
117
+ const stale = 'dsh-native-uia-ui';
118
+ if (json.dependencies[stale] !== undefined) {
119
+ delete json.dependencies[stale];
120
+ added.push(`removed ${stale} (dependency; the panel now lives inside ${CORE_NAME})`);
121
+ }
122
+ if (json.dsh.profile.bundles.includes(stale)) {
123
+ json.dsh.profile.bundles = json.dsh.profile.bundles.filter((b) => b !== stale);
124
+ added.push(`removed ${stale} (bundle entry)`);
125
+ }
126
+ const backup = added.length > 0 ? writeManifest(json) : null;
127
+ const after = readManifest();
128
+ if (!after.dsh.profile.bundles.includes(CORE_NAME)) fail('re-read after write still lacks the core bundle entry');
129
+ for (const pkg of ALL) {
130
+ if (after.dependencies[pkg.name] !== `link:${pkg.dir}`) fail(`re-read after write still lacks the ${pkg.name} dependency`);
131
+ }
132
+ if (after.dependencies[stale] !== undefined) fail(`${stale} dependency survived removal`);
133
+ console.log(added.length === 0 ? 'already registered, nothing written' : `added:\n ${added.join('\n ')}\nbackup: ${backup}`);
134
+ console.log('then run: (cd "$DSH_PROFILE" && pnpm install --ignore-scripts) # link: deps must be linked, file: deps would be copied');
135
+ console.log('restart DeepSeek Harness for the profile to reload');
136
+ process.exit(0);
137
+ }
138
+
139
+ if (mode === 'remove') {
140
+ const json = readManifest();
141
+ const names = new Set([...ALL.map((pkg) => pkg.name), 'dsh-native-uia-ui']);
142
+ json.dsh.profile.bundles = json.dsh.profile.bundles.filter((b) => !names.has(b));
143
+ for (const name of names) delete json.dependencies[name];
144
+ const backup = writeManifest(json);
145
+ const after = readManifest();
146
+ for (const name of names) {
147
+ if (after.dsh.profile.bundles.includes(name)) fail(`${name} bundle entry survived removal`);
148
+ }
149
+ console.log(`removed ${names.size} entries (everything else untouched)\nbackup: ${backup}`);
150
+ process.exit(0);
151
+ }
152
+
153
+ console.error(`usage: node install.mjs [install|remove|status]`);
154
+ process.exit(2);
@@ -0,0 +1,24 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { classify, classifyBatch, classifyClose, classifyLaunch, classifyKeys, POLICY } from '../../src/guard.js';
5
+
6
+ // Shared loader for the regression scripts: reads the PRODUCTION src/tools.js, strips its ESM
7
+ // wrapper (imports / named exports) and evaluates it as a plain function body with injected
8
+ // deps, so the scripts exercise the real source without a copy. `returnExpr` is the expression
9
+ // of the `return` statement inside the new Function body — each script picks the names it needs.
10
+ // Exported consts (PASS_THROUGH / OCR_COVER) are stripped to plain consts so scripts can pull the
11
+ // SAME set the tool uses instead of keeping a second copy around.
12
+ const root = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
13
+
14
+ export async function loadToolsSource(returnExpr) {
15
+ const source = await fs.readFile(join(root, 'src/tools.js'), 'utf8');
16
+ const body = source
17
+ .replace(/^import .*;\r?\n/gm, '')
18
+ .replace(/export const (\w+) =/g, 'const $1 =')
19
+ .replace('export function registerTools', 'function registerTools')
20
+ .replace('export { POLICY };', '');
21
+ return new Function('deps', `const {writeFile,readdir,readFile,mkdir,unlink,join,defineTool,classify,classifyBatch,classifyClose,classifyLaunch,classifyKeys,POLICY}=deps;\n${body}\nreturn ${returnExpr};`)({
22
+ ...fs, join, defineTool: (x) => x, classify, classifyBatch, classifyClose, classifyLaunch, classifyKeys, POLICY,
23
+ });
24
+ }
@@ -0,0 +1,77 @@
1
+ import { CuaWorker } from '../src/worker-client.js';
2
+ import * as fs from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { loadToolsSource } from './lib/load-tools-source.mjs';
6
+
7
+ // A/B on ONE identical snapshot: the old rendering emitted one target per OCR word, the new one
8
+ // emits one target per merged line, anchored on an uncovered character. Same coverers, same words,
9
+ // same window => the delta is caused by the change, not by a different moment on screen.
10
+ const root = dirname(dirname(fileURLToPath(import.meta.url)));
11
+ const mod = await loadToolsSource('{ registerTools, groupOcrWords, ocrTargets, OCR_COVER }');
12
+ const { registerTools, groupOcrWords, ocrTargets, OCR_COVER: COVER } = mod;
13
+ // COVER is the production set imported straight from src/tools.js — a verbatim copy here used to
14
+ // be the divergence risk (tools.js's list moves, the script's copy silently stays).
15
+
16
+ const dataDir = join(root, '.test-output', 'measure');
17
+ await fs.mkdir(dataDir, { recursive: true });
18
+ const worker = new CuaWorker({ logger: (m) => console.log(` . ${m}`) });
19
+ const tools = new Map();
20
+ const store = { running: false, windows: [], pointerMode: 'background', counters: {}, step() {}, actionDone() {}, setTree() {}, setTarget() {} };
21
+ const dispose = registerTools({ tools: { register(def) { tools.set(def.name, def); return () => {}; } } }, { worker, store, dataDir, owned: new Map() });
22
+
23
+ const inRect = (r, x, y) => x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
24
+
25
+ let code = 0;
26
+ try {
27
+ const list = await worker.call('list_windows', {});
28
+ const windows = list.windows ?? list ?? [];
29
+ const wanted = String(process.env.MEASURE_TITLE ?? '').toLowerCase();
30
+ const target = (wanted
31
+ ? windows.filter((w) => String(w.title ?? '').toLowerCase().includes(wanted))[0]
32
+ : windows.filter((w) => w.rect.w > 900 && w.rect.h > 600).sort((a, b) => b.rect.w * b.rect.h - a.rect.w * a.rect.h)[0]) ?? windows[0];
33
+ const windowId = target.windowId;
34
+
35
+ const snap = await worker.call('snapshot', { windowId, maxNodes: 300 });
36
+ const ocr = await worker.call('ocr', { windowId }, { timeoutMs: 40000 });
37
+ const nodes = snap.nodes ?? [];
38
+ const words = (ocr.words ?? []).filter((w) => w.rect && w.rect.w > 0 && w.rect.h > 0);
39
+ const coverers = nodes.filter((n) => COVER.has(n.controlType) && String(n.name ?? '').trim() !== '' && n.rect && n.rect.w > 0 && !n.isOffscreen);
40
+ const covered = (x, y) => coverers.some((n) => inRect(n.rect, x, y));
41
+
42
+ // old behaviour: every uncovered word was its own clickable target
43
+ const oldTargets = words.filter((w) => !covered(w.cx, w.cy)).length;
44
+ // new behaviour: the production pure function, on the SAME words and nodes
45
+ const { grouped: lines, targets: newTargetList } = ocrTargets(nodes, words);
46
+ const newTargets = newTargetList.length;
47
+
48
+ console.log(`window ${windowId} ${target.rect.w}x${target.rect.h} UIA ${nodes.length} OCR words ${words.length} lines ${lines.length}`);
49
+ console.log(`clickable targets: old=${oldTargets} new=${newTargets} (${oldTargets > 0 ? Math.round((1 - newTargets / Math.max(1, oldTargets)) * 100) : 0}% fewer, same pixels)`);
50
+ if (lines.length >= words.length && words.length > 20) { console.log('[FAIL] grouping produced no compression'); code = 1; }
51
+ else console.log(`[PASS] line grouping compresses ${words.length} words into ${lines.length} lines`);
52
+ if (newTargets > oldTargets) { console.log('[FAIL] grouped targets exceed per-word targets'); code = 1; }
53
+ else console.log(`[PASS] no clickable text was lost: new ${newTargets} <= old ${oldTargets}`);
54
+
55
+ // and the tool output must agree with that computation
56
+ const out = await tools.get('computer_parse').execute({ windowId }, { signal: new AbortController().signal });
57
+ const head = out.split('\n')[0];
58
+ const listed = out.split('\n').filter((l) => /^\s{2}"/.test(l)).length;
59
+ console.log(head);
60
+ console.log(`tool listed ${listed} targets (capped at 120)`);
61
+ // The tool takes its own (later) snapshot, and the window under test is streaming text, so the
62
+ // counts are compared WITHIN that call: header vs listed rows. The cross-call A/B above is the
63
+ // claim about the change; this is the claim that the rendering is self-consistent.
64
+ const reported = Number(head.match(/其中 (\d+) 行/)?.[1] ?? -1);
65
+ if (!/词合并为 \d+ 行/.test(head)) { console.log('[FAIL] tool header does not report the merge'); code = 1; }
66
+ else if (reported < 0 || listed !== Math.min(reported, 120)) { console.log(`[FAIL] header says ${reported} rows but ${listed} were listed`); code = 1; }
67
+ else console.log(`[PASS] rendering is self-consistent (${listed} rows listed, header says ${reported})`);
68
+ console.log('--- sample ---');
69
+ for (const l of out.split('\n').filter((x) => /^\s{2}"/.test(x)).slice(0, 6)) console.log(l);
70
+ } catch (error) {
71
+ console.log(`[FAIL] ${error.code ?? ''} ${error.message}`);
72
+ code = 1;
73
+ } finally {
74
+ dispose();
75
+ await worker.shutdown({ killMs: 5000 });
76
+ }
77
+ process.exitCode = code;
@@ -0,0 +1,100 @@
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)`);
@@ -0,0 +1,207 @@
1
+ import assert from 'node:assert/strict';
2
+ import { loadToolsSource } from './lib/load-tools-source.mjs';
3
+
4
+ // Unit-level checks for the two observation-quality transforms and the effect report.
5
+ // They run against the PRODUCTION source (no copy), with no desktop input.
6
+ const mod = await loadToolsSource('{ registerTools, groupOcrWords, elideRedundantContainers, renderResults, renderTree, ocrTargets, locatorNotes, observationLine, newWindowNote }');
7
+ const { groupOcrWords, elideRedundantContainers, renderResults, renderTree, ocrTargets, locatorNotes, observationLine, newWindowNote } = mod;
8
+
9
+ let passed = 0;
10
+ function test(name, fn) {
11
+ try { fn(); passed++; console.log(`PASS ${name}`); }
12
+ catch (error) { console.log(`FAIL ${name}: ${error.message}`); process.exitCode = 1; }
13
+ }
14
+
15
+ const word = (text, x, y, w = 20, h = 22) => ({ text, cx: x + w / 2, cy: y + h / 2, rect: { x, y, w, h } });
16
+
17
+ test('CJK per-character OCR words merge into one readable line', () => {
18
+ const words = ['御', '屏', '面', '板', '是', '好'].map((t, i) => word(t, 100 + i * 20, 300));
19
+ const lines = groupOcrWords(words);
20
+ assert.equal(lines.length, 1, `expected 1 line, got ${lines.length}`);
21
+ assert.equal(lines[0].text, '御屏面板是好');
22
+ assert.equal(lines[0].words, 6);
23
+ const r = lines[0].rect;
24
+ assert.ok(r.x <= 100 && r.x + r.w >= 100 + 6 * 20, 'union rect must cover every member word');
25
+ });
26
+
27
+ test('separate text lines stay separate targets', () => {
28
+ const words = [word('a', 10, 100), word('b', 30, 100), word('c', 10, 160), word('d', 30, 160)];
29
+ assert.equal(groupOcrWords(words).length, 2);
30
+ });
31
+
32
+ test('two columns on the same baseline never merge', () => {
33
+ const words = [word('标', 100, 200), word('题', 120, 200), word('值', 900, 200), word('项', 920, 200)];
34
+ const lines = groupOcrWords(words);
35
+ assert.equal(lines.length, 2, `far-apart columns merged into ${lines.length} line(s)`);
36
+ assert.equal(lines[0].text, '标题');
37
+ assert.equal(lines[1].text, '值项');
38
+ });
39
+
40
+ test('latin words keep a space, CJK does not', () => {
41
+ const latin = groupOcrWords([word('Save', 10, 50, 40, 20), word('as', 54, 50, 20, 20)]);
42
+ assert.equal(latin[0].text, 'Save as');
43
+ const cjk = groupOcrWords([word('保', 10, 50), word('存', 30, 50)]);
44
+ assert.equal(cjk[0].text, '保存');
45
+ });
46
+
47
+ test('one target per line keeps the clickable point inside the phrase', () => {
48
+ const words = ['提', '交', '按', '钮'].map((t, i) => word(t, 400 + i * 18, 700, 18, 26));
49
+ const [line] = groupOcrWords(words);
50
+ assert.ok(line.cx >= 400 && line.cx <= 400 + 4 * 18, 'click point left the phrase');
51
+ assert.ok(line.cy >= 700 && line.cy <= 700 + 26, 'click point left the phrase');
52
+ });
53
+
54
+ test('unnamed pass-through containers are elided but keep children reachable', () => {
55
+ const nodes = [
56
+ { ref: 'e1', controlType: 'Window', name: 'App', depth: 0, patterns: [] },
57
+ { ref: 'e2', controlType: 'Pane', name: '', depth: 1, patterns: [] },
58
+ { ref: 'e3', controlType: 'Group', name: '', depth: 2, patterns: [] },
59
+ { ref: 'e4', controlType: 'Button', name: '提交', depth: 3, patterns: ['Invoke'] },
60
+ ];
61
+ const out = elideRedundantContainers(nodes);
62
+ assert.equal(out.length, 2, 'empty structural wrappers should be elided');
63
+ const button = out.find((n) => n.ref === 'e4');
64
+ assert.ok(button !== undefined, 'the actionable child disappeared');
65
+ assert.equal(button.depth, 1, `button depth should collapse to 1, got ${button.depth}`);
66
+ assert.ok(out.some((n) => n.ref === 'e1'), 'named window root must stay');
67
+ });
68
+
69
+ test('containers that are named or actionable are never elided', () => {
70
+ const nodes = [
71
+ { ref: 'e1', controlType: 'Pane', name: '主区域', depth: 0, patterns: [] },
72
+ { ref: 'e2', controlType: 'Pane', name: '', depth: 0, patterns: ['Scroll'] },
73
+ ];
74
+ const out = elideRedundantContainers(nodes);
75
+ assert.equal(out.length, 2, 'a named or scrollable container must stay addressable');
76
+ });
77
+
78
+ test('renderTree stays readable and keeps every actionable ref', () => {
79
+ const nodes = [
80
+ { ref: 'e1', controlType: 'Window', name: 'App', depth: 0, patterns: [] },
81
+ { ref: 'e2', controlType: 'Pane', name: '', depth: 1, patterns: [] },
82
+ { ref: 'e3', controlType: 'Button', name: '保存', depth: 2, patterns: ['Invoke'] },
83
+ ];
84
+ const text = renderTree(nodes);
85
+ assert.match(text, /e3 Button "保存"/);
86
+ assert.doesNotMatch(text, /e2 Pane/, 'an unnamed pass-through pane is still rendered');
87
+ assert.equal(text.split('\n').length, 2);
88
+ });
89
+
90
+ test('effect report distinguishes verified, changed and unobservable', () => {
91
+ const html = renderResults([
92
+ { index: 0, action: 'set_value', performed: true, status: 'passed', before: 'a', after: 'b', verify: { type: 'value_equals', matched: true } },
93
+ { index: 1, action: 'set_value', performed: true, status: 'passed', before: 'a', after: 'b' },
94
+ ], 2);
95
+ assert.match(html, /校验命中/);
96
+ assert.match(html, /属性已变/);
97
+ assert.match(html, /没有校验条件/);
98
+ const blind = renderResults([
99
+ { index: 0, action: 'invoke', performed: true, status: 'passed', before: '', after: '' },
100
+ ], 1);
101
+ assert.match(blind, /无可观测属性变化/);
102
+ // Button verbs have no assertable reading, so they get NO verify suggestion — a suggested
103
+ // value_changed there would only produce verify checks that never match. The old blanket
104
+ // "请再快照确认界面" is gone: the performedCount tail already carries the
105
+ // "已送达不代表界面已改变" guidance for every unverified step.
106
+ assert.doesNotMatch(blind, /verify:\{type/);
107
+ assert.doesNotMatch(blind, /请再快照确认界面/);
108
+ // Verbs with an observable effect suggest an inline verify (aligned with the worker's
109
+ // Eval-Once evaluator) so one call settles it instead of another snapshot round-trip.
110
+ const hinted = renderResults([
111
+ { index: 0, action: 'set_value', performed: true, status: 'passed', before: '', after: '' },
112
+ { index: 1, action: 'toggle', performed: true, status: 'passed', before: '', after: '' },
113
+ ], 2);
114
+ assert.match(hinted, /verify:\{type:"value_equals"\}/);
115
+ assert.match(hinted, /verify:\{type:"value_changed"\}(或 enabled_is)/);
116
+ });
117
+
118
+
119
+ test('OCR coverage is decided per character, so partially covered text stays clickable', () => {
120
+ const nodes = [{ controlType: 'Text', name: '前两个字', rect: { x: 100, y: 300, w: 42, h: 22 }, isOffscreen: false }];
121
+ const words = ['前', '两', '个', '字', '后', '续'].map((t, i) => word(t, 100 + i * 20, 300));
122
+ const { targets } = ocrTargets(nodes, words);
123
+ assert.equal(targets.length, 1, 'the uncovered half of a line must stay a target');
124
+ assert.equal(targets[0].text, '前两个字后续');
125
+ // the coverer spans x=100..142, so the first two characters are labelled and four are not
126
+ assert.equal(targets[0].openWords, 4, `expected 4 uncovered characters, got ${targets[0].openWords}`);
127
+ assert.ok(targets[0].cx >= 150, `click point should sit on the first uncovered character, got ${targets[0].cx}`);
128
+ });
129
+
130
+ test('text already addressable through UIA produces no OCR target', () => {
131
+ const nodes = ['全', '部', '覆', '盖'].map((n, i) => ({ controlType: 'Text', name: n, rect: { x: 100 + i * 20, y: 300, w: 20, h: 22 }, isOffscreen: false }));
132
+ const words = ['全', '部', '覆', '盖'].map((t, i) => word(t, 100 + i * 20, 300));
133
+ assert.equal(ocrTargets(nodes, words).targets.length, 0);
134
+ });
135
+
136
+ test('a self-drawn surface with no coverers keeps one target per line', () => {
137
+ const words = ['开', '始', '菜', '单'].map((t, i) => word(t, 300 + i * 20, 500));
138
+ const { targets } = ocrTargets([], words);
139
+ assert.equal(targets.length, 1);
140
+ assert.equal(targets[0].text, '开始菜单');
141
+ assert.equal(targets[0].openWords, 4);
142
+ });
143
+
144
+
145
+ test('a degraded locator is surfaced with its rung and score', () => {
146
+ const note = locatorNotes([
147
+ { index: 0, degraded: false, matchedBy: 'strict', score: 1 },
148
+ { index: 1, degraded: true, matchedBy: 'normalizedName', score: 0.9 },
149
+ { index: 2, degraded: true, matchedBy: 'id', score: 0.85 },
150
+ ]);
151
+ assert.match(note, /定位降级 2 步/);
152
+ assert.match(note, /normalizedName\(90%\)/);
153
+ assert.match(note, /id\(85%\)/);
154
+ assert.match(note, /find_text 复核/);
155
+ assert.equal(locatorNotes([{ index: 0, degraded: false }]), '', 'a clean batch must stay silent');
156
+ });
157
+
158
+
159
+ // P-04: the observation head renders only what the worker actually probed, truncates everything
160
+ // through str(), and renders nothing when every field is absent. Render-stub assertions on the
161
+ // PRODUCTION function (P-04 gate ②: 新增字段必走 str() 截断).
162
+ test('observation line renders foreground/focus and truncates through str()', () => {
163
+ const full = observationLine({
164
+ ms: 812.4,
165
+ foreground: { title: ' 一段非常长的窗口标题——远超四十个字符的长度——必须被截断而不能撑爆这一行 ', class: 'Chrome_WidgetWin_1', pid: 5016, isTarget: false },
166
+ focus: { controlType: 'Button', name: '一个非常非常非常非常非常非常非常长的按钮名必须被截断到二十四字符', pid: 4242 },
167
+ focusInWindow: false,
168
+ });
169
+ assert.match(full, /前台="/);
170
+ assert.match(full, /焦点=Button/);
171
+ assert.match(full, /不在本窗/);
172
+ assert.match(full, /resolve_window 或带 windowId 聚焦/);
173
+ assert.match(full, /采集 812ms/);
174
+ assert.ok(!full.includes('远超四十个字符的长度——必须被截断而不能撑爆这一行'.slice(0, 20) + '不能撑爆'), 'the foreground title must be cut at 40 chars');
175
+ // 焦点在本窗时给「在本窗」标记,不给修正指引。
176
+ const inWin = observationLine({ ms: 5, foreground: { title: '记事本', pid: 1, isTarget: true }, focus: { controlType: 'Edit', name: '文本', pid: 1 }, focusInWindow: true });
177
+ assert.match(inWin, /在本窗/);
178
+ assert.doesNotMatch(inWin, /resolve_window/);
179
+ // worker 探测失败(字段缺省)→ 零输出,绝不渲染半个空行。
180
+ assert.equal(observationLine({}), '', 'absent fields must render nothing');
181
+ assert.equal(observationLine(null), '', 'a null result must render nothing');
182
+ });
183
+
184
+ // P-09: newWindows renders the warning line ONLY when the diff is non-empty, and never reports
185
+ // the plugin's own indicator capsule (pid filter + fixed title filter).
186
+ test('newWindowNote warns on real new windows and stays silent otherwise', () => {
187
+ const rows = [
188
+ { hwnd: 9999, pid: 4243, title: '弹出对话框', class: '#32770' },
189
+ ];
190
+ const note = newWindowNote(rows, 0);
191
+ assert.match(note, /批次期间出现新窗口/);
192
+ assert.match(note, /弹出对话框/);
193
+ assert.match(note, /pid=4243/);
194
+ assert.match(note, /避免它的按钮文本混进下一次定位/);
195
+ // our own overlay pid → filtered → zero output (the cold-first-batch self-report case)
196
+ assert.equal(newWindowNote([{ hwnd: 8888, pid: 7777, title: '随便什么标题', class: 'X' }], 7777), '');
197
+ // the overlay's fixed title → filtered even when the pid filter misses (worker never learned it)
198
+ assert.equal(newWindowNote([{ hwnd: 8888, pid: 1, title: 'dsh-yuping-indicator', class: 'X' }], 0), '');
199
+ // no diff → zero output (the two-state contract: absent key and empty array both stay silent)
200
+ assert.equal(newWindowNote([], 0), '');
201
+ assert.equal(newWindowNote(undefined, 0), '');
202
+ // long window titles go through str(), not raw
203
+ const long = newWindowNote([{ hwnd: 1, pid: 2, title: '一'.repeat(120), class: 'X' }], 0);
204
+ assert.ok(long.length < 120, 'the new-window title must be truncated');
205
+ });
206
+
207
+ console.log(`\n${passed}/15 quality regressions passed (no desktop input)`);