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.
- package/LICENSE +21 -0
- package/README.md +431 -2
- package/client/client.js +81 -0
- package/cordis.patch.yml +11 -0
- package/icon.svg +11 -0
- package/locale/desktop/en.json +6 -0
- package/locale/desktop/zh.json +6 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +80 -4
- package/scripts/bench-live.mjs +157 -0
- package/scripts/check-lease.mjs +308 -0
- package/scripts/install.mjs +154 -0
- package/scripts/lib/load-tools-source.mjs +24 -0
- package/scripts/measure-parse.mjs +77 -0
- package/scripts/regression-halt-latch.mjs +100 -0
- package/scripts/regression-quality.mjs +207 -0
- package/scripts/regression-tools.mjs +88 -0
- package/scripts/regression-worker.ps1 +1042 -0
- package/scripts/smoke.mjs +158 -0
- package/scripts/verify-capture-scale.mjs +37 -0
- package/scripts/verify-live-clipboard.mjs +108 -0
- package/scripts/verify-live.mjs +110 -0
- package/scripts/verify-locator.mjs +52 -0
- package/scripts/verify.mjs +1459 -0
- package/src/activity-window.js +212 -0
- package/src/dashboard.js +145 -0
- package/src/guard.js +191 -0
- package/src/index.js +377 -0
- package/src/native-uia-remote.js +80 -0
- package/src/panel-face.js +14 -0
- package/src/state.js +177 -0
- package/src/tools.js +1482 -0
- package/src/worker-client.js +246 -0
- package/web/control.html +1413 -0
- package/worker/bin/build-ocr.ps1 +41 -0
- package/worker/bin/ocr.cs +69 -0
- package/worker/bin/ocr.exe +0 -0
- package/worker/indicator-server.ps1 +1928 -0
- package/worker/ps-stdio.ps1 +168 -0
- package/worker/uia-worker.ps1 +4220 -0
|
@@ -0,0 +1,1459 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Static gates for the plugin. Every list is read from the artifacts under test,
|
|
4
|
+
* never copied into this file, and a check that cannot run reports SKIP — which
|
|
5
|
+
* is not a pass.
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync, existsSync, readdirSync } from 'node:fs';
|
|
8
|
+
import { join, dirname } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { execFileSync } from 'node:child_process';
|
|
11
|
+
import { classify, classifyBatch, classifyLaunch, classifyClose, classifyKeys } from '../src/guard.js';
|
|
12
|
+
import { Store } from '../src/state.js';
|
|
13
|
+
import { loadToolsSource } from './lib/load-tools-source.mjs';
|
|
14
|
+
|
|
15
|
+
const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
16
|
+
const UI_ROOT = ROOT; // one package, multiple components: the panel lives inside the core package now
|
|
17
|
+
const results = [];
|
|
18
|
+
let failed = 0;
|
|
19
|
+
const inflight = [];
|
|
20
|
+
|
|
21
|
+
function gate(name, run) {
|
|
22
|
+
let verdict;
|
|
23
|
+
let detail = '';
|
|
24
|
+
const record = () => {
|
|
25
|
+
results.push({ name, verdict, detail });
|
|
26
|
+
console.log(`[${verdict}] ${name}${detail ? ` — ${detail}` : ''}`);
|
|
27
|
+
};
|
|
28
|
+
try {
|
|
29
|
+
const outcome = run();
|
|
30
|
+
if (outcome !== null && typeof outcome === 'object' && typeof outcome.then === 'function') {
|
|
31
|
+
// Async gate body: settled before the summary (top-level await below). Same contract as the
|
|
32
|
+
// synchronous path — resolved 'SKIP' is a SKIP, any other resolution a PASS, a rejection a FAIL.
|
|
33
|
+
inflight.push(outcome.then(
|
|
34
|
+
(value) => {
|
|
35
|
+
if (value === 'SKIP') { verdict = 'SKIP'; detail = 'precondition absent'; }
|
|
36
|
+
else { verdict = 'PASS'; detail = typeof value === 'string' ? value : ''; }
|
|
37
|
+
record();
|
|
38
|
+
},
|
|
39
|
+
(error) => {
|
|
40
|
+
verdict = 'FAIL';
|
|
41
|
+
detail = String(error?.message ?? error).split('\n')[0];
|
|
42
|
+
failed++;
|
|
43
|
+
record();
|
|
44
|
+
},
|
|
45
|
+
));
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (outcome === 'SKIP') {
|
|
49
|
+
verdict = 'SKIP';
|
|
50
|
+
detail = 'precondition absent';
|
|
51
|
+
} else {
|
|
52
|
+
verdict = 'PASS';
|
|
53
|
+
detail = typeof outcome === 'string' ? outcome : '';
|
|
54
|
+
}
|
|
55
|
+
} catch (error) {
|
|
56
|
+
verdict = 'FAIL';
|
|
57
|
+
detail = String(error?.message ?? error).split('\n')[0];
|
|
58
|
+
failed++;
|
|
59
|
+
}
|
|
60
|
+
record();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function assert(condition, message) {
|
|
64
|
+
if (!condition) throw new Error(message);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const sourceFiles = readdirSync(join(ROOT, 'src')).filter((f) => f.endsWith('.js')).map((f) => join('src', f));
|
|
68
|
+
|
|
69
|
+
gate('every source file parses', () => {
|
|
70
|
+
assert(sourceFiles.length >= 5, `only ${sourceFiles.length} files under src/`);
|
|
71
|
+
const bad = [];
|
|
72
|
+
for (const file of sourceFiles) {
|
|
73
|
+
try {
|
|
74
|
+
execFileSync(process.execPath, ['--check', file], { cwd: ROOT, stdio: 'inherit' });
|
|
75
|
+
} catch (error) {
|
|
76
|
+
bad.push(`${file}: ${String(error.stderr ?? error.message).split('\n')[0]}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
assert(bad.length === 0, bad.join(' | '));
|
|
80
|
+
return `${sourceFiles.length} files`;
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
gate('the two PS processes share one stdio JSON framework via ps-stdio.ps1', () => {
|
|
84
|
+
const stdioPath = join(ROOT, 'worker', 'ps-stdio.ps1');
|
|
85
|
+
assert(existsSync(stdioPath), 'worker/ps-stdio.ps1 is missing: the stdio JSON framing must live once, not once per PS process');
|
|
86
|
+
const shared = readFileSync(stdioPath, 'utf8');
|
|
87
|
+
for (const fn of ['Esc', 'JsonOf', 'OneLine', 'Err', 'ArgOf', 'IntArg', 'StrArg', 'BoolArg', 'Dict', 'Split-Err']) {
|
|
88
|
+
assert(new RegExp(`function ${fn}\\(`).test(shared), `ps-stdio.ps1 does not define ${fn}`);
|
|
89
|
+
}
|
|
90
|
+
assert(!/function (Send-Ok|Send-Err)\b/.test(shared), 'Send-Ok/Send-Err must stay in their hosts: they write per-host stats and the indicator decorates results');
|
|
91
|
+
for (const host of ['uia-worker.ps1', 'indicator-server.ps1']) {
|
|
92
|
+
const text = readFileSync(join(ROOT, 'worker', host), 'utf8');
|
|
93
|
+
assert(text.includes(". (Join-Path $PSScriptRoot 'ps-stdio.ps1')"), `${host} no longer dot-sources ps-stdio.ps1`);
|
|
94
|
+
assert(!/function (JsonOf|Esc)\b/.test(text), `${host} re-inlines the shared stdio helpers instead of dot-sourcing ps-stdio.ps1`);
|
|
95
|
+
}
|
|
96
|
+
// Syntax check with the real PowerShell parser; degrade to SKIP where powershell.exe does
|
|
97
|
+
// not exist (SKIP is not a pass).
|
|
98
|
+
const script = "foreach($f in @('worker/ps-stdio.ps1','worker/uia-worker.ps1','worker/indicator-server.ps1')){ $e=$null;$t=$null; [void][System.Management.Automation.Language.Parser]::ParseFile((Join-Path (Get-Location).Path $f),[ref]$t,[ref]$e); if($e.Count -gt 0){ $e | ForEach-Object { Write-Host ('PARSE '+$f+' L'+$_.Extent.StartLineNumber+': '+$_.Message) }; exit 2 } }";
|
|
99
|
+
try {
|
|
100
|
+
execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script], { cwd: ROOT, timeout: 60000, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error && (error.code === 'ENOENT' || error.code === 'EACCES')) return 'SKIP';
|
|
103
|
+
assert(false, `a worker PS file fails to parse: ${String(error?.stdout ?? error?.message ?? error).split('\n')[0]}`);
|
|
104
|
+
}
|
|
105
|
+
return 'shared helpers live once in ps-stdio.ps1; both hosts dot-source it; all three PS files parse';
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
gate('client bundle parses and speaks the module-loader protocol', () => {
|
|
109
|
+
const file = join(UI_ROOT, 'client', 'client.js');
|
|
110
|
+
assert(existsSync(file), 'the panel package has no client/client.js');
|
|
111
|
+
const body = readFileSync(file, 'utf8');
|
|
112
|
+
new Function('window', 'require', body);
|
|
113
|
+
assert(body.includes('window.__ModuleLoader__.load'), 'no __ModuleLoader__.load call');
|
|
114
|
+
assert(/exports\.apply\s*=/.test(body), 'does not export apply');
|
|
115
|
+
assert(/exports\.inject\s*=/.test(body), 'does not export inject');
|
|
116
|
+
assert(body.includes("require('react") || body.includes('require("react'), 'does not require react');
|
|
117
|
+
return 'parses; exports apply+inject';
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
gate('the client bundle requires only declared modules and matches the server port', () => {
|
|
121
|
+
const client = readFileSync(join(UI_ROOT, 'client', 'client.js'), 'utf8');
|
|
122
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
123
|
+
const uiManifest = JSON.parse(readFileSync(join(UI_ROOT, 'package.json'), 'utf8'));
|
|
124
|
+
/* A plugin client that requires something outside the client module table aborts
|
|
125
|
+
the whole web boot with "import failed: client-modules: require(...) missed the
|
|
126
|
+
module table" — measured, not theoretical. Only react plus the packages declared
|
|
127
|
+
in dsh.client.inject may be required. */
|
|
128
|
+
const allowed = new Set(['react', 'react/jsx-runtime', ...(uiManifest.dsh?.client?.inject ?? [])]);
|
|
129
|
+
// Strip comments first: matching inside prose turns a warning about `require("zod")`
|
|
130
|
+
// into a false positive that looks like a caught regression.
|
|
131
|
+
const code = client.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
|
|
132
|
+
const required = [...new Set([...code.matchAll(/require\((['"])([^'"]+)\1\)/g)].map((m) => m[2]))];
|
|
133
|
+
const unknown = required.filter((spec) => !allowed.has(spec));
|
|
134
|
+
assert(unknown.length === 0, `the client requires ${unknown.join(', ')}, which is not in the declared module table: this blocks app startup`);
|
|
135
|
+
const clientPort = client.match(/127\.0\.0\.1:(\d+)/)?.[1];
|
|
136
|
+
const serverPort = index.match(/dashboardPort\s*\?\?\s*(\d+)/)?.[1];
|
|
137
|
+
assert(clientPort !== undefined && serverPort !== undefined, 'the panel port or the server default is missing');
|
|
138
|
+
assert(clientPort === serverPort, `client :${clientPort} but server binds :${serverPort}`);
|
|
139
|
+
assert(!/require\(['"]zod/.test(code), 'the client requires zod again: zod is bundled into generated host artifacts, not available to plugins');
|
|
140
|
+
return `requires [${required.join(', ')}], port :${clientPort}`;
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
gate('control page exists and serves the contract it is written against', () => {
|
|
144
|
+
const file = join(ROOT, 'web', 'control.html');
|
|
145
|
+
assert(existsSync(file), 'web/control.html is absent');
|
|
146
|
+
const html = readFileSync(file, 'utf8');
|
|
147
|
+
const missing = ['/api/state', '/api/action', '/api/stream', '/api/screenshot'].filter((e) => !html.includes(e));
|
|
148
|
+
assert(missing.length === 0, `page never calls ${missing.join(' ')}`);
|
|
149
|
+
const server = readFileSync(join(ROOT, 'src', 'dashboard.js'), 'utf8');
|
|
150
|
+
const serverPaths = [...server.matchAll(/url\.pathname === '([^']+)'/g)].map((m) => m[1]);
|
|
151
|
+
const orphan = ['/api/state', '/api/action', '/api/stream', '/api/screenshot'].filter((e) => !serverPaths.includes(e));
|
|
152
|
+
assert(orphan.length === 0, `page calls endpoints the server never registers: ${orphan.join(' ')}`);
|
|
153
|
+
return `4 endpoints on both sides`;
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
gate('guard denies every category the user asked to block (MUST FIRE)', () => {
|
|
157
|
+
const mustDeny = [
|
|
158
|
+
{ action: 'invoke', descriptor: { name: 'Shut down', controlType: 'Button' } },
|
|
159
|
+
{ action: 'invoke', descriptor: { name: 'Restart', controlType: 'MenuItem' } },
|
|
160
|
+
{ action: 'invoke', descriptor: { name: 'Sign out of Windows', controlType: 'MenuItem' } },
|
|
161
|
+
{ action: 'invoke', descriptor: { name: '关机', controlType: 'Button' } },
|
|
162
|
+
{ action: 'invoke', descriptor: { name: '注销', controlType: 'MenuItem' } },
|
|
163
|
+
{ action: 'invoke', descriptor: { name: 'Exit', controlType: 'MenuItem' } },
|
|
164
|
+
{ action: 'invoke', descriptor: { name: '退出程序', controlType: 'MenuItem' } },
|
|
165
|
+
{ action: 'invoke', descriptor: { name: 'Delete', controlType: 'Button', className: 'Button' } },
|
|
166
|
+
{ action: 'invoke', descriptor: { name: '永久删除', controlType: 'MenuItem' } },
|
|
167
|
+
{ action: 'invoke', descriptor: { name: 'Empty Recycle Bin', controlType: 'MenuItem' } },
|
|
168
|
+
{ action: 'toggle', descriptor: { name: 'Delete all history', controlType: 'Button' } },
|
|
169
|
+
{ action: 'close_window', descriptor: { name: 'Settings', ownedByPlugin: false } },
|
|
170
|
+
{ action: 'launch', descriptor: {}, extra: 'shutdown.exe' },
|
|
171
|
+
// The window-close affordance: invoking it ends the application exactly like Alt+F4, and it
|
|
172
|
+
// used to be allowed because the pattern only knew the words "退出程序"/"关闭程序".
|
|
173
|
+
{ action: 'invoke', descriptor: { name: '关闭', controlType: 'Button' } },
|
|
174
|
+
{ action: 'invoke', descriptor: { name: 'Close', controlType: 'Button' } },
|
|
175
|
+
{ action: 'invoke', descriptor: { name: '✕', controlType: 'Button' } },
|
|
176
|
+
{ action: 'invoke', descriptor: { name: '×', controlType: 'Button' } },
|
|
177
|
+
// Case variants: computer_run/replay accept free JSON, so a step can carry any case; the
|
|
178
|
+
// worker lower-cases before executing, so the guard must match the same way or "Invoke"
|
|
179
|
+
// sails past the text refusal while the step still runs (fixed 2026-11-16).
|
|
180
|
+
{ action: 'Invoke', descriptor: { name: 'Shut down', controlType: 'Button' } },
|
|
181
|
+
{ action: 'INVOKE', descriptor: { name: 'Exit', controlType: 'MenuItem' } },
|
|
182
|
+
{ action: 'Toggle', descriptor: { name: 'Delete all history', controlType: 'Button' } },
|
|
183
|
+
];
|
|
184
|
+
const leaks = [];
|
|
185
|
+
for (const item of mustDeny) {
|
|
186
|
+
const outcome = item.extra !== undefined ? classifyLaunch(item.extra)
|
|
187
|
+
: item.action === 'close_window' ? classifyClose({ ...item.descriptor })
|
|
188
|
+
: classify(item);
|
|
189
|
+
if (outcome.verdict !== 'deny') leaks.push(`${item.extra ?? item.descriptor.name}/${item.action}`);
|
|
190
|
+
}
|
|
191
|
+
assert(leaks.length === 0, `policy leaked: ${leaks.join(' | ')}`);
|
|
192
|
+
// A boundary that refuses normal work is not usable, so pin the near-misses that must stay
|
|
193
|
+
// allowed: dismissing a dialog and closing a message box are ordinary steps.
|
|
194
|
+
const mustAllow = ['确定', '取消', '保存', '最小化', '最大化', '关闭对话框', 'Close dialog', 'OK'];
|
|
195
|
+
const overblocked = mustAllow.filter((name) => classify({ action: 'invoke', descriptor: { name, controlType: 'Button' } }).verdict !== 'allow');
|
|
196
|
+
assert(overblocked.length === 0, `policy now blocks ordinary controls: ${overblocked.join(' | ')}`);
|
|
197
|
+
// Batch pre-checks have one home: computer_run and computer_replay must both route their
|
|
198
|
+
// per-step policy loop through guard.classifyBatch. The regex pins the inline-loop SHAPE
|
|
199
|
+
// (for over steps + a bare classify call), so a future batch entry cannot quietly grow a
|
|
200
|
+
// second copy of "check every step, refuse on first deny" — that copy drifts the first time
|
|
201
|
+
// someone edits one refusal wording and not the other. classifyPoint's single classify is
|
|
202
|
+
// not a loop and does not match.
|
|
203
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
204
|
+
assert(!/for \(let i = 0; i < steps\.length; i\+\+\) \{\s*const outcome = classify\(/.test(tools),
|
|
205
|
+
'tools.js inlines a batch classify loop again: batch pre-checks must go through guard.classifyBatch');
|
|
206
|
+
const batchCalls = [...tools.matchAll(/classifyBatch\(/g)].length;
|
|
207
|
+
assert(batchCalls >= 2, `classifyBatch is called ${batchCalls}x in tools.js; computer_run and computer_replay must both pre-check through it`);
|
|
208
|
+
const firstDeny = classifyBatch(
|
|
209
|
+
[{ action: 'invoke' }, { action: 'invoke' }],
|
|
210
|
+
[{ name: 'OK', controlType: 'Button' }, { name: '关机', controlType: 'Button' }],
|
|
211
|
+
);
|
|
212
|
+
assert(firstDeny?.verdict === 'deny' && firstDeny?.index === 1 && firstDeny?.category === 'shutdown',
|
|
213
|
+
`classifyBatch did not return the first deny tagged with its index: ${JSON.stringify(firstDeny)}`);
|
|
214
|
+
assert(classifyBatch([{ action: 'invoke' }], [{ name: 'OK', controlType: 'Button' }]) === null,
|
|
215
|
+
'classifyBatch denies an all-allow batch');
|
|
216
|
+
// 防循环护栏 (P-08):AndroidWorld 的「动作缓存不记结果导致无限滚动」——同目标滚动步连续
|
|
217
|
+
// 重复 3 次且重复段内没有任何 verify,必须在第 3 次出现处拒绝并带 index(prepare 阶段就拒,
|
|
218
|
+
// computer_run 与 computer_replay 共用这一条 classifyBatch)。
|
|
219
|
+
const loopDeny = classifyBatch([
|
|
220
|
+
{ action: 'scroll_down', ref: 'r7' },
|
|
221
|
+
{ action: 'scroll_down', ref: 'r7' },
|
|
222
|
+
{ action: 'scroll_down', ref: 'r7' },
|
|
223
|
+
]);
|
|
224
|
+
assert(loopDeny?.verdict === 'deny' && loopDeny?.category === 'loop' && loopDeny?.index === 2,
|
|
225
|
+
`3 consecutive no-verify scrolls on one target must deny as loop at index 2: ${JSON.stringify(loopDeny)}`);
|
|
226
|
+
// 更长的卡死段也只报一次:deny 落在首次越线的位置(第 3 次出现处),不逐个重报。
|
|
227
|
+
const loopFive = classifyBatch([
|
|
228
|
+
{ action: 'scroll_up', ref: 'r7' },
|
|
229
|
+
{ action: 'scroll_up', ref: 'r7' },
|
|
230
|
+
{ action: 'scroll_up', ref: 'r7' },
|
|
231
|
+
{ action: 'scroll_up', ref: 'r7' },
|
|
232
|
+
{ action: 'scroll_up', ref: 'r7' },
|
|
233
|
+
]);
|
|
234
|
+
assert(loopFive?.verdict === 'deny' && loopFive?.category === 'loop' && loopFive?.index === 2,
|
|
235
|
+
`a longer stuck run must deny at the first crossing (index 2): ${JSON.stringify(loopFive)}`);
|
|
236
|
+
assert(classifyBatch([
|
|
237
|
+
{ action: 'pointer_scroll', by: { name: '列表' } },
|
|
238
|
+
{ action: 'pointer_scroll', by: { name: '列表' } },
|
|
239
|
+
{ action: 'pointer_scroll', by: { name: '列表' } },
|
|
240
|
+
])?.category === 'loop', 'the pointer scroll family is part of the loop guard too');
|
|
241
|
+
return `${mustDeny.length} refusals fired, ${mustAllow.length} ordinary controls still allowed, batch pre-checks via classifyBatch, loop guard fires on 3-in-a-row`;
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
gate('guard allows benign work (MUST NOT FIRE)', () => {
|
|
245
|
+
const mustAllow = [
|
|
246
|
+
{ action: 'set_value', descriptor: { name: 'File name', controlType: 'Edit' } },
|
|
247
|
+
{ action: 'invoke', descriptor: { name: 'OK', controlType: 'Button' } },
|
|
248
|
+
{ action: 'invoke', descriptor: { name: 'Cancel', controlType: 'Button' } },
|
|
249
|
+
{ action: 'invoke', descriptor: { name: 'Submit', controlType: 'Button' } },
|
|
250
|
+
{ action: 'invoke', descriptor: { name: 'Save', controlType: 'Button' } },
|
|
251
|
+
{ action: 'invoke', descriptor: { name: 'Copy', controlType: 'MenuItem' } },
|
|
252
|
+
{ action: 'invoke', descriptor: { name: 'Forward', controlType: 'Button' } },
|
|
253
|
+
{ action: 'scroll_down', descriptor: { name: 'Document', controlType: 'Document' } },
|
|
254
|
+
{ action: 'expand', descriptor: { name: 'More options', controlType: 'Button' } },
|
|
255
|
+
{ action: 'invoke', descriptor: { name: 'Recalculate', controlType: 'Button' } },
|
|
256
|
+
{ action: 'close_window', descriptor: { name: 'Untitled - Notepad', ownedByPlugin: true } },
|
|
257
|
+
{ action: 'launch', descriptor: {}, extra: 'notepad.exe' },
|
|
258
|
+
{ action: 'launch', descriptor: {}, extra: 'calc' },
|
|
259
|
+
];
|
|
260
|
+
const stuck = [];
|
|
261
|
+
for (const item of mustAllow) {
|
|
262
|
+
const outcome = item.extra !== undefined ? classifyLaunch(item.extra)
|
|
263
|
+
: item.action === 'close_window' ? classifyClose({ ...item.descriptor })
|
|
264
|
+
: classify(item);
|
|
265
|
+
if (outcome.verdict !== 'allow') stuck.push(`${item.extra ?? item.descriptor.name}/${item.action}: ${outcome.refusal}`);
|
|
266
|
+
}
|
|
267
|
+
assert(stuck.length === 0, `policy over-fired and would break ordinary work: ${stuck.join(' | ')}`);
|
|
268
|
+
// 防循环护栏 MUST NOT FIRE:2 次重复是正常的「再滚一格」;重复段里带 verify 则循环已被
|
|
269
|
+
// 结果校验兜住(verify 未命中会硬停批次);不连续(滚动-点击交替)或不同目标交替是轮询式
|
|
270
|
+
// 操作;非滚动动作连点同一条 invoke 是正常工作——都不拦。
|
|
271
|
+
const loopOk = [
|
|
272
|
+
[{ action: 'scroll_down', ref: 'r1' }, { action: 'scroll_down', ref: 'r1' }],
|
|
273
|
+
[
|
|
274
|
+
{ action: 'scroll_down', ref: 'r1' },
|
|
275
|
+
{ action: 'scroll_down', ref: 'r1' },
|
|
276
|
+
{ action: 'scroll_down', ref: 'r1', verify: { type: 'scroll_percent_changed', expect: 5 } },
|
|
277
|
+
],
|
|
278
|
+
[
|
|
279
|
+
{ action: 'scroll_down', ref: 'r1' }, { action: 'invoke', ref: 'r2' },
|
|
280
|
+
{ action: 'scroll_down', ref: 'r1' }, { action: 'invoke', ref: 'r2' },
|
|
281
|
+
{ action: 'scroll_down', ref: 'r1' },
|
|
282
|
+
],
|
|
283
|
+
[{ action: 'scroll_down', ref: 'r1' }, { action: 'scroll_down', ref: 'r2' }, { action: 'scroll_down', ref: 'r1' }],
|
|
284
|
+
[{ action: 'invoke', ref: 'r1' }, { action: 'invoke', ref: 'r1' }, { action: 'invoke', ref: 'r1' }],
|
|
285
|
+
[
|
|
286
|
+
{ action: 'scroll_down', ref: 'r1' },
|
|
287
|
+
{ action: 'scroll_down', ref: 'r1' },
|
|
288
|
+
{ type: 'scroll_percent_changed', ref: 'r1' },
|
|
289
|
+
{ action: 'scroll_down', ref: 'r1' },
|
|
290
|
+
],
|
|
291
|
+
];
|
|
292
|
+
const loopStuck = [];
|
|
293
|
+
for (const steps of loopOk) {
|
|
294
|
+
const outcome = classifyBatch(steps);
|
|
295
|
+
if (outcome !== null) loopStuck.push(JSON.stringify(steps.map((s) => `${s.action ?? s.type}/${s.ref ?? ''}`)) + ' -> ' + outcome.category);
|
|
296
|
+
}
|
|
297
|
+
assert(loopStuck.length === 0, `loop guard over-fired: ${loopStuck.join(' | ')}`);
|
|
298
|
+
return `${mustAllow.length} benign actions all allowed, loop guard stays quiet on 2 repeats / verified repeats / non-consecutive repeats`;
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
gate('the kill latch gates input, and every gated command is recognised as input', () => {
|
|
302
|
+
const client = readFileSync(join(ROOT, 'src', 'worker-client.js'), 'utf8');
|
|
303
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
304
|
+
const declared = client.match(/ACTION_COMMANDS = new Set\(\[([^\]]+)\]/)?.[1];
|
|
305
|
+
assert(declared !== undefined, 'ACTION_COMMANDS set not found');
|
|
306
|
+
const set = [...declared.matchAll(/'([^']+)'/g)].map((m) => m[1]);
|
|
307
|
+
assert(set.includes('act') && set.includes('commit_batch') && set.includes('launch'), `set is missing an input command: ${set.join(',')}`);
|
|
308
|
+
assert(index.includes('halt:') && /this\.halt\?\.\(\)|this\.halt\(\)/.test(client), 'the halt callback is not wired end to end');
|
|
309
|
+
return `gated commands: ${set.join(', ')}`;
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
gate('an SSE fan-out frame cannot break the broadcast loop', () => {
|
|
313
|
+
// Measured: Node's http layer absorbs a write to a destroyed socket (no uncaughtException; the
|
|
314
|
+
// req 'close' handler removes the client anyway). This gate locks the cheap defense-in-depth —
|
|
315
|
+
// per-frame try + immediate drop — so a future change that throws synchronously inside the
|
|
316
|
+
// fan-out (this runs inside a store event, outside #handle's try) cannot take the loop down.
|
|
317
|
+
const dash = readFileSync(join(ROOT, 'src', 'dashboard.js'), 'utf8');
|
|
318
|
+
const body = dash.match(/#broadcast\(event, payload\) \{([\s\S]*?)\n \}/)?.[1];
|
|
319
|
+
assert(body !== undefined, '#broadcast is missing');
|
|
320
|
+
assert(/try\s*\{[\s\S]*?res\.write\(frame\)/.test(body), 'the SSE frame write is not guarded');
|
|
321
|
+
assert(/clients\.delete/.test(body), 'a failing client is not dropped from the broadcast set');
|
|
322
|
+
const stream = dash.match(/\/api\/stream'\) \{([\s\S]*?)\n \}/)?.[1];
|
|
323
|
+
assert(stream !== undefined && /req\.on\('close'/.test(stream), 'the SSE endpoint does not clean clients up on close');
|
|
324
|
+
return 'per-frame try, dead clients dropped, cleanup on close';
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
gate('state-class SSE frames carry the data they announce, and the panel consumes them', () => {
|
|
328
|
+
// The F-03 regression: every state-class emit carried {reason} only. The live EventSource
|
|
329
|
+
// kept refreshing lastEventAt with frames the panel could not render anything from — the
|
|
330
|
+
// window list, tree, target chip, killed/busy/pointerMode all froze during live mode — while
|
|
331
|
+
// those same empty frames suppressed the 12 s idle polling fallback. Frames must carry real
|
|
332
|
+
// data (snapshot-shaped for arrays), and applyPartial must have a state branch for the rest.
|
|
333
|
+
const store = new Store();
|
|
334
|
+
const frames = [];
|
|
335
|
+
store.on('state', (p) => frames.push(p));
|
|
336
|
+
store.setWindows([{ windowId: 'w1', appName: 'App', title: 'Title', pid: 42, rect: { x: 1, y: 2, w: 3, h: 4 }, isForeground: true }]);
|
|
337
|
+
store.setTree([{ ref: 'r1', controlType: 'Button', name: 'N', className: 'C', depth: 2, patterns: ['Invoke'], enabled: false, isOffscreen: true, rect: { x: 0, y: 0, w: 9, h: 9 } }], { windowId: 'w1', revision: 7 });
|
|
338
|
+
store.setTarget({ windowId: 'w1', appName: 'App', title: 'Title' });
|
|
339
|
+
store.setKilled(true);
|
|
340
|
+
store.setPointerMode('auto');
|
|
341
|
+
const byReason = Object.fromEntries(frames.map((f) => [f.reason, f]));
|
|
342
|
+
assert(byReason.windows?.windows?.[0]?.windowId === 'w1', 'setWindows emits no windows array: the live panel never refreshes the window list');
|
|
343
|
+
assert(byReason.tree?.tree?.[0]?.ref === 'r1', 'setTree emits no tree array: the live panel never refreshes the element tree');
|
|
344
|
+
assert(byReason.target?.target?.windowId === 'w1', 'setTarget emits no target payload: the live panel never moves the target chip');
|
|
345
|
+
assert(byReason.killed?.killed === true, 'setKilled emits no killed value');
|
|
346
|
+
assert(byReason.pointerMode?.pointerMode === 'auto', 'setPointerMode emits no pointerMode value');
|
|
347
|
+
// Frame shapes must equal the snapshot shapes — the panel renders frames and /api/state
|
|
348
|
+
// through one code path, so a divergent frame shape would render as a second dialect.
|
|
349
|
+
const snap = store.snapshot({});
|
|
350
|
+
assert(JSON.stringify(byReason.windows.windows) === JSON.stringify(snap.windows), 'the windows frame shape diverged from the snapshot shape');
|
|
351
|
+
assert(JSON.stringify(byReason.tree.tree) === JSON.stringify(snap.tree), 'the tree frame shape diverged from the snapshot shape');
|
|
352
|
+
assert(JSON.stringify(byReason.target.target) === JSON.stringify(snap.session.target), 'the target frame shape diverged from the snapshot shape');
|
|
353
|
+
store.setTarget(null);
|
|
354
|
+
assert(frames[frames.length - 1].target === null, 'clearing the target no longer reaches the panel: computer_done would leave a stale target chip');
|
|
355
|
+
// The busy/running transitions are emitted from index.js, not Store.
|
|
356
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
357
|
+
assert(/reason: 'busy', busy: value === true/.test(index), 'the busy frame carries no busy value');
|
|
358
|
+
assert(/reason: 'running', running: running === true/.test(index), 'the running frame carries no running value');
|
|
359
|
+
// And the panel must consume the small payloads it now receives.
|
|
360
|
+
const html = readFileSync(join(ROOT, 'web', 'control.html'), 'utf8');
|
|
361
|
+
assert(/applyPartial[\s\S]*?name === 'state'/.test(html), 'applyPartial has no state branch: target/killed/busy/pointerMode frames arrive and are dropped');
|
|
362
|
+
return 'windows/tree/target frames carry snapshot-shaped data; killed/busy/pointerMode/running carry values; applyPartial consumes them';
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
gate('hard refusals are not approvable from the control page', () => {
|
|
366
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
367
|
+
const approve = index.match(/if \(kind === 'approve'\) \{\s*return \{ ok: false/);
|
|
368
|
+
assert(approve !== null, 'the approve action does not refuse: a policy denial would become clickable');
|
|
369
|
+
return 'approve returns ok:false';
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
gate('the tool set the model sees matches what the plugin registers', () => {
|
|
373
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
374
|
+
const names = [...tools.matchAll(/name: '(computer_[a-z_]+)'/g)].map((m) => m[1]);
|
|
375
|
+
assert(names.length >= 6, `only ${names.length} computer_* tools registered`);
|
|
376
|
+
assert(new Set(names).size === names.length, 'duplicate tool name');
|
|
377
|
+
assert(names.includes('computer_run') && names.includes('computer_snapshot'), 'the batch or tree channel is missing');
|
|
378
|
+
return names.join(', ');
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
gate('screenshots never bypass the host image-route gate', () => {
|
|
382
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
383
|
+
assert(!/saveImage|attachments/.test(tools), 'tools.js attaches images itself; the host gate would be bypassed');
|
|
384
|
+
assert(/read_image/.test(tools), 'the capture tool must point at read_image for image-capable routes');
|
|
385
|
+
return 'capture returns a path; read_image stays the gate';
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
gate('every tool renders with the two-argument contract', async () => {
|
|
389
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
390
|
+
const declared = [...tools.matchAll(/name: '(computer_[a-z_]+)'/g)].length;
|
|
391
|
+
// Two spellings of the same contract are both in use: `(_args, value)` and the short `(_a, v)`.
|
|
392
|
+
// What matters is that the renderer takes (args, value) rather than the 1-argument helper.
|
|
393
|
+
const long = [...tools.matchAll(/render: \(_args, value\) => text\(value\)/g)].length;
|
|
394
|
+
const short = [...tools.matchAll(/render: \(_a, v\) => text\(v\)/g)].length;
|
|
395
|
+
const correct = long + short;
|
|
396
|
+
const shorthand = [...tools.matchAll(/render: text[,}]/g)].length;
|
|
397
|
+
assert(shorthand === 0, `${shorthand} tool(s) bind render to the 1-argument helper: the host calls render(args, value), so the model would receive the arguments object`);
|
|
398
|
+
assert(correct === declared, `${declared} tools declared but ${correct} renderers match the (args, value) contract (${long} long + ${short} short)`);
|
|
399
|
+
// Batch-result four-state tally: feed renderResults a stub carrying all four statuses and
|
|
400
|
+
// require all four count labels in the output — the model must not have to re-count the lines.
|
|
401
|
+
const { renderResults } = await loadToolsSource('{ renderResults }');
|
|
402
|
+
const rendered = renderResults([
|
|
403
|
+
{ index: 0, action: 'invoke', ref: 'e1', status: 'passed', performed: true, ms: 10 },
|
|
404
|
+
{ index: 1, action: 'invoke', ref: 'e2', status: 'failed', performed: false, ms: 5, detail: 'element not found' },
|
|
405
|
+
{ index: 2, action: 'invoke', ref: 'e3', status: 'verify_failed', performed: true, ms: 8, verify: { type: 'element_appears', matched: false } },
|
|
406
|
+
{ index: 3, action: 'invoke', ref: 'e4', status: 'not_executed', performed: false, ms: 0 },
|
|
407
|
+
], 2);
|
|
408
|
+
assert(/通过 1 \/ 失败 1(首条原因:第 1 步 element not found)/u.test(rendered), `renderResults tally lost the failed count or its first reason: ${rendered.split('\n').at(-1)}`);
|
|
409
|
+
assert(/校验未命中 1/.test(rendered), 'renderResults tally lost the verify-missed count');
|
|
410
|
+
assert(/未执行 1/.test(rendered), 'renderResults tally lost the not-executed count');
|
|
411
|
+
// The not_executed wording is single-source: the exported constant, referenced at the one
|
|
412
|
+
// render site — a second literal copy is exactly the drift this gate forbids.
|
|
413
|
+
const occurrences = tools.split('未执行:前序步骤失败/被取消').length - 1;
|
|
414
|
+
assert(occurrences === 1, `the not-executed wording appears ${occurrences} times in tools.js: it must exist only as the NOT_EXECUTED_TEXT constant`);
|
|
415
|
+
assert(/notExecuted \? NOT_EXECUTED_TEXT : r\.detail/.test(tools), 'renderResults no longer renders the not-executed tail from the shared constant');
|
|
416
|
+
return `${declared} renderers (${long} long-form, ${short} short-form); four-state tally verified on a stub; NOT_EXECUTED_TEXT single-source`;
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
gate('close authority is scoped to the window, not the process', () => {
|
|
420
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
421
|
+
assert(!/launched\.has\(/.test(tools), 'tools.js still keys close authority on a pid set: a single-process store app would let the model close unrelated user windows');
|
|
422
|
+
assert(/owned\.get\(`\$\{worker\.epoch\}:\$\{args\.windowId\}`\)/.test(tools), 'the close check does not bind windowId to the worker epoch');
|
|
423
|
+
assert(/owned\.set\(`\$\{worker\.epoch\}:\$\{result\.windowId\}`/.test(tools), 'launch does not claim a per-epoch window identity');
|
|
424
|
+
assert(/matchedBy === 'new-window'/.test(tools), 'launch claims ownership without checking the window is genuinely new');
|
|
425
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
426
|
+
assert(/const owned = new Map\(\)/.test(index), 'index.js does not create the ownership map');
|
|
427
|
+
return 'ownership = epoch + windowId, claimed only for new windows';
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
gate('manifest satisfies the host bundle contract', () => {
|
|
431
|
+
const manifest = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
|
|
432
|
+
assert(manifest.dsh?.bundle?.patch !== undefined, 'dsh.bundle.patch is missing: the host loads no components and the card says 不包含任何组件');
|
|
433
|
+
const patchRel = manifest.dsh.bundle.patch.replace(/^\.\//, '');
|
|
434
|
+
assert(existsSync(join(ROOT, patchRel)), `declared patch layer ${patchRel} does not exist`);
|
|
435
|
+
const patch = readFileSync(join(ROOT, patchRel), 'utf8');
|
|
436
|
+
assert(/insert:/.test(patch), 'the patch layer has no insert list, so it contributes no plugin');
|
|
437
|
+
assert(/name:\s*'dsh-native-uia'/.test(patch), 'the patch must insert by package name so the host can attribute the component row to this package');
|
|
438
|
+
assert(!/name:\s*'\.\//.test(patch), 'the patch inserts a relative module path: the row loses package attribution and shows a bare file:// URL');
|
|
439
|
+
assert(manifest.type === 'module', 'package.json must declare type: module');
|
|
440
|
+
assert(manifest.exports?.['.'] === './src/panel-face.js', 'the . export must be the bare-name row entry (the panel face)');
|
|
441
|
+
assert(manifest.exports?.['./desktop'] === './src/index.js', 'the ./desktop export must be the tools row entry');
|
|
442
|
+
assert(manifest.exports?.['./package.json'] === './package.json', 'exports ./package.json is required for host metadata reads');
|
|
443
|
+
assert(manifest.exports?.['./locale/*.json'] === './locale/*.json', 'exports ./locale/*.json is required for the display title');
|
|
444
|
+
assert(manifest.exports?.['./desktop/locale/*.json'] === './locale/desktop/*.json', 'exports ./desktop/locale/*.json is required for the tools row title');
|
|
445
|
+
return `patch=${patchRel}`;
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
gate('display name and icon are real files the card can read without activating', () => {
|
|
449
|
+
const manifest = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
|
|
450
|
+
for (const locale of ['en', 'zh']) {
|
|
451
|
+
const file = join(ROOT, 'locale', `${locale}.json`);
|
|
452
|
+
assert(existsSync(file), `locale/${locale}.json is absent`);
|
|
453
|
+
const meta = JSON.parse(readFileSync(file, 'utf8')).meta;
|
|
454
|
+
assert(typeof meta?.title === 'string' && meta.title.length > 0, `locale/${locale}.json has no meta.title`);
|
|
455
|
+
assert(typeof meta?.description === 'string' && meta.description.length > 40, `locale/${locale}.json has no meta.description`);
|
|
456
|
+
}
|
|
457
|
+
assert(!existsSync(join(ROOT, 'locale', 'zh-CN.json')), 'locale/zh-CN.json is not the host convention: every official package ships locale/zh.json');
|
|
458
|
+
const zh = JSON.parse(readFileSync(join(ROOT, 'locale', 'zh.json'), 'utf8')).meta.title;
|
|
459
|
+
assert(zh !== manifest.name, 'the Chinese title still equals the package name, so the card would show dsh-native-uia');
|
|
460
|
+
assert(/[一-龥]/.test(zh), 'the Chinese title contains no Chinese characters');
|
|
461
|
+
const iconRel = String(manifest.icon ?? '').replace(/^\.\//, '');
|
|
462
|
+
assert(iconRel !== '', 'package.json declares no icon');
|
|
463
|
+
const iconFile = join(ROOT, iconRel);
|
|
464
|
+
assert(existsSync(iconFile), `declared icon ${iconRel} does not exist`);
|
|
465
|
+
const bytes = readFileSync(iconFile);
|
|
466
|
+
assert(bytes.length <= 256 * 1024, `icon is ${bytes.length} bytes; the host accepts at most 256 KiB`);
|
|
467
|
+
const iconText = bytes.toString('utf8');
|
|
468
|
+
assert(!/(?:xlink:href|href|src)\s*=\s*["'](?:https?:|data:)/i.test(iconText) && !/url\(\s*["']?https?:/i.test(iconText), 'the icon must not reference an external resource (the host rejects absolute paths and URLs)');
|
|
469
|
+
assert(/<svg[\s>]/i.test(iconText), 'the declared icon is not an SVG document');
|
|
470
|
+
const client = readFileSync(join(UI_ROOT, 'client', 'client.js'), 'utf8');
|
|
471
|
+
const panelTitle = JSON.parse(readFileSync(join(UI_ROOT, 'locale', 'zh.json'), 'utf8')).meta.title;
|
|
472
|
+
assert(client.includes(panelTitle.split(' ')[0]), `the conversation tab label does not use the panel title (${panelTitle})`);
|
|
473
|
+
return `title="${zh}", icon=${iconRel} (${bytes.length} B)`;
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
gate('the panel is its own row under the same package (one package, multiple components)', () => {
|
|
477
|
+
const core = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
|
|
478
|
+
// 灵犀同构:一个包两行组件 —— 裸名行 = 卡片 + 面板(client 源唯一挂点),
|
|
479
|
+
// /desktop 子路径行 = 桌面操控工具(provider 在前),两行的开关相互独立。
|
|
480
|
+
assert(core.dsh?.bundle?.patch !== undefined, 'the core package lost its bundle patch');
|
|
481
|
+
assert(core.dsh?.client?.platform === 'web', 'the package does not declare dsh.client');
|
|
482
|
+
assert(core.exports?.['./client'] === './client/client.js', 'the package does not export ./client');
|
|
483
|
+
assert(core.exports?.['./desktop'] === './src/index.js', 'the package does not export ./desktop (the tools row)');
|
|
484
|
+
assert(core.main === './src/panel-face.js', 'main (the bare-name row) must be the panel face, not the tools entry');
|
|
485
|
+
const clientPath = join(ROOT, 'client', 'client.js');
|
|
486
|
+
assert(existsSync(clientPath), 'the client/client.js panel bundle is absent');
|
|
487
|
+
for (const locale of ['en', 'zh']) {
|
|
488
|
+
const meta = JSON.parse(readFileSync(join(ROOT, 'locale', `${locale}.json`), 'utf8')).meta;
|
|
489
|
+
assert(typeof meta?.title === 'string' && typeof meta?.description === 'string', `the package has no locale/${locale}.json meta`);
|
|
490
|
+
const desktop = JSON.parse(readFileSync(join(ROOT, 'locale', 'desktop', `${locale}.json`), 'utf8')).meta;
|
|
491
|
+
assert(typeof desktop?.title === 'string' && typeof desktop?.description === 'string', `the desktop row has no locale/desktop/${locale}.json meta`);
|
|
492
|
+
assert(desktop?.title !== meta.title, 'the panel row and the desktop row share one title: rows would be indistinguishable');
|
|
493
|
+
}
|
|
494
|
+
const installer = readFileSync(join(ROOT, 'scripts', 'install.mjs'), 'utf8');
|
|
495
|
+
assert(!/bundles\.push\(pkg\.name\)/.test(installer), 'install.mjs still pushes every package into bundles: a component would render as its own plugin card');
|
|
496
|
+
const patch = readFileSync(join(ROOT, 'cordis.patch.yml'), 'utf8');
|
|
497
|
+
const rows = [...patch.matchAll(/-\s*id:\s*([a-z0-9-]+)\s*\n\s*name:\s*'([^']+)'/g)].map((m) => ({ id: m[1], name: m[2] }));
|
|
498
|
+
const panelRow = rows.find((r) => r.name === core.name);
|
|
499
|
+
const desktopRow = rows.find((r) => r.name === `${core.name}/desktop`);
|
|
500
|
+
assert(panelRow, 'the patch does not insert the bare-name row: the panel would have no mounted entry to declare dsh.client on');
|
|
501
|
+
assert(desktopRow, 'the patch does not insert the /desktop row: the tools would not appear as a switchable component');
|
|
502
|
+
assert(rows.indexOf(desktopRow) < rows.indexOf(panelRow), 'the tools row must precede the panel row (provider before consumer)');
|
|
503
|
+
// The client bundle registers under the package name: client-modules keys each
|
|
504
|
+
// package to exactly one client source, and registration ids must match its graph row.
|
|
505
|
+
const client = readFileSync(clientPath, 'utf8');
|
|
506
|
+
assert(client.includes(`id: '${core.name}'`), `the client bundle does not register as "${core.name}"`);
|
|
507
|
+
// The tools entry must own its row identity.
|
|
508
|
+
const toolsEntry = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
509
|
+
assert(toolsEntry.includes(`export const name = '${core.name}/desktop'`), 'src/index.js does not claim the /desktop row name');
|
|
510
|
+
assert(!core.dependencies?.['dsh-native-uia-ui'], 'the package still links the old panel package');
|
|
511
|
+
return 'two rows under one card: /desktop (tools) + bare name (card = panel)';
|
|
512
|
+
});
|
|
513
|
+
|
|
514
|
+
gate('the page really sends the header the server demands', () => {
|
|
515
|
+
const html = readFileSync(join(ROOT, 'web', 'control.html'), 'utf8');
|
|
516
|
+
const server = readFileSync(join(ROOT, 'src', 'dashboard.js'), 'utf8');
|
|
517
|
+
const header = server.match(/API_HEADER = '([^']+)'/)?.[1];
|
|
518
|
+
assert(header !== undefined, 'dashboard.js no longer names its API header constant');
|
|
519
|
+
const postBodies = [...html.matchAll(/method\s*:\s*'POST'[\s\S]{0,220}/g)].map((m) => m[0]);
|
|
520
|
+
assert(postBodies.length > 0, 'the page no longer issues any POST, so the control switches are dead');
|
|
521
|
+
const missing = postBodies.filter((b) => !b.includes(`'${header}'`) && !b.includes(`"${header}"`));
|
|
522
|
+
assert(missing.length === 0, `${missing.length} POST site(s) omit ${header}: every panel button would 403 while still looking wired`);
|
|
523
|
+
return `${postBodies.length} POST site(s) all send ${header}`;
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
gate('the overlay is driven from the one choke point that performs input', () => {
|
|
527
|
+
const client = readFileSync(join(ROOT, 'src', 'worker-client.js'), 'utf8');
|
|
528
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
529
|
+
const branch = client.match(/if \(isAction\) \{([\s\S]*?)\n \}/)?.[1];
|
|
530
|
+
assert(branch !== undefined, 'worker-client no longer has the isAction branch');
|
|
531
|
+
assert(/this\.onActionStart\?\.\(cmd\)/.test(branch), 'the claim is not fired inside the action branch, so some input would go unreported');
|
|
532
|
+
assert(/onActionStart:[\s\S]{0,260}?activity\.claim\(/.test(index), 'index.js does not wire the claim to the activity window');
|
|
533
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
534
|
+
// A capture may ask ActivityWindow to hide itself for the sampling window; that is a read-only
|
|
535
|
+
// suspension owned by ActivityWindow, not a second indicator owner. Direct indicator calls remain
|
|
536
|
+
// forbidden in tools.js.
|
|
537
|
+
assert(!/indicator\.call|indicator\.send/.test(tools), 'tools.js directly drives the indicator; ActivityWindow must remain the owner');
|
|
538
|
+
return 'claim fires once per mutating command; capture suspension stays behind ActivityWindow';
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
gate('lease renewal is a whitelist, so internal probes cannot strobe the overlay', () => {
|
|
542
|
+
const client = readFileSync(join(ROOT, 'src', 'worker-client.js'), 'utf8');
|
|
543
|
+
const setOf = (name) => {
|
|
544
|
+
const body = client.match(new RegExp(`${name} = new Set\\(\\[([\\s\\S]*?)\\]\\)`))?.[1];
|
|
545
|
+
assert(body !== undefined, `${name} not found`);
|
|
546
|
+
return new Set([...body.matchAll(/'([^']+)'/g)].map((m) => m[1]));
|
|
547
|
+
};
|
|
548
|
+
const actions = setOf('ACTION_COMMANDS');
|
|
549
|
+
const observes = setOf('OBSERVE_COMMANDS');
|
|
550
|
+
// The regression this locks: `escape_pressed` is polled every 40 ms by the Esc watchdog. When
|
|
551
|
+
// observation was inferred as "not an action", that poll beat the overlay ~25×/s and the ring
|
|
552
|
+
// flickered. Probes must be in neither set.
|
|
553
|
+
for (const probe of ['escape_pressed', 'ping', 'set_pointer_mode']) {
|
|
554
|
+
assert(!observes.has(probe), `${probe} renews the lease: an internal probe must not beat the overlay`);
|
|
555
|
+
assert(!actions.has(probe), `${probe} is treated as desktop input`);
|
|
556
|
+
}
|
|
557
|
+
for (const cmd of observes) {
|
|
558
|
+
assert(!actions.has(cmd), `${cmd} is in both sets: it would claim and observe at once`);
|
|
559
|
+
}
|
|
560
|
+
// Every command the tools actually send must be classified, so a new tool cannot silently land
|
|
561
|
+
// in neither bucket (an unclassified read would just stop renewing the lease).
|
|
562
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
563
|
+
const sent = new Set([...tools.matchAll(/worker\.call\('([a-z_]+)'/g)].map((m) => m[1]));
|
|
564
|
+
const runtimeOnly = new Set(['set_pointer_mode', 'escape_pressed']); // index.js drives the worker directly
|
|
565
|
+
for (const cmd of sent) {
|
|
566
|
+
if (runtimeOnly.has(cmd)) continue;
|
|
567
|
+
assert(actions.has(cmd) || observes.has(cmd), `"${cmd}" is sent by a tool but is in neither ACTION_COMMANDS nor OBSERVE_COMMANDS`);
|
|
568
|
+
}
|
|
569
|
+
return `${actions.size} input commands, ${observes.size} observation commands, probes silent`;
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
gate('read-only mode refuses every ACTION command at the choke point and lets every OBSERVE command through', async () => {
|
|
573
|
+
const { CuaWorker } = await import('../src/worker-client.js');
|
|
574
|
+
const client = readFileSync(join(ROOT, 'src', 'worker-client.js'), 'utf8');
|
|
575
|
+
const setOf = (name) => {
|
|
576
|
+
const body = client.match(new RegExp(`${name} = new Set\\(\\[([\\s\\S]*?)\\]\\)`))?.[1];
|
|
577
|
+
assert(body !== undefined, `${name} not found`);
|
|
578
|
+
// The literal carries historical comments ('foreground' was removed…) whose quoted words are
|
|
579
|
+
// NOT set members — parsing them would behaviourally test a command the Set rejects, and a
|
|
580
|
+
// non-member call just pends forever instead of refusing. Parse code lines only.
|
|
581
|
+
const code = body.split('\n').filter((l) => !/^\s*\/\//.test(l)).join('\n');
|
|
582
|
+
return [...code.matchAll(/'([^']+)'/g)].map((m) => m[1]);
|
|
583
|
+
};
|
|
584
|
+
const actions = setOf('ACTION_COMMANDS');
|
|
585
|
+
const observes = setOf('OBSERVE_COMMANDS');
|
|
586
|
+
assert(actions.length > 0 && observes.length > 0, 'one of the whitelists parsed empty');
|
|
587
|
+
// Order invariant: the refusal sits at the halt-latch layer but ABOVE it, so it cannot consume
|
|
588
|
+
// the one-shot latch and cannot reach busy()/claim() — a read-only session lights no overlay.
|
|
589
|
+
const branch = client.match(/if \(isAction\) \{([\s\S]*?)\n \}/)?.[1];
|
|
590
|
+
assert(branch !== undefined, 'the isAction branch is gone');
|
|
591
|
+
assert(branch.includes('this.readOnly'), 'the choke point has no read-only refusal inside the action branch');
|
|
592
|
+
assert(branch.indexOf('this.readOnly') < branch.indexOf('this.halt'), 'the read-only refusal moved below the halt check: it would consume the one-shot latch');
|
|
593
|
+
const makeWorker = () => {
|
|
594
|
+
const fired = { claim: [], observe: [] };
|
|
595
|
+
const w = new CuaWorker({
|
|
596
|
+
readOnly: true,
|
|
597
|
+
logger: () => {},
|
|
598
|
+
onActionStart: (cmd) => fired.claim.push(cmd),
|
|
599
|
+
onObserve: (cmd) => fired.observe.push(cmd),
|
|
600
|
+
});
|
|
601
|
+
// Stub the spawn — observation commands legitimately lazily-spawn the worker for UIA reads
|
|
602
|
+
// (do NOT assert zero spawns); a fake running proc keeps the whole check inside this process.
|
|
603
|
+
w.start = () => {};
|
|
604
|
+
w.proc = { stdin: { write: () => {} }, exitCode: null, killed: false };
|
|
605
|
+
return { w, fired };
|
|
606
|
+
};
|
|
607
|
+
// Every input command must be refused with read_only_mode, one by one, before any claim.
|
|
608
|
+
const { w: actionWorker, fired: actionFired } = makeWorker();
|
|
609
|
+
const leaked = [];
|
|
610
|
+
for (const cmd of actions) {
|
|
611
|
+
try {
|
|
612
|
+
await actionWorker.call(cmd, {});
|
|
613
|
+
leaked.push(`${cmd}: allowed`);
|
|
614
|
+
} catch (error) {
|
|
615
|
+
if (error?.code !== 'read_only_mode') leaked.push(`${cmd}: ${error?.code ?? error?.message}`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
assert(leaked.length === 0, `read-only mode did not refuse every input command: ${leaked.join(' | ')}`);
|
|
619
|
+
assert(actionFired.claim.length === 0, 'a refused action still claimed the overlay: a read-only session would light the screen');
|
|
620
|
+
assert(actionWorker.stats.readOnlyRefused === actions.length, 'read-only refusals are not counted in stats');
|
|
621
|
+
// Observation rides the normal path: the hook fires per command and the request reaches the
|
|
622
|
+
// (stubbed) pipe — no rejection may come back, least of all read_only_mode.
|
|
623
|
+
const { w: obsWorker, fired: obsFired } = makeWorker();
|
|
624
|
+
const bad = [];
|
|
625
|
+
for (const cmd of observes) {
|
|
626
|
+
obsWorker.call(cmd, {}).then(
|
|
627
|
+
() => {},
|
|
628
|
+
(error) => bad.push(`${cmd}: ${error?.code ?? error?.message}`),
|
|
629
|
+
);
|
|
630
|
+
}
|
|
631
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
632
|
+
assert(bad.length === 0, `an observation command did not pass the read-only choke point: ${bad.join(' | ')}`);
|
|
633
|
+
const missing = observes.filter((c) => !obsFired.observe.includes(c));
|
|
634
|
+
const extra = obsFired.observe.filter((c) => !observes.includes(c));
|
|
635
|
+
assert(missing.length === 0 && extra.length === 0, `observation hook mismatch: missing=[${missing}] extra=[${extra}]`);
|
|
636
|
+
assert(obsFired.claim.length === 0, 'an observation command claimed the overlay in read-only mode');
|
|
637
|
+
return `${actions.length} input commands refused (read_only_mode, no claim), ${observes.length} observation commands through (spawn stubbed)`;
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
gate('POLICY.note names the current mode, read-only included', async () => {
|
|
641
|
+
// The note is written from the activation env, so both branches are loaded as fresh module
|
|
642
|
+
// instances (a query string gives a separate module record) with the env controlled here —
|
|
643
|
+
// deterministic even if the ambient environment already carries the switch.
|
|
644
|
+
const prev = process.env.DSH_NATIVE_UIA_READ_ONLY;
|
|
645
|
+
const load = async (tag, value) => {
|
|
646
|
+
if (value === undefined) delete process.env.DSH_NATIVE_UIA_READ_ONLY;
|
|
647
|
+
else process.env.DSH_NATIVE_UIA_READ_ONLY = value;
|
|
648
|
+
try {
|
|
649
|
+
return (await import(`../src/guard.js?mode=${tag}`)).POLICY;
|
|
650
|
+
} finally {
|
|
651
|
+
if (prev === undefined) delete process.env.DSH_NATIVE_UIA_READ_ONLY;
|
|
652
|
+
else process.env.DSH_NATIVE_UIA_READ_ONLY = prev;
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
const normal = await load('normal', undefined);
|
|
656
|
+
const ro = await load('readonly', '1');
|
|
657
|
+
assert(/硬拒不可批准/.test(normal.note), 'the default POLICY.note no longer states the hard-refuse rule');
|
|
658
|
+
assert(/只读/.test(ro.note) && /一律拒绝/.test(ro.note), `POLICY.note ignores DSH_NATIVE_UIA_READ_ONLY: ${ro.note}`);
|
|
659
|
+
assert(/DSH_NATIVE_UIA_READ_ONLY/.test(ro.note), 'the read-only note does not name the switch that turns it on');
|
|
660
|
+
assert(JSON.stringify(ro.deniedCategories) === JSON.stringify(normal.deniedCategories), 'read-only mode re-derived the denial categories: it must layer on top of the policy, not replace it');
|
|
661
|
+
assert(ro.approvable === false && normal.approvable === false, 'read-only mode made refusals approvable');
|
|
662
|
+
return 'default note intact; env-set note announces 只读观察模式 with categories unchanged';
|
|
663
|
+
});
|
|
664
|
+
|
|
665
|
+
gate('the heartbeat feeds the renderer but cannot keep a run alive forever', () => {
|
|
666
|
+
const activity = readFileSync(join(ROOT, 'src', 'activity-window.js'), 'utf8');
|
|
667
|
+
const hb = activity.match(/#startHeartbeat\(\) \{([\s\S]*?)\n \}/)?.[1];
|
|
668
|
+
assert(hb !== undefined, '#startHeartbeat is missing');
|
|
669
|
+
assert(!/renewLease/.test(hb), 'the heartbeat renews the lease again: a run the model never closed with computer_done beats forever and the overlay never stops (the 用完不停止 bug)');
|
|
670
|
+
const lease = activity.match(/#renewLease\(\) \{([\s\S]*?)\n \}/)?.[1];
|
|
671
|
+
assert(lease !== undefined && /this\.end\(/.test(lease), 'lease expiry no longer ends the run: the auto-stop backstop is gone');
|
|
672
|
+
assert(/canEnd/.test(activity), 'lease expiry ignores in-flight commands: a long OCR/wait/batch would drop the capsule mid-action');
|
|
673
|
+
return 'beats only render; only claim/observe renew; expiry ends the run, deferred while busy';
|
|
674
|
+
});
|
|
675
|
+
|
|
676
|
+
gate('an idle run closes itself instead of waiting out the whole lease', () => {
|
|
677
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
678
|
+
const touch = tools.match(/const touch = \(\) => \{([\s\S]*?)\n \};/)?.[1];
|
|
679
|
+
assert(touch !== undefined, 'touch() is missing: nothing closes a run whose model simply stopped calling tools');
|
|
680
|
+
assert(/store\.running !== true\) return/.test(touch), 'touch() arms a teardown even when no run is lit: a read-only session would schedule a stop for a run that never started');
|
|
681
|
+
// The teardown body lives in fireIdle now (touch arms it, fireIdle decides); the busy guard is
|
|
682
|
+
// the F-22 fix: a 40 s OCR / long batch in flight is NOT silence, and firing under it finished
|
|
683
|
+
// the run out from under the action, then the next action re-claimed — the capsule flickered.
|
|
684
|
+
const fireIdle = tools.match(/const fireIdle = \(\) => \{([\s\S]*?)\n \};/)?.[1];
|
|
685
|
+
assert(fireIdle !== undefined, 'fireIdle() is missing: the idle teardown body is gone');
|
|
686
|
+
assert(/finishRun\(/.test(fireIdle), 'the idle timer no longer ends the run: the capsule stays up until the 300 s lease');
|
|
687
|
+
assert(/store\.running !== true\) return/.test(fireIdle), 'fireIdle tears down a run that already ended');
|
|
688
|
+
assert(/store\.busy === true/.test(fireIdle) && /setTimeout\(fireIdle/.test(fireIdle), 'the idle timer has no busy guard: an in-flight action gets its run finished underneath it');
|
|
689
|
+
assert(!/renewLease|\.observe\(/.test(fireIdle), 'the idle timer renews the overlay instead of ending it: that is the immortal-capsule bug again');
|
|
690
|
+
// The idle finish must say WHO ended it (F-38): a silent teardown reported as 模型宣告完成
|
|
691
|
+
// misreads a dead run as a done one.
|
|
692
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
693
|
+
assert(/reason: 'idle'/.test(tools), 'the idle teardown does not pass reason:"idle"');
|
|
694
|
+
assert(/reason === 'idle'/.test(index), 'index.js finishRun ignores the reason: an idle teardown still logs as 模型宣告完成');
|
|
695
|
+
assert(/Number\(process\.env\.DSH_NATIVE_UIA_IDLE_MS \?\? 20000\) \|\| 20000/.test(tools), 'idleMs lost its NaN guard: a malformed env value fires the timer immediately and kills a fresh run');
|
|
696
|
+
// Every tool must pass through the one wrapper, or an untouched tool could be the last call of
|
|
697
|
+
// a run and the countdown would never start.
|
|
698
|
+
const raw = (tools.match(/ctx\.tools\.register\(defineTool\(\{/g) ?? []).length;
|
|
699
|
+
const wrapped = (tools.match(/disposers\.push\(register\(defineTool\(\{/g) ?? []).length;
|
|
700
|
+
assert(raw === 0, `${raw} tool(s) still bypass the touch wrapper and would not arm the idle timer`);
|
|
701
|
+
assert(wrapped >= 18, `only ${wrapped} tools go through the wrapper`);
|
|
702
|
+
return `every tool (${wrapped}) touches the idle timer; busy defers, idle reason reported, env guarded`;
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
gate('computer_done clears the target it was driving', () => {
|
|
706
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
707
|
+
const done = tools.match(/name: 'computer_done'([\s\S]*?)\n \}\)\)\);/)?.[1];
|
|
708
|
+
assert(done !== undefined, 'computer_done is missing');
|
|
709
|
+
assert(/store\.setTarget\(null\)/.test(done), 'computer_done leaves the driven window as the session target: the panel keeps advertising a window the run no longer owns');
|
|
710
|
+
assert(/disarmIdle\(\)/.test(done), 'computer_done does not disarm the idle timer: an explicit finish could be followed by a second teardown');
|
|
711
|
+
return 'an explicit finish clears the target and the idle timer';
|
|
712
|
+
});
|
|
713
|
+
|
|
714
|
+
gate('computer_done declares the ending: done / blocked / failed', () => {
|
|
715
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
716
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
717
|
+
const done = tools.match(/name: 'computer_done'([\s\S]*?)\n \}\)\)\);/)?.[1];
|
|
718
|
+
assert(done !== undefined, 'computer_done is missing');
|
|
719
|
+
// The model needs a graceful exit for "the channel is stuck": without an outcome enum every
|
|
720
|
+
// ending renders as 已完成, and an infeasible task can only be signalled by retrying forever.
|
|
721
|
+
assert(/outcome: \{ type: 'string', enum: \['done', 'blocked', 'failed'\]/.test(done), 'computer_done has no outcome enum: the model cannot declare a blocked/failed ending');
|
|
722
|
+
assert(/finishRun\(\{ summary, outcome \}\)/.test(done), 'computer_done does not forward the outcome to finishRun');
|
|
723
|
+
// finishRun honours the outcome and defaults it to done.
|
|
724
|
+
assert(/outcome = 'done'/.test(index), 'finishRun does not default the outcome to done');
|
|
725
|
+
assert(/模型宣告受阻未完成/.test(index) && /模型宣告失败放弃/.test(index), 'finishRun collapses blocked/failed endings into 模型宣告完成 again');
|
|
726
|
+
// Only the done branch may say 已完成: the blocked/failed branch texts must not.
|
|
727
|
+
const blockedText = done.match(/blocked: \{[\s\S]*?text: `([^`]+)`/)?.[1] ?? '';
|
|
728
|
+
const failedText = done.match(/failed: \{[\s\S]*?text: `([^`]+)`/)?.[1] ?? '';
|
|
729
|
+
assert(blockedText !== '' && !/已完成/.test(blockedText), 'the blocked ending still renders as 已完成');
|
|
730
|
+
assert(failedText !== '' && !/已完成/.test(failedText), 'the failed ending still renders as 已完成');
|
|
731
|
+
return 'outcome enum on the tool, three finishRun verdicts, blocked/failed never say 已完成';
|
|
732
|
+
});
|
|
733
|
+
|
|
734
|
+
gate('Esc is watched on the always-idle overlay channel, so a long worker command cannot swallow it', () => {
|
|
735
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
736
|
+
const esc = index.match(/const escTimer = setInterval\(\(\) => \{([\s\S]*?)\n \}, (\d+)\)/);
|
|
737
|
+
assert(esc !== null, 'the Esc watchdog block was not found in index.js');
|
|
738
|
+
const [, block, interval] = esc;
|
|
739
|
+
// The interval is a latency contract, not a detail: a tap shorter than the poll gap is only
|
|
740
|
+
// recoverable because the probe latches the key-down edge, and the latch is consumed by the
|
|
741
|
+
// next poll. Anything at or above the old 120 ms made a normal tap feel ignored.
|
|
742
|
+
assert(Number(interval) <= 60, `the Esc watchdog polls every ${interval} ms: a quick tap waits too long to be noticed`);
|
|
743
|
+
assert(/indicator\.pending\.size === 0\s*\n?\s*\?\s*indicator/.test(block), 'the Esc watchdog no longer prefers the indicator channel: a tapped Esc during a long worker command goes unseen');
|
|
744
|
+
assert(/worker\.pending\.size === 0 \? worker : null/.test(block), 'the worker fallback lost its queue-empty gate: probes would pile up behind real work');
|
|
745
|
+
// The watchdog must gate on the RUN, not on whether the overlay happens to be painted: the
|
|
746
|
+
// overlay self-closes after 20 s of tool silence, and gating on it made Esc dead exactly while a
|
|
747
|
+
// person watches the model think (measured 2026-11-21: no response at all, run still open).
|
|
748
|
+
assert(!/escBusy \|\| !activity\.active/.test(block), 'the Esc watchdog gates on activity.active again: a thinking pause makes Esc unresponsive');
|
|
749
|
+
assert(/store\.running !== true && store\.busy !== true/.test(block), 'the Esc watchdog no longer gates on the live run plus in-flight commands');
|
|
750
|
+
const server = readFileSync(join(ROOT, 'worker', 'indicator-server.ps1'), 'utf8');
|
|
751
|
+
assert(/escape_pressed\s*=\s*'Cmd-EscapePressed'/.test(server), 'the indicator does not answer escape_pressed');
|
|
752
|
+
assert(/GetAsyncKeyState/.test(server), 'the indicator cannot sense the physical Esc key');
|
|
753
|
+
// Sampling only the high bit loses any press released between two polls; the low bit is the
|
|
754
|
+
// "pressed since the last call" latch that makes a quick tap count exactly once.
|
|
755
|
+
assert(/-band 0x0001/.test(server), 'the indicator samples only the held bit: a tap released between two polls is lost');
|
|
756
|
+
const worker = readFileSync(join(ROOT, 'worker', 'uia-worker.ps1'), 'utf8');
|
|
757
|
+
assert(/Cmd-EscapePressed[\s\S]{0,600}-band 0x0001/.test(worker), 'the worker fallback samples only the held bit: a quick tap is lost when the indicator is down');
|
|
758
|
+
return `indicator primary (${interval} ms poll, key-down latch), worker fallback with the same latch, neither probed behind its own queue`;
|
|
759
|
+
});
|
|
760
|
+
|
|
761
|
+
gate('find_text is a first-class tool, not just a worker command', () => {
|
|
762
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
763
|
+
assert(/name: 'computer_find_text'/.test(tools), 'computer_find_text is not registered: the worker implements find_text and the click guidance names it, but the model cannot call it');
|
|
764
|
+
const client = readFileSync(join(ROOT, 'src', 'worker-client.js'), 'utf8');
|
|
765
|
+
assert(/'find_text'/.test(client), 'find_text is not in the observation whitelist, so it would neither renew the lease nor beat the overlay');
|
|
766
|
+
return 'computer_find_text registered and classified as observation';
|
|
767
|
+
});
|
|
768
|
+
|
|
769
|
+
gate('every worker command the error messages name is reachable', () => {
|
|
770
|
+
// The regression: worker error text told the model to "call list_windows or resolve_window
|
|
771
|
+
// first" while resolve_window was never exposed as a tool — the advice pointed at a door that
|
|
772
|
+
// did not exist. Any command the worker names in an error must be model-callable.
|
|
773
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
774
|
+
const workerSrc = readFileSync(join(ROOT, 'worker', 'uia-worker.ps1'), 'utf8');
|
|
775
|
+
const named = [...workerSrc.matchAll(/Err '[a-z_]+' \([^)]*?([a-z_]+) first/g)].map((m) => m[1]);
|
|
776
|
+
for (const cmd of new Set(named)) {
|
|
777
|
+
assert(new RegExp(`worker\\.call\\('${cmd}'`).test(tools) || cmd === 'list_windows' && /worker\.call\('list_windows'/.test(tools),
|
|
778
|
+
`the worker tells the model to call ${cmd} first, but no tool sends it`);
|
|
779
|
+
}
|
|
780
|
+
assert(/name: 'computer_resolve_window'/.test(tools), 'computer_resolve_window is not registered, so a stale windowId after a relaunch has no recovery path');
|
|
781
|
+
return `named-in-errors: ${[...new Set(named)].join(', ') || 'none'}; resolve_window exposed`;
|
|
782
|
+
});
|
|
783
|
+
|
|
784
|
+
gate('the overlay has exactly two visible states, and no phase is dead', () => {
|
|
785
|
+
const activity = readFileSync(join(ROOT, 'src', 'activity-window.js'), 'utf8');
|
|
786
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
787
|
+
const server = readFileSync(join(ROOT, 'worker', 'indicator-server.ps1'), 'utf8');
|
|
788
|
+
// The paused state was removed from the product: no switch could reach it. A phase with no
|
|
789
|
+
// caller is dead code, so assert the remaining set is both reachable and small.
|
|
790
|
+
for (const phase of ['acting', 'stopped']) {
|
|
791
|
+
assert(new RegExp(`phase: '${phase}'`).test(activity), `phase "${phase}" is never sent by the plugin`);
|
|
792
|
+
assert(new RegExp(`${phase}\\s*=`).test(server), `phase "${phase}" is not rendered`);
|
|
793
|
+
}
|
|
794
|
+
assert(!/phase: 'waiting'/.test(activity) && !/phase: 'waiting'/.test(index), 'a waiting phase came back, but no switch can reach it');
|
|
795
|
+
assert(!/\bwaiting\(\)/.test(activity), 'ActivityWindow.waiting() is back: a phase nobody calls is dead code');
|
|
796
|
+
assert(!/\bresume\(\)/.test(activity), 'ActivityWindow.resume() is back: nothing can resume a run that cannot pause');
|
|
797
|
+
assert(/activity\.claim\(/.test(index), 'no owner claims the overlay');
|
|
798
|
+
assert(/activity\.observe\(/.test(index), 'observation no longer renews the lease');
|
|
799
|
+
assert(/kind === 'kill'[\s\S]{0,300}?activity\.end\(/.test(index), 'kill must end the run, not park it in some third state');
|
|
800
|
+
// Every visible phase carries the brand, so the capsule never loses 御屏 on a phase change.
|
|
801
|
+
const pill = server.match(/\$script:PILL = @\{([\s\S]*?)\n\}/)?.[1] ?? '';
|
|
802
|
+
for (const phase of ['acting', 'stopped']) {
|
|
803
|
+
assert(new RegExp(`${phase}\\s*=\\s*\\(\\$script:TEXT\\.brand`).test(pill), `PILL.${phase} drops the brand: the capsule would lose 御屏 on that phase`);
|
|
804
|
+
}
|
|
805
|
+
assert(!/\bwaiting\b/.test(pill), 'PILL still carries a waiting entry');
|
|
806
|
+
return 'two visible phases (acting/stopped), both branded, neither dead';
|
|
807
|
+
});
|
|
808
|
+
|
|
809
|
+
gate('a broken overlay can never fail a desktop action', () => {
|
|
810
|
+
const activity = readFileSync(join(ROOT, 'src', 'activity-window.js'), 'utf8');
|
|
811
|
+
assert(/catch[^{]*\{[\s\S]{0,200}?this\.failures\+\+/.test(activity), 'the indicator send path does not swallow failures');
|
|
812
|
+
assert(!/throw /.test(activity), 'activity-window rethrows: an overlay outage would surface as a desktop-action failure');
|
|
813
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
814
|
+
const probe = index.match(/try \{\s*const screens = await indicator\.call\([\s\S]*?\n \}/)?.[0];
|
|
815
|
+
assert(probe !== undefined, 'the startup overlay probe is missing');
|
|
816
|
+
assert(!/throw/.test(probe), 'the overlay probe throws on failure, which would block activation for a cosmetic feature');
|
|
817
|
+
return 'overlay outage degrades to a log line';
|
|
818
|
+
});
|
|
819
|
+
|
|
820
|
+
gate('the stop latch expires instead of blocking the next instruction', () => {
|
|
821
|
+
// Measured 2026-11-21: Esc armed the latch, the next mutating call consumed it and was refused,
|
|
822
|
+
// the model read that as a dead session and never retried, so `killed` stayed true and the run
|
|
823
|
+
// could never light again - the overlay looked unresponsive after a stop the person asked for.
|
|
824
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
825
|
+
const state = readFileSync(join(ROOT, 'src', 'state.js'), 'utf8');
|
|
826
|
+
assert(/const HALT_LATCH_MS = \d+;/.test(index), 'the kill latch lost its expiry window');
|
|
827
|
+
assert(/killedAt/.test(index) && /HALT_LATCH_MS/.test(index), 'the halt callback no longer compares the latch age');
|
|
828
|
+
assert(/if \(ageMs > HALT_LATCH_MS\)/.test(index), 'a stale latch no longer releases the next instruction');
|
|
829
|
+
assert(/killedAt = 0;/.test(state), 'the store has no killedAt field to measure the latch age');
|
|
830
|
+
assert(/if \(value === true\) this\.killedAt = Date\.now\(\);/.test(state), 'arming the latch does not record when it was armed');
|
|
831
|
+
// Esc dismisses the overlay, so nothing else would ever consume a latch nobody read.
|
|
832
|
+
assert(/clearAt/.test(index), 'nothing clears a latch that no command ever consumed after Esc');
|
|
833
|
+
return 'window + timestamp + stale release + scheduled clear';
|
|
834
|
+
})
|
|
835
|
+
|
|
836
|
+
gate('indicator script is present for the overlay client', () => {
|
|
837
|
+
const file = join(ROOT, 'worker', 'indicator-server.ps1');
|
|
838
|
+
if (!existsSync(file)) return 'SKIP';
|
|
839
|
+
const text = readFileSync(file, 'utf8');
|
|
840
|
+
for (const cmd of ['show', 'beat', 'phase', 'shutdown', 'ping']) {
|
|
841
|
+
assert(new RegExp(`['"]?${cmd}['"]?`).test(text), `indicator-server.ps1 never handles "${cmd}"`);
|
|
842
|
+
}
|
|
843
|
+
// Negative half: the dead commands hide/state must not be re-registered. phase:'hidden' is
|
|
844
|
+
// the ONE entry that lowers the overlay, so a hide/state dispatch entry (or a client call)
|
|
845
|
+
// means a second indicator owner came back. The regex only matches a dispatch-table entry
|
|
846
|
+
// shaped `name = 'Cmd-...'`, so Hide-Overlay/hideCount and the phase:'hidden' payload
|
|
847
|
+
// cannot trip it.
|
|
848
|
+
assert(!/^\s*(hide|state)\s*=\s*'Cmd-/m.test(text), 'a hide/state handler came back in the indicator dispatch table: phase must stay the only hidden-entry');
|
|
849
|
+
const activity = readFileSync(join(ROOT, 'src', 'activity-window.js'), 'utf8');
|
|
850
|
+
assert(!/#send\('(hide|state)'/.test(activity), 'the activity window sends the dead hide/state command again: phase is the only hidden-entry');
|
|
851
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
852
|
+
assert(!/indicator\.call\('(hide|state)'/.test(index), 'index.js calls the dead hide/state indicator command directly');
|
|
853
|
+
assert(/WS_EX_TRANSPARENT/.test(text), 'the overlay window is not click-through, which would eat the user mouse');
|
|
854
|
+
return `${text.split('\n').length} lines, click-through style declared`;
|
|
855
|
+
});
|
|
856
|
+
|
|
857
|
+
gate('the panel offers exactly one control: Esc stops the run', () => {
|
|
858
|
+
const html = readFileSync(join(ROOT, 'web', 'control.html'), 'utf8');
|
|
859
|
+
const resurrected = ['btnPause', 'btnKillCancel', 'btnKill', 'doPauseToggle', 'setKillArmed'].filter((id) => html.includes(id));
|
|
860
|
+
assert(resurrected.length === 0, `the panel grew controls back: ${resurrected.join(', ')}`);
|
|
861
|
+
assert(/function stopRun\(/.test(html), 'stopRun is gone, so Esc has nothing to call');
|
|
862
|
+
assert(/e\.key === 'Escape'[\s\S]{0,200}?stopRun\(\)/.test(html), 'Esc no longer stops the run');
|
|
863
|
+
assert(/id="runState"/.test(html) && /sess\(\)\.running === true/.test(html), 'the run state chip is missing or not driven by the claim lease');
|
|
864
|
+
const state = readFileSync(join(ROOT, 'src', 'state.js'), 'utf8');
|
|
865
|
+
assert(/running: this\.running === true/.test(state), 'the snapshot does not publish the run lease');
|
|
866
|
+
const index = readFileSync(join(ROOT, 'src', 'index.js'), 'utf8');
|
|
867
|
+
assert(/store\.setKilled\(false\)/.test(index), 'the next action does not clear the stopped flag');
|
|
868
|
+
assert(!/setPaused|store\.paused/.test(index), 'a pause state came back: the product has no pause switch');
|
|
869
|
+
// The latch must be cleared by halt itself: clearing it in onActionStart is unreachable,
|
|
870
|
+
// because call() throws HaltedError before onActionStart ever runs (measured: one Esc then
|
|
871
|
+
// every later action stayed halted forever). One-shot refusal, next action restarts.
|
|
872
|
+
assert(/halt: \(\) => \{[\s\S]{0,300}?!?store\.killed[\s\S]{0,300}?store\.setKilled\(false\)/.test(index)
|
|
873
|
+
|| /halt: \(\) => \{[\s\S]{0,300}?store\.killed[\s\S]{0,300}?store\.setKilled\(false\)/.test(index),
|
|
874
|
+
'the kill latch is not a one-shot gate cleared at the choke point');
|
|
875
|
+
return 'Esc only; two states; a stopped run can be restarted by the next action';
|
|
876
|
+
});
|
|
877
|
+
|
|
878
|
+
gate('the panel never offers to approve what policy hard-refuses', () => {
|
|
879
|
+
const html = readFileSync(join(ROOT, 'web', 'control.html'), 'utf8');
|
|
880
|
+
assert(!/data-ap=/.test(html), 'the page renders an approve button again: the server answers every approve with ok:false');
|
|
881
|
+
assert(!/kind:\s*'approve'/.test(html), "the page still POSTs kind:'approve'");
|
|
882
|
+
assert(/硬拒不可批准/.test(html), 'the refusal row lost its non-approvable note');
|
|
883
|
+
return 'deny only, and the row says why';
|
|
884
|
+
});
|
|
885
|
+
|
|
886
|
+
gate('the panel injects the module that declares the slot it registers into', () => {
|
|
887
|
+
const ui = JSON.parse(readFileSync(join(UI_ROOT, 'package.json'), 'utf8'));
|
|
888
|
+
const client = readFileSync(join(UI_ROOT, 'client', 'client.js'), 'utf8');
|
|
889
|
+
const slots = [...new Set([...client.matchAll(/ctx\.slots\.(?:inject|register)\(\s*'([a-z.]+)'/g)].map((m) => m[1]))];
|
|
890
|
+
assert(slots.length > 0, 'the panel registers into no slot');
|
|
891
|
+
const inject = ui.dsh?.client?.inject ?? [];
|
|
892
|
+
const missing = slots.filter((slot) => {
|
|
893
|
+
const owner = slot.split('.')[0];
|
|
894
|
+
return !inject.some((pkg) => pkg.endsWith(`-${owner}`) || pkg.endsWith(`-${owner}-slots`));
|
|
895
|
+
});
|
|
896
|
+
assert(missing.length === 0, `slot(s) ${missing.join(', ')} are declared by a module this package does not inject: registration can run before the slot exists and the tab never appears`);
|
|
897
|
+
return `${slots.join(', ')} covered by ${inject.length} inject entries`;
|
|
898
|
+
});
|
|
899
|
+
|
|
900
|
+
gate('the icon cannot blob at the size the card renders it', () => {
|
|
901
|
+
const svg = readFileSync(join(ROOT, 'icon.svg'), 'utf8');
|
|
902
|
+
const uiSvg = readFileSync(join(UI_ROOT, 'icon.svg'), 'utf8');
|
|
903
|
+
assert(svg === uiSvg, 'the two packages ship different icons');
|
|
904
|
+
const paths = [...svg.matchAll(/<path/g)].length;
|
|
905
|
+
assert(paths <= 3, `${paths} path elements; the official artwork family ships 1-2, and more than that is unreadable at 36px`);
|
|
906
|
+
assert(!/stopColor=|strokeWidth=|strokeLinecap=/.test(svg), 'React camelCase attributes in a raw SVG: stopColor does not exist in SVG, so the gradient silently falls back to black');
|
|
907
|
+
assert(/stop-color="#54ECE7"/.test(svg) && /stop-color="#658EFF"/.test(svg), 'the icon gradient is not the host Default artwork pair');
|
|
908
|
+
assert(/stroke="#679EFE"/.test(svg), 'the icon stroke is not the host Terminal artwork colour (#679EFE)');
|
|
909
|
+
const ticks = [...svg.matchAll(/[hH]\d/g)].length;
|
|
910
|
+
assert(ticks <= 2, `${ticks} horizontal segments: three or more ticks on one stem renders as the letter E at 36px`);
|
|
911
|
+
const strokes = [...svg.matchAll(/stroke-width="([\d.]+)"/g)].map((m) => Number(m[1]));
|
|
912
|
+
assert(strokes.length > 0 && strokes.every((s) => s === 3.5), `stroke widths ${strokes.join(',')} do not match the family value 3.5`);
|
|
913
|
+
const tickYs = [...svg.matchAll(/M[\d.]+ ([\d.]+)h/g)].map((m) => Number(m[1]));
|
|
914
|
+
if (tickYs.length >= 2) {
|
|
915
|
+
const widest = Math.max(...strokes);
|
|
916
|
+
const tight = tickYs.slice(1).map((y, i) => y - tickYs[i]).filter((gap) => gap < widest + 1.5);
|
|
917
|
+
assert(tight.length === 0, `tick centre lines ${tickYs.join('/')} leave gaps under stroke+1.5px (${tight.join(',')}), so the strokes overlap into one blob`);
|
|
918
|
+
}
|
|
919
|
+
return `${paths} paths, stroke ${Math.max(...strokes)}, ${ticks} horizontal segment(s)`;
|
|
920
|
+
});
|
|
921
|
+
|
|
922
|
+
gate('every inserted row has a host-resolvable entry module', () => {
|
|
923
|
+
const patch = readFileSync(join(ROOT, 'cordis.patch.yml'), 'utf8');
|
|
924
|
+
const rows = [...patch.matchAll(/-\s*id:\s*([a-z0-9-]+)[\s\S]*?name:\s*'([a-z0-9._/-]+)'/g)].map((m) => ({ id: m[1], pkg: m[2] }));
|
|
925
|
+
assert(rows.length >= 1, `the patch inserts ${rows.length} row(s); the card row is missing`);
|
|
926
|
+
const missing = [];
|
|
927
|
+
for (const row of rows) {
|
|
928
|
+
// Subpath row names (pkg/sub) resolve through the package's own exports; a
|
|
929
|
+
// bare name resolves through exports["."] or main. Either way the file must exist.
|
|
930
|
+
const [pkgName, subpath] = row.pkg.includes('/') ? [row.pkg.split('/')[0], row.pkg.split('/').slice(1).join('/')] : [row.pkg, ''];
|
|
931
|
+
const dir = pkgName === 'dsh-native-uia' ? ROOT : join(dirname(ROOT), pkgName);
|
|
932
|
+
const manifestPath = join(dir, 'package.json');
|
|
933
|
+
if (!existsSync(manifestPath)) { missing.push(`${row.id}: no manifest at ${dir}`); continue; }
|
|
934
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
935
|
+
const entry = subpath ? manifest.exports?.[`./${subpath}`] : (manifest.exports?.['.'] ?? manifest.main);
|
|
936
|
+
if (typeof entry !== 'string') { missing.push(`${row.id}: package.json declares no "${subpath ? './' + subpath : '.'}" export or main, so the host cannot import the row`); continue; }
|
|
937
|
+
const file = join(dir, entry.replace(/^\.\//, ''));
|
|
938
|
+
if (!existsSync(file)) { missing.push(`${row.id}: entry ${entry} does not exist on disk`); continue; }
|
|
939
|
+
const text = readFileSync(file, 'utf8');
|
|
940
|
+
if (!/export (function apply|const name|default class)/.test(text)) missing.push(`${row.id}: ${entry} exports no apply/name/default, so the loader has nothing to mount`);
|
|
941
|
+
}
|
|
942
|
+
assert(missing.length === 0, missing.join(' | '));
|
|
943
|
+
return `${rows.length} rows: ${rows.map((r) => r.id).join(', ')}`;
|
|
944
|
+
});
|
|
945
|
+
|
|
946
|
+
gate('the panel keeps a slim status strip and no title block', () => {
|
|
947
|
+
const html = readFileSync(join(ROOT, 'web', 'control.html'), 'utf8');
|
|
948
|
+
const resurrected = ['class="brand"', 'id="uptime"', 'id="policyChip"', 'id="busyChip"', 'class="mark"'].filter((s) => html.includes(s));
|
|
949
|
+
assert(resurrected.length === 0, `the title block grew back: ${resurrected.join(', ')}`);
|
|
950
|
+
const bar = html.indexOf('topbar slim');
|
|
951
|
+
const grid = html.indexOf('<main class="grid"');
|
|
952
|
+
assert(bar > 0 && grid > bar, 'the status strip is not above the grid: it should sit at the top, thin');
|
|
953
|
+
assert(/\.topbar\.slim\{[^}]*padding:3px/.test(html), 'the slim strip has no compressed padding rule, so it inherits the old 10px header height');
|
|
954
|
+
assert(/id="runState"/.test(html) && /id="connText"/.test(html) && /id="targetChip"/.test(html), 'the strip lost connection, target, or run state');
|
|
955
|
+
return 'one thin strip on top; brand, uptime, policy and busy chips are gone';
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
gate('the overlay palette is plugin-owned data and is lavender', () => {
|
|
959
|
+
const activity = readFileSync(join(ROOT, 'src', 'activity-window.js'), 'utf8');
|
|
960
|
+
const block = activity.match(/export const PALETTE = \{([\s\S]*?)\n\};/);
|
|
961
|
+
assert(block !== undefined, 'no exported PALETTE: colour would be baked into the renderer');
|
|
962
|
+
const hexes = Object.fromEntries([...block[1].matchAll(/(\w+):\s*'#([0-9A-Fa-f]{6})'/g)].map((m) => [m[1], m[2].toUpperCase()]));
|
|
963
|
+
assert(hexes.ringFrom !== undefined && hexes.ringTo !== undefined && hexes.pillBorder !== undefined, `PALETTE is missing keys, has ${Object.keys(hexes).join(',')}`);
|
|
964
|
+
const rgb = (hex) => [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16)];
|
|
965
|
+
const strict = ['ringFrom', 'ringTo', 'pillBorder'];
|
|
966
|
+
const wrong = strict.filter((k) => {
|
|
967
|
+
const [r, g, b] = rgb(hexes[k]);
|
|
968
|
+
return !(b >= r && r > g && b - g >= 40);
|
|
969
|
+
});
|
|
970
|
+
assert(wrong.length === 0, `these are not in the lavender family (need blue highest, red above green, b-g>=40): ${wrong.join(', ')}`);
|
|
971
|
+
const [pr, pg, pb] = rgb(hexes.pillBg);
|
|
972
|
+
assert(pb > pg && pr > pg, 'pillBg is not a purple-tinted dark');
|
|
973
|
+
const [tr, tg, tb] = rgb(hexes.pillText);
|
|
974
|
+
assert(tb >= tr && tr >= tg && tr > 200, 'pillText is not a lavender-white');
|
|
975
|
+
assert(!activity.includes('679EFE'), 'the old host-blue accent is still in the palette');
|
|
976
|
+
assert(/\{ \.\.\.args, palette: PALETTE \}/.test(activity), 'the palette is not handed to the renderer on show/phase/beat');
|
|
977
|
+
return Object.entries(hexes).map(([k, v]) => `${k}=#${v}`).join(' ');
|
|
978
|
+
});
|
|
979
|
+
|
|
980
|
+
gate('every alias the dark theme defines is re-mapped for light', () => {
|
|
981
|
+
const html = readFileSync(join(ROOT, 'web', 'control.html'), 'utf8');
|
|
982
|
+
const root = html.match(/:root\{([\s\S]*?)\n \}/)?.[1] ?? '';
|
|
983
|
+
const light = html.match(/prefers-color-scheme: light[\s\S]*?:root\{([\s\S]*?)\n \}/)?.[1];
|
|
984
|
+
assert(light !== undefined, 'the page has no light media block: it renders dark in a light host (measured on the user\'s screen)');
|
|
985
|
+
const darkVars = [...new Set([...root.matchAll(/(--dsw-alias-[a-z0-9-]+):/g)].map((m) => m[1]))];
|
|
986
|
+
const lightVars = new Set([...light.matchAll(/(--dsw-alias-[a-z0-9-]+):/g)].map((m) => m[1]));
|
|
987
|
+
const missing = darkVars.filter((v) => !lightVars.has(v));
|
|
988
|
+
assert(missing.length === 0, `light theme leaves ${missing.join(', ')} at dark values`);
|
|
989
|
+
assert(/color-scheme:\s*light dark/.test(html), 'no color-scheme declaration, so prefers-color-scheme may not resolve as the host expects');
|
|
990
|
+
const client = readFileSync(join(UI_ROOT, 'client', 'client.js'), 'utf8');
|
|
991
|
+
assert(!/#151517|#1b2027/.test(client), 'the panel container hard-codes a dark surface again: it shows as a dark frame in light mode');
|
|
992
|
+
return `${darkVars.length} aliases mapped in both themes`;
|
|
993
|
+
});
|
|
994
|
+
|
|
995
|
+
const worker = join(ROOT, 'worker', 'uia-worker.ps1');
|
|
996
|
+
gate('worker file is present for the spawn site', () => {
|
|
997
|
+
assert(existsSync(worker), 'worker/uia-worker.ps1 is absent');
|
|
998
|
+
const client = readFileSync(join(ROOT, 'src', 'worker-client.js'), 'utf8');
|
|
999
|
+
assert(client.includes('../worker/uia-worker.ps1'), 'worker-client does not reference that path');
|
|
1000
|
+
return `${readFileSync(worker, 'utf8').split('\n').length} lines`;
|
|
1001
|
+
});
|
|
1002
|
+
|
|
1003
|
+
gate('the two snapshot crash sites cannot regress to a null Hashtable key', () => {
|
|
1004
|
+
// A Hashtable indexed with $null throws "Exception getting Item: Key cannot be null", which
|
|
1005
|
+
// surfaced as a WHOLE snapshot failing with internal_error — intermittently, only on trees that
|
|
1006
|
+
// triggered eviction or on a provider reporting a pattern with no name/id. Both sites are fixed;
|
|
1007
|
+
// this gate pins exactly those two, because they fail only under load and so pass every casual
|
|
1008
|
+
// run. Other .Item() uses take keys built from [string] casts and are not in scope.
|
|
1009
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1010
|
+
const evict = ps.match(/function Evict-ForReservation[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1011
|
+
assert(evict !== '', 'Evict-ForReservation is missing');
|
|
1012
|
+
assert(!/refs\.Item\(/.test(evict), 'eviction indexes the ref map with .Item() again: a null ref aborts the snapshot');
|
|
1013
|
+
assert(/IsNullOrEmpty\(\[string\]\$rk\)/.test(evict), 'eviction no longer guards its ref key');
|
|
1014
|
+
assert(/ContainsKey\(\$rk\)/.test(evict), 'eviction indexes the ref map without ContainsKey');
|
|
1015
|
+
const pat = ps.match(/function PatternsOf[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1016
|
+
assert(pat !== '', 'PatternsOf is missing');
|
|
1017
|
+
assert(!/patCache\.Item\(/.test(pat), 'PatternsOf uses .Item() on its cache again: a nameless pattern aborts the snapshot');
|
|
1018
|
+
assert(/IsNullOrEmpty\(\$pk\)/.test(pat), 'PatternsOf can still add a null pattern name to the signature');
|
|
1019
|
+
assert(/ContainsKey\(\$pk\)/.test(pat), 'PatternsOf indexes its cache without ContainsKey');
|
|
1020
|
+
return 'eviction and pattern caching both guard their keys';
|
|
1021
|
+
});
|
|
1022
|
+
|
|
1023
|
+
gate('the snapshot stays cheap and readable for a text model', () => {
|
|
1024
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1025
|
+
// Default node budget: every node is a COM round-trip AND tokens, so the default must not creep
|
|
1026
|
+
// back to the old 300 without someone noticing.
|
|
1027
|
+
assert(/maxNodes: args\.maxNodes \?\? 200/.test(tools), 'the snapshot default node budget changed: 200 is the measured speed/size trade');
|
|
1028
|
+
// Non-actionable patterns are pure noise in a rendered tree.
|
|
1029
|
+
assert(/const ACTIONABLE = new Set\(\[/.test(tools), 'the actionable-pattern filter is gone: every UIA pattern is rendered again');
|
|
1030
|
+
assert(/renderActionables\(nodes\)/.test(tools), 'the actionable summary line is no longer printed before the tree');
|
|
1031
|
+
return 'default 200 nodes, actionable-only patterns, summary line before the tree';
|
|
1032
|
+
});
|
|
1033
|
+
|
|
1034
|
+
gate('computer_snapshot exposes depth and passes it through as maxDepth', () => {
|
|
1035
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1036
|
+
const snap = tools.match(/name: 'computer_snapshot'([\s\S]*?)\n \}\)\)\);/)?.[1];
|
|
1037
|
+
assert(snap !== undefined, 'computer_snapshot is missing');
|
|
1038
|
+
// The worker already honours maxDepth (uia-worker.ps1 Build-Snapshot, default 30); the tool
|
|
1039
|
+
// layer must surface it as `depth` or the shallow-first rhythm stays unreachable.
|
|
1040
|
+
assert(/depth: \{ \.\.\.INT,/.test(snap), 'computer_snapshot has no depth parameter: the shallow-first pass cannot be requested');
|
|
1041
|
+
// Pass-through must reach the worker call, not just the schema.
|
|
1042
|
+
assert(/maxDepth: args\.depth/.test(snap), 'computer_snapshot does not pass depth through as maxDepth to the worker');
|
|
1043
|
+
assert(/depth=4-5/.test(snap), 'the snapshot description no longer teaches the shallow-first rhythm');
|
|
1044
|
+
return 'depth parameter declared and forwarded as worker maxDepth';
|
|
1045
|
+
});
|
|
1046
|
+
|
|
1047
|
+
gate('find_text ranks actionable hits first and labels containers', () => {
|
|
1048
|
+
// Searching a window title ("插件") matches the window's own Pane and Document first — both huge,
|
|
1049
|
+
// both clickable only in the "focus the window" sense. A model reading top-down picks #1 and
|
|
1050
|
+
// reports "点不准", even though the coordinates were exact (measured 0 px error on this box).
|
|
1051
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1052
|
+
const block = tools.match(/const matches = result\.matches \?\? \[\];[\s\S]*?return `\$\{head\}/)?.[0] ?? '';
|
|
1053
|
+
assert(block !== '', 'the find_text result block was not found');
|
|
1054
|
+
assert(/isContainer/.test(block), 'find_text no longer distinguishes whole-window containers');
|
|
1055
|
+
assert(/ranked/.test(block) && /\.sort\(/.test(block), 'find_text results are unsorted again: a container can sit at #1');
|
|
1056
|
+
assert(/可作=/.test(block), 'find_text stopped publishing which actions a hit supports');
|
|
1057
|
+
assert(/容器/.test(block), 'find_text stopped labelling container hits');
|
|
1058
|
+
return 'actionable first, containers last and labelled';
|
|
1059
|
+
});
|
|
1060
|
+
|
|
1061
|
+
gate('a no-op action tells the model it changed nothing', () => {
|
|
1062
|
+
// The FIRST version of this check used before===after, which was wrong: before/after read the
|
|
1063
|
+
// element's Value, and a Button has none — so every successful invoke on a normal button was
|
|
1064
|
+
// flagged as a no-op (live report: invoke on e7 "最小化" printed a false warning). The honest
|
|
1065
|
+
// test is whether the element exposes a pattern for the requested verb.
|
|
1066
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1067
|
+
const act = tools.match(/name: 'computer_act'[\s\S]*?\n \}\)\)\);/)?.[0] ?? '';
|
|
1068
|
+
assert(act !== '', 'computer_act is missing');
|
|
1069
|
+
assert(!/JSON\.stringify\(result\.before\) === JSON\.stringify\(result\.after\)/.test(act),
|
|
1070
|
+
'before===after is back as the no-op test: a Button has no Value, so every successful invoke gets flagged');
|
|
1071
|
+
assert(/const NEEDED = \{/.test(act), 'the per-verb capability table is missing');
|
|
1072
|
+
assert(/availablePatterns/.test(act), 'the no-op check no longer reads the element capabilities');
|
|
1073
|
+
assert(/\|\| !capable/.test(act), 'a call on an incapable element is no longer reported');
|
|
1074
|
+
assert(/没有真正执行/.test(act), 'computer_act no longer explains an incapable target');
|
|
1075
|
+
// And before/after must not be shown when the element has no value at all.
|
|
1076
|
+
assert(/const hasValue =/.test(act), 'empty before/after is still printed, which reads as "nothing changed"');
|
|
1077
|
+
return 'incapability is judged from availablePatterns, not from an empty Value';
|
|
1078
|
+
});
|
|
1079
|
+
|
|
1080
|
+
gate('computer_act describe rides the ref cache instead of re-reading the element', () => {
|
|
1081
|
+
// describe+act is two round-trips by design (the policy decision stays in Node), but the
|
|
1082
|
+
// describe leg used to pay a full COM property re-read inside the worker on top of
|
|
1083
|
+
// Resolve-Ref. New-Ref already caches every descriptor field at snapshot time, and the batch
|
|
1084
|
+
// path has always judged policy on that cached descriptor (Cmd-PrepareBatch →
|
|
1085
|
+
// DescriptorOf $re $false) — so the single-call describe must do the same. The live re-read is
|
|
1086
|
+
// allowed ONLY in the cache-miss branch: a rebound ref's cached fields belong to the OLD
|
|
1087
|
+
// element (Resolve-Ref swaps the element without refreshing them).
|
|
1088
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1089
|
+
const block = ps.match(/function Cmd-Describe[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1090
|
+
assert(block !== '', 'Cmd-Describe is missing');
|
|
1091
|
+
assert((block.match(/DescriptorOf \$re \$true/g) ?? []).length === 1,
|
|
1092
|
+
'the live COM re-read appears more than once in Cmd-Describe: a cached hit must not re-read the element');
|
|
1093
|
+
const rebind = block.indexOf('if ($re.rebound)');
|
|
1094
|
+
const live = block.indexOf('DescriptorOf $re $true');
|
|
1095
|
+
assert(rebind !== -1, 'Cmd-Describe no longer branches on the rebind flag: the cache-miss fallback is gone');
|
|
1096
|
+
assert(live > rebind, 'the live COM re-read moved out of the cache-miss branch');
|
|
1097
|
+
assert(/if \(\$re\.rebound\) \{[\s\S]{0,400}DescriptorOf \$re \$true/.test(block),
|
|
1098
|
+
'the live COM re-read is not gated behind the rebind branch');
|
|
1099
|
+
assert((block.match(/DescriptorOf \$re \$false/g) ?? []).length === 1,
|
|
1100
|
+
'the cache-hit path no longer returns the ref-record descriptor');
|
|
1101
|
+
assert(!/\.Current/.test(block), 'Cmd-Describe reads .Current directly: the cache-hit path touches the element again');
|
|
1102
|
+
return 'cache hit returns the ref-record descriptor; only the rebound branch re-reads Current';
|
|
1103
|
+
});
|
|
1104
|
+
|
|
1105
|
+
gate('a duplicate-named element can be addressed individually', () => {
|
|
1106
|
+
// This window has two Button "新建会话" (top brand row and the sidebar's new-session button) and
|
|
1107
|
+
// used to be reachable only through FindFirst, i.e. always the first one. A model asking for the
|
|
1108
|
+
// second got the first and reported "点不准" while its coordinates were exact.
|
|
1109
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1110
|
+
const find = ps.match(/function Find-ByDescriptor[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1111
|
+
assert(find !== '', 'Find-ByDescriptor is missing');
|
|
1112
|
+
assert(/nearPoint/.test(ps), 'descriptor resolution lost nearPoint: the caller can no longer say "the one near here"');
|
|
1113
|
+
assert(/hits\[\$nth - 1\]/.test(ps) && /\$nth/.test(find), 'descriptor resolution lost nth: duplicates collapse back to the first match');
|
|
1114
|
+
// 消歧现在由 ladder 里统一的候选筛选 + 选择器完成,不再有 disambiguate 开关;钉住语义而非变量名。
|
|
1115
|
+
assert(/selectedBy/.test(ps) && /matchedBy/.test(ps), 'descriptor resolution stopped reporting why an element was chosen');
|
|
1116
|
+
assert(/Test-ExplicitFalse/.test(find), 'the strict name match no longer defaults to exact: fuzzy matching may have become the default');
|
|
1117
|
+
const ft = ps.match(/function Cmd-FindText[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1118
|
+
assert(ft !== '', 'Cmd-FindText is missing');
|
|
1119
|
+
assert(/\$seen/.test(ft), 'find_text stopped counting duplicates');
|
|
1120
|
+
// Whitespace-tolerant: the hit must still publish its duplicate index AND carry it in the
|
|
1121
|
+
// descriptor the caller replays, however the two lines happen to be formatted.
|
|
1122
|
+
assert(/nth\s*=\s*\$nth/.test(ft), 'find_text no longer publishes nth on each hit');
|
|
1123
|
+
assert(/\$byDesc\['nth'\]\s*=\s*\$nth/.test(ft), 'the by-descriptor find_text returns no longer carries nth, so duplicates collapse on replay');
|
|
1124
|
+
return 'nth + nearPoint make duplicates individually addressable';
|
|
1125
|
+
});
|
|
1126
|
+
gate('locator degradation is reported instead of silently guessed', () => {
|
|
1127
|
+
// A descriptor that only matched after relaxing something must SAY so, otherwise a replayed
|
|
1128
|
+
// recipe looks exact while it actually drifted. The strict rung must also remain the default.
|
|
1129
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1130
|
+
for (const rung of ['normalizedName', 'prefix']) {
|
|
1131
|
+
assert(ps.includes(rung), `the ${rung} rung of the locator ladder is gone`);
|
|
1132
|
+
}
|
|
1133
|
+
assert(/matchedBy/.test(ps) && /degraded/.test(ps) && /score/.test(ps), 'the locator stopped reporting matchedBy/degraded/score');
|
|
1134
|
+
assert(/descriptor_match\s*=\s*'Cmd-DescriptorMatch'/.test(ps), 'descriptor_match is not registered in the handler table');
|
|
1135
|
+
assert(/descriptor_match\s*=\s*\d+/.test(ps), 'descriptor_match has no request budget');
|
|
1136
|
+
assert(/read-only|Read-only|只读/i.test(ps.match(/function Cmd-DescriptorMatch[\s\S]*?\n\}/)?.[0] ?? ''), 'descriptor_match no longer documents itself as read-only');
|
|
1137
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1138
|
+
assert(!/worker\.call\('descriptor_match'/.test(tools) || /describeLocator/.test(tools), 'tools.js needs to surface locator confidence when it uses it');
|
|
1139
|
+
return 'ladder rungs + matchedBy/degraded/score + read-only probe';
|
|
1140
|
+
});
|
|
1141
|
+
|
|
1142
|
+
gate('the plan is scored on accuracy, not just speed', () => {
|
|
1143
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1144
|
+
assert(/可作=/.test(tools), 'find_text no longer states which actions a hit supports');
|
|
1145
|
+
assert(/容器/.test(tools), 'container hits are no longer labelled');
|
|
1146
|
+
assert(/同名/.test(tools), 'same-name collisions are no longer called out');
|
|
1147
|
+
return 'actionability, container and same-name hints all present';
|
|
1148
|
+
});
|
|
1149
|
+
|
|
1150
|
+
gate('prepare_batch refuses a bad verb instead of deferring it to commit', () => {
|
|
1151
|
+
// The dry run exists to answer "would this batch work?". It used to copy the action through
|
|
1152
|
+
// untouched, so a typo burned a revision and a second round-trip before commit refused it.
|
|
1153
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1154
|
+
const prep = ps.match(/function Cmd-PrepareBatch[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1155
|
+
assert(prep !== '', 'Cmd-PrepareBatch is missing');
|
|
1156
|
+
assert(/actionNames\.ContainsKey\(\$actName\)/.test(prep), 'prepare_batch no longer validates the verb');
|
|
1157
|
+
assert(/ToLowerInvariant\(\)/.test(prep), 'prepare_batch no longer normalises case: "Invoke" would pass prepare and fail commit');
|
|
1158
|
+
const commit = ps.match(/function Cmd-CommitBatch[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1159
|
+
assert(/ToLowerInvariant\(\)/.test(commit), 'commit_batch does not normalise the verb the same way prepare does');
|
|
1160
|
+
return 'the dry run validates the verb and both phases agree on case';
|
|
1161
|
+
});
|
|
1162
|
+
|
|
1163
|
+
gate('the wait tool asks for a target instead of timing out', () => {
|
|
1164
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1165
|
+
const wait = tools.match(/name: 'computer_wait'[\s\S]*?\n \}\)\)\);/)?.[0] ?? '';
|
|
1166
|
+
assert(wait !== '', 'computer_wait is missing');
|
|
1167
|
+
assert(/needsTarget/.test(wait), 'computer_wait no longer checks that a measuring condition names an element');
|
|
1168
|
+
assert(/需要指定 ref 或 by/.test(wait), 'computer_wait no longer explains the missing target');
|
|
1169
|
+
assert(/observed/.test(wait), 'computer_wait drops the observed value on timeout: the model cannot tell why it failed');
|
|
1170
|
+
return 'a target-less condition is rejected up front and timeouts carry their observation';
|
|
1171
|
+
});
|
|
1172
|
+
|
|
1173
|
+
gate('the whole desktop can be captured, not just one window', () => {
|
|
1174
|
+
// computer_capture could only ever see a single window, so anything outside it — a second app,
|
|
1175
|
+
// another process's dialog, a multi-monitor desktop — was simply absent from the model's view
|
|
1176
|
+
// ("设备屏幕截不全"). scope="screen" now captures the composed desktop.
|
|
1177
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1178
|
+
assert(/public static CapResult CaptureScreen\(/.test(ps), 'the worker has no whole-desktop capture');
|
|
1179
|
+
assert(/capture_screen\s*=\s*'Cmd-CaptureScreen'/.test(ps), 'capture_screen is not dispatched');
|
|
1180
|
+
const fn = ps.match(/function Cmd-CaptureScreen[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1181
|
+
assert(fn !== '', 'Cmd-CaptureScreen is missing');
|
|
1182
|
+
assert(/Get-VirtScreen/.test(fn), 'the screen capture does not read the measured virtual screen');
|
|
1183
|
+
assert(/coordinateMap/.test(fn), 'the screen capture publishes no image->screen mapping');
|
|
1184
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1185
|
+
assert(/scope === 'screen'/.test(tools), 'computer_capture has no screen scope');
|
|
1186
|
+
assert(/capture_screen/.test(tools), 'computer_capture never calls capture_screen');
|
|
1187
|
+
return 'scope="screen" captures every monitor through the measured virtual screen';
|
|
1188
|
+
});
|
|
1189
|
+
|
|
1190
|
+
gate('no screen dimension is ever hardcoded', () => {
|
|
1191
|
+
// A guessed 1920x1080 makes every coordinate normalisation wrong on any other display, and it
|
|
1192
|
+
// fails silently: SendInput just lands somewhere else. Dimensions must be measured.
|
|
1193
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1194
|
+
const virt = ps.match(/function Get-VirtScreen[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1195
|
+
assert(virt !== '', 'Get-VirtScreen is missing');
|
|
1196
|
+
assert(!/\$\w+\s*=\s*(1920|2560|3840|1366|1280)\b/.test(virt), 'Get-VirtScreen falls back to a hardcoded resolution again');
|
|
1197
|
+
assert(/GetSystemMetrics\(78\)/.test(virt), 'Get-VirtScreen no longer measures the virtual screen width');
|
|
1198
|
+
assert(/PrimaryScreen\.Bounds|screen_unknown/.test(virt), 'Get-VirtScreen has no measured last resort before failing');
|
|
1199
|
+
// Whole-desktop capture must derive its size the same way.
|
|
1200
|
+
const ps2 = ps.match(/public static CapResult CaptureScreen[\s\S]*?\n \}/)?.[0] ?? '';
|
|
1201
|
+
assert(/GetSystemMetrics\(78\)/.test(ps2), 'CaptureScreen does not measure the virtual screen width');
|
|
1202
|
+
assert(/GetSystemMetrics\(76\)/.test(ps2), 'CaptureScreen assumes a 0,0 origin instead of measuring it');
|
|
1203
|
+
// Cmd-Ping used to re-derive the station size from PhysWidth+PrimaryScreen.Bounds — a second
|
|
1204
|
+
// measurement that silently drifted from Get-VirtScreen (the pointer channel's answer). Every
|
|
1205
|
+
// reporter must read the ONE authoritative measurement.
|
|
1206
|
+
const ping = ps.match(/function Cmd-Ping\(\$A\)[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1207
|
+
assert(ping !== '', 'Cmd-Ping is missing');
|
|
1208
|
+
assert(!/PhysWidth|PhysHeight/.test(ping), 'Cmd-Ping still measures the station size itself instead of reading Get-VirtScreen');
|
|
1209
|
+
assert(/Get-VirtScreen/.test(ping), 'Cmd-Ping does not read the authoritative Get-VirtScreen measurement');
|
|
1210
|
+
// The dead "logical" pair (a WinForms bounds read with no consumer anywhere in src/ or web/)
|
|
1211
|
+
// must not come back inside Cmd-Ping. The check runs on the function body with line comments
|
|
1212
|
+
// stripped: the function's own history note may mention "logical", only CODE may not.
|
|
1213
|
+
const pingCode = ping.split('\n').filter((l) => !/^\s*#/.test(l)).join('\n');
|
|
1214
|
+
assert(!/\blogical\b/.test(pingCode), 'Cmd-Ping still reports the dead "logical" field no consumer reads');
|
|
1215
|
+
// PrimaryScreen.Bounds may appear ONLY inside Get-VirtScreen's fallback chain: any other call
|
|
1216
|
+
// site is a second measurement drifting from the authoritative one. Count non-comment lines
|
|
1217
|
+
// and require every .Bounds occurrence to live inside the Get-VirtScreen block.
|
|
1218
|
+
const codeOnly = ps.split('\n').filter((l) => !/^\s*#/.test(l)).join('\n');
|
|
1219
|
+
const virtBounds = (virt.match(/\.Bounds/g) ?? []).length;
|
|
1220
|
+
const allBounds = (codeOnly.match(/\.Bounds/g) ?? []).length;
|
|
1221
|
+
assert(allBounds > 0 && allBounds === virtBounds, `PrimaryScreen.Bounds call site(s) outside Get-VirtScreen's fallback chain: ${allBounds - virtBounds}`);
|
|
1222
|
+
return 'virtual screen is measured every time; no fallback resolution is assumed';
|
|
1223
|
+
});
|
|
1224
|
+
|
|
1225
|
+
gate('a window capture is native 1:1 unless the caller asks for less', () => {
|
|
1226
|
+
// A silently downscaled capture is the worst of both worlds: the model loses small text and the
|
|
1227
|
+
// coordinateMap grows a scale factor. Default to the window's real pixels; opt in to downscaling
|
|
1228
|
+
// explicitly. (1400 as a default made a 1941-wide window come back as 1600x1024, which reads as
|
|
1229
|
+
// "the screen was cut off".)
|
|
1230
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1231
|
+
const cap = ps.match(/function Cmd-Capture\(\$A\)[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1232
|
+
assert(cap !== '', 'Cmd-Capture is missing');
|
|
1233
|
+
assert(/IntArg \$A 'maxDim' 0/.test(cap), 'the window capture defaults to a downscale again: native 1:1 must be the default');
|
|
1234
|
+
assert(!/IntArg \$A 'maxDim' 1400/.test(cap), 'the old 1400 default is back');
|
|
1235
|
+
// The desktop capture follows the same rule: native unless the caller opts into downscaling.
|
|
1236
|
+
const screen = ps.match(/function Cmd-CaptureScreen\(\$A\)[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1237
|
+
assert(screen !== '', 'Cmd-CaptureScreen is missing');
|
|
1238
|
+
assert(/IntArg \$A 'maxDim' 0/.test(screen), 'the desktop capture silently downscales by default again');
|
|
1239
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1240
|
+
assert(!/\? capArgs\.maxDim : 1600/.test(tools), 'the screen scope still forces a 1600 default on the caller');
|
|
1241
|
+
return 'both scopes default to native 1:1; downscaling is opt-in';
|
|
1242
|
+
});
|
|
1243
|
+
|
|
1244
|
+
gate('find_text issues refs so computer_act can be driven from a search', () => {
|
|
1245
|
+
// Live run: searching "设置" returned centres and by-descriptors but no ref, and computer_act
|
|
1246
|
+
// takes a ref and nothing else — so every search result had to fall back to a physical
|
|
1247
|
+
// computer_click, moving the real cursor for what should have been a background action.
|
|
1248
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1249
|
+
const ft = ps.match(/function Cmd-FindText[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1250
|
+
assert(ft !== '', 'Cmd-FindText is missing');
|
|
1251
|
+
assert(/New-Ref \$entry \$c \$cp \$node/.test(ft), 'find_text no longer issues a ref for each hit');
|
|
1252
|
+
assert(/ref\s*=\s*\$\(if \(\$null -ne \$refRec\)/.test(ft), 'find_text does not publish the issued ref on the item');
|
|
1253
|
+
assert(/patterns\s*=\s*@\(\$pats\)/.test(ft), 'find_text no longer reports patterns, so the ranking cannot tell commands from text');
|
|
1254
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1255
|
+
assert(/refStr/.test(tools), 'the rendered find_text line does not show the ref');
|
|
1256
|
+
return 'every hit carries a usable ref';
|
|
1257
|
+
});
|
|
1258
|
+
|
|
1259
|
+
gate('find_text ranks by what can actually be clicked', () => {
|
|
1260
|
+
// Live run failures this pins:
|
|
1261
|
+
// - the chat transcript (Text nodes, all offscreen) outranked the real MenuItem "设置";
|
|
1262
|
+
// - sidebar session titles (TreeItem) outranked the real Button "花费".
|
|
1263
|
+
// The tiers live in the module-level rankMatch() now, shared with computer_parse's operable
|
|
1264
|
+
// list — two copies had already started to drift (F-07/F-42).
|
|
1265
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1266
|
+
const block = tools.match(/function rankMatch\(m\) \{[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1267
|
+
assert(block !== '', 'the shared rankMatch ranking block is missing');
|
|
1268
|
+
assert(/isOffscreen === true\) return 5/.test(block), 'offscreen hits are no longer ranked last');
|
|
1269
|
+
assert(/PASS_THROUGH\.has/.test(block), 'container hits no longer rank last');
|
|
1270
|
+
assert(/NAVIGATION\.has/.test(block), 'TreeItem/ListItem navigation rows are no longer demoted');
|
|
1271
|
+
assert(/COMMANDS\.has/.test(block), 'real command controls no longer rank first');
|
|
1272
|
+
// find_text and computer_parse must both sort through the SAME ranking.
|
|
1273
|
+
const find = tools.match(/name: 'computer_find_text'[\s\S]*?\n \}\)\)\);/)?.[0] ?? '';
|
|
1274
|
+
const parse = tools.match(/name: 'computer_parse'[\s\S]*?\n \}\)\)\);/)?.[0] ?? '';
|
|
1275
|
+
assert(/rankMatch\(/.test(find), 'find_text stopped sorting through the shared rankMatch');
|
|
1276
|
+
assert(/rankMatch\(/.test(parse), 'computer_parse stopped sorting through the shared rankMatch');
|
|
1277
|
+
assert(!/patterns\.length > 0/.test(parse), 'computer_parse lists every pattern-bearing node as operable again: Text paragraphs and containers compete with buttons, and auto mode pixel-clicks them');
|
|
1278
|
+
// Text must not count as an action: it carries the Text pattern.
|
|
1279
|
+
const verbs = tools.match(/const ACT_VERBS = new Set\(\[([^\]]*)\]\)/)?.[1] ?? '';
|
|
1280
|
+
assert(verbs !== '', 'ACT_VERBS is missing');
|
|
1281
|
+
assert(!/['"]Text['"]/.test(verbs), 'Text is back in ACT_VERBS: every paragraph competes with the real control');
|
|
1282
|
+
// And navigation types must not be commands.
|
|
1283
|
+
assert(!/NAVIGATION = new Set\(\[[^\]]*Button/.test(tools), 'navigation and command sets overlap');
|
|
1284
|
+
// One definition of "container whose click only focuses the window" (F-42): find_text references
|
|
1285
|
+
// the module-level set instead of keeping a second literal.
|
|
1286
|
+
assert(/const CONTAINERS = PASS_THROUGH/.test(find), 'find_text keeps its own container set literal again: two definitions can drift');
|
|
1287
|
+
return 'offscreen < navigation < commands ordering pinned and shared by find_text and parse';
|
|
1288
|
+
});
|
|
1289
|
+
|
|
1290
|
+
gate('the capability table only names patterns the worker can actually obtain', () => {
|
|
1291
|
+
// NEEDED used to list LegacyIAccessible for invoke/set_value, but the managed UIAutomationClient
|
|
1292
|
+
// has no such pattern type: the worker's GetPattern returned $null for it, its three
|
|
1293
|
+
// LegacyIAccessible fallbacks were dead branches, and describe() reported the name via
|
|
1294
|
+
// availablePatterns — so invoke/set_value on a LegacyIAccessible-only element read as "capable"
|
|
1295
|
+
// while nothing could ever run. This gate compares the two tables so they cannot diverge again.
|
|
1296
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1297
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1298
|
+
const needed = tools.match(/const NEEDED = \{([\s\S]*?)\n \};/)?.[1] ?? '';
|
|
1299
|
+
assert(needed !== '', 'the NEEDED capability table is missing');
|
|
1300
|
+
const used = [...new Set([...needed.matchAll(/['"]([A-Za-z]+)['"]/g)].map((m) => m[1]))];
|
|
1301
|
+
assert(used.length > 0, 'the NEEDED table names no patterns');
|
|
1302
|
+
const types = ps.match(/\$patternTypes = @\{([\s\S]*?)\n\}/)?.[1] ?? '';
|
|
1303
|
+
assert(types !== '', 'the worker $patternTypes table is missing');
|
|
1304
|
+
const known = [...new Set([...types.matchAll(/^\s*(\w+)\s+=/gm)].map((m) => m[1]))];
|
|
1305
|
+
const unknown = used.filter((p) => !known.includes(p));
|
|
1306
|
+
assert(unknown.length === 0, `NEEDED names patterns the worker's GetPattern can never resolve: ${unknown.join(', ')}`);
|
|
1307
|
+
// focus needs no pattern at all (plain SetFocus on the element); listing patterns for it made
|
|
1308
|
+
// every focus call read as incapable.
|
|
1309
|
+
assert(!/focus:/.test(needed), 'focus is back in NEEDED: it requires no pattern and would always read as incapable');
|
|
1310
|
+
// And the worker must not keep an unreachable LegacyIAccessible fallback either.
|
|
1311
|
+
assert(!/GetPattern \$el 'LegacyIAccessible'/.test(ps), 'the worker still calls GetPattern for LegacyIAccessible: the managed client has no such pattern type, so every such branch is dead');
|
|
1312
|
+
return `${used.length} patterns all obtainable; focus pattern-free; no dead LegacyIAccessible branches`;
|
|
1313
|
+
});
|
|
1314
|
+
|
|
1315
|
+
gate('keyboard combos go through the same policy gate as elements', () => {
|
|
1316
|
+
// The refusal used to be hand-written inside computer_key (README: guard.js is the only policy
|
|
1317
|
+
// decision point), with its own refusal wording maintained separately from CATEGORIES.
|
|
1318
|
+
const guard = readFileSync(join(ROOT, 'src', 'guard.js'), 'utf8');
|
|
1319
|
+
assert(/export function classifyKeys\(/.test(guard), 'guard.js does not export classifyKeys');
|
|
1320
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1321
|
+
const key = tools.match(/name: 'computer_key'([\s\S]*?)\n \}\)\)\);/)?.[0] ?? '';
|
|
1322
|
+
assert(key !== '', 'computer_key is missing');
|
|
1323
|
+
assert(/classifyKeys\(/.test(key), 'computer_key does not route through guard.classifyKeys');
|
|
1324
|
+
assert(!/alt\+f4/.test(key), 'computer_key still hand-matches alt+f4: the hotkey policy moved into guard.js');
|
|
1325
|
+
// Behaviour pins: the two dangerous combos still deny, ordinary work still passes.
|
|
1326
|
+
assert(classifyKeys('alt+f4').verdict === 'deny' && classifyKeys('alt+f4').category === 'exit', 'alt+f4 no longer denies as exit');
|
|
1327
|
+
assert(classifyKeys('win+l').verdict === 'deny' && classifyKeys('win+l').category === 'shutdown', 'win+l no longer denies as shutdown');
|
|
1328
|
+
for (const ok of ['ctrl+c', 'ctrl+shift+s', 'alt+tab', 'enter', 'f5']) {
|
|
1329
|
+
assert(classifyKeys(ok).verdict === 'allow', `classifyKeys now blocks ordinary combo ${ok}`);
|
|
1330
|
+
}
|
|
1331
|
+
return 'classifyKeys in guard.js; alt+f4=exit, win+l=shutdown, ordinary combos allowed';
|
|
1332
|
+
});
|
|
1333
|
+
|
|
1334
|
+
gate('a native-scale capture says its coordinates are usable', () => {
|
|
1335
|
+
// scale=1 means image pixels ARE screen pixels; telling the model "已缩放、不能直接当屏幕坐标点"
|
|
1336
|
+
// there is false and makes it do arithmetic it does not need.
|
|
1337
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1338
|
+
assert(/const native = result\.scaleX === 1/.test(tools), 'the capture no longer detects a 1:1 image');
|
|
1339
|
+
assert(/可以直接点击图像中的坐标/.test(tools), 'the native capture no longer tells the model coordinates are direct');
|
|
1340
|
+
assert(!/已缩放到 maxDim,不能直接当屏幕坐标点/.test(tools), 'the unconditional "cannot be used as screen coordinates" text is back');
|
|
1341
|
+
return 'the mapping note matches the actual scale';
|
|
1342
|
+
});
|
|
1343
|
+
|
|
1344
|
+
gate('desktop capture hides the indicator while sampling', () => {
|
|
1345
|
+
const activity = readFileSync(join(ROOT, 'src', 'activity-window.js'), 'utf8');
|
|
1346
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1347
|
+
assert(/async withoutIndicator\(fn\)/.test(activity), 'ActivityWindow has no capture suspension');
|
|
1348
|
+
assert(/phase: 'hidden'/.test(activity), 'capture suspension does not hide the indicator');
|
|
1349
|
+
assert(/phase: this\.phase === 'stopped' \? 'stopped' : 'acting'/.test(activity), 'capture suspension does not restore the run phase');
|
|
1350
|
+
assert(/scope === 'screen' && activity\?\.withoutIndicator/.test(tools),
|
|
1351
|
+
'computer_capture does not suspend the indicator for desktop captures');
|
|
1352
|
+
// A window capture is PrintWindow(hwnd) and never contains the overlay; suspending there would
|
|
1353
|
+
// only add a flicker the person can see.
|
|
1354
|
+
assert(!/const result = activity\?\.withoutIndicator \? await activity\.withoutIndicator/.test(tools),
|
|
1355
|
+
'the suspension is applied to window captures too, which just flickers the overlay for nothing');
|
|
1356
|
+
return 'indicator hidden for desktop sampling only, then restored';
|
|
1357
|
+
});
|
|
1358
|
+
|
|
1359
|
+
gate('screen capture never hardcodes display geometry', () => {
|
|
1360
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1361
|
+
const cap = ps.match(/function Cmd-CaptureScreen[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1362
|
+
assert(/Get-VirtScreen/.test(cap), 'screen capture does not use measured virtual-screen geometry');
|
|
1363
|
+
assert(!/\b(?:2560|1920|1080)\b/.test(cap), 'screen capture contains a display-size constant');
|
|
1364
|
+
return 'screen capture uses the measured virtual-screen rectangle';
|
|
1365
|
+
});
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
gate('the snapshot cache request carries pattern availability and runtime id, with a one-shot path and a walker fallback', () => {
|
|
1369
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1370
|
+
// P-01 ①: one bulk cache must buy the pattern-availability bits AND the ref identity, so the
|
|
1371
|
+
// per-node GetSupportedPatterns / GetRuntimeId round-trips stay gone.
|
|
1372
|
+
assert(/'IsInvokePatternAvailableProperty'/.test(ps), 'the snapshot cache request lost IsInvokePatternAvailableProperty');
|
|
1373
|
+
assert(/'RuntimeIdProperty'/.test(ps), 'the snapshot cache request lost RuntimeIdProperty');
|
|
1374
|
+
// ② one-shot subtree path (GetUpdatedCache -> CachedChildren) and the walker fallback
|
|
1375
|
+
// (GetFirstChild request overload) must BOTH exist, plus the fallback catch branch.
|
|
1376
|
+
const snap = ps.match(/function Build-Snapshot\(\$entry, \$A\) \{[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1377
|
+
assert(snap !== '', 'Build-Snapshot is missing');
|
|
1378
|
+
assert(/GetUpdatedCache\(/.test(snap), 'Build-Snapshot lost the one-shot GetUpdatedCache subtree path');
|
|
1379
|
+
assert(/CachedChildren/.test(snap), 'Build-Snapshot no longer walks CachedChildren');
|
|
1380
|
+
assert(/GetFirstChild\(/.test(snap), 'Build-Snapshot lost the walker fallback (GetFirstChild request overload)');
|
|
1381
|
+
assert(/catch/.test(snap), 'Build-Snapshot lost its fallback catch branch');
|
|
1382
|
+
// ③ cached availability first, live fallback kept; snapshot value reads go through the cache,
|
|
1383
|
+
// the act/verify path stays live.
|
|
1384
|
+
assert(/function Cached-PatternsOf/.test(ps), 'the cached pattern-availability helper is missing');
|
|
1385
|
+
assert(/GetSupportedPatterns/.test(ps), 'the live GetSupportedPatterns fallback is gone');
|
|
1386
|
+
assert(/function Read-Value\(\$el, \$patterns, \$refRec, \$useCached\)/.test(ps), 'Read-Value lost its cached-snapshot flag');
|
|
1387
|
+
assert(/function Cached-ValueOf/.test(ps), 'the cached value reader is missing');
|
|
1388
|
+
return 'cache request carries IsInvoke+RuntimeId; one-shot + walker fallback + catch + cached value reader all present';
|
|
1389
|
+
});
|
|
1390
|
+
|
|
1391
|
+
gate('find_text reads the cache it built and keeps the live fallback', () => {
|
|
1392
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1393
|
+
const ft = ps.match(/function Cmd-FindText[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1394
|
+
assert(ft !== '', 'Cmd-FindText is missing');
|
|
1395
|
+
// P-02: the scan enumerates inside an Activate()d private request and reads $c.Cached; the
|
|
1396
|
+
// historical live path ($c.Current after a plain FindAll) must stay as the fallback — deleting
|
|
1397
|
+
// it would turn one provider quirk into a dead tool.
|
|
1398
|
+
assert(/Activate\(\)/.test(ft), 'find_text does not activate its own cache request');
|
|
1399
|
+
assert(/\$c\.Cached/.test(ft), 'find_text lost the cached read path');
|
|
1400
|
+
assert(/\$c\.Current/.test(ft), 'find_text lost the live Current fallback path');
|
|
1401
|
+
assert(/\$usedCached/.test(ft), 'find_text lost the cached/live switch');
|
|
1402
|
+
assert(/function Find-CacheRequest/.test(ps), 'find_text has no private request builder');
|
|
1403
|
+
// Refs minted from cached elements stay live elements (AutomationElementMode=Full) — the
|
|
1404
|
+
// ref-issuance contract must not regress while the scan gets faster.
|
|
1405
|
+
assert(/New-Ref \$entry \$c \$cp \$node/.test(ft), 'find_text no longer issues a ref for each hit');
|
|
1406
|
+
return 'cached scan + live fallback + private request object + ref issuance all pinned';
|
|
1407
|
+
});
|
|
1408
|
+
|
|
1409
|
+
gate('observations carry position metadata and the renderer truncates it', () => {
|
|
1410
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1411
|
+
// P-04 worker half: the helper reads foreground + UIA focus and is advisory (try/catch-guarded).
|
|
1412
|
+
assert(/function Window-ObservationHeader/.test(ps), 'the worker has no observation header helper');
|
|
1413
|
+
assert(/FocusedElement/.test(ps), 'the observation header does not read the UIA focus');
|
|
1414
|
+
assert(/focusInWindow/.test(ps), 'the observation header does not compare the focus pid with the window');
|
|
1415
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1416
|
+
const line = tools.match(/function observationLine\([\s\S]*?\n\}/)?.[0] ?? '';
|
|
1417
|
+
assert(line !== '', 'tools.js has no observationLine renderer');
|
|
1418
|
+
assert(/foreground/.test(line) && /focusInWindow/.test(line), 'observationLine ignores the focus/foreground fields');
|
|
1419
|
+
assert(/str\(/.test(line), 'observationLine does not truncate through str(): a long title would blow the line');
|
|
1420
|
+
assert(/observationLine\(result\)/.test(tools), 'the snapshot head never renders the observation line');
|
|
1421
|
+
return 'worker probes foreground+focus; renderer truncates through str() and renders on the head';
|
|
1422
|
+
});
|
|
1423
|
+
|
|
1424
|
+
gate('computer_type offers the clipboard channel', () => {
|
|
1425
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1426
|
+
// P-05 ①: the tool advertises the via enum, and the description must warn about the one
|
|
1427
|
+
// destructive side effect (the clipboard is overwritten and not restored).
|
|
1428
|
+
assert(/via: \{ type: 'string', enum: \['keyboard', 'clipboard'\]/.test(tools), 'computer_type has no via keyboard|clipboard parameter');
|
|
1429
|
+
assert(/OVERWRITES the user/.test(tools) || /覆盖.*剪贴板/.test(tools), 'the via description does not warn that the clipboard is overwritten');
|
|
1430
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1431
|
+
const tt = ps.match(/function Cmd-TypeText[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1432
|
+
assert(tt !== '', 'Cmd-TypeText is missing');
|
|
1433
|
+
assert(/Set-Clipboard/.test(tt), 'the worker clipboard path does not use Set-Clipboard');
|
|
1434
|
+
assert(/'keyboard', 'clipboard'/.test(tt), 'Cmd-TypeText does not branch on via');
|
|
1435
|
+
assert(/bad_arg/.test(tt), 'Cmd-TypeText does not refuse an unknown via');
|
|
1436
|
+
assert(/KeyDownVk\(0x11\)/.test(tt) && /KeyDownVk\(0x56\)/.test(tt), 'the clipboard path does not paste with ctrl+v through the Cmd-Key event pipeline');
|
|
1437
|
+
return 'via enum on the tool with overwrite warning; Set-Clipboard + ctrl+v + bad_arg refusal in the worker';
|
|
1438
|
+
});
|
|
1439
|
+
|
|
1440
|
+
gate('commit_batch diffs top-level windows and the renderer warns without noise', () => {
|
|
1441
|
+
const ps = readFileSync(worker, 'utf8');
|
|
1442
|
+
const cb = ps.match(/function Cmd-CommitBatch[\s\S]*?\n\}/)?.[0] ?? '';
|
|
1443
|
+
assert(cb !== '', 'Cmd-CommitBatch is missing');
|
|
1444
|
+
// P-09: one read-only RootWindows sweep before AND after phase 2, diffed by hwnd.
|
|
1445
|
+
assert((cb.match(/RootWindows/g) ?? []).length >= 2, 'commit_batch no longer enumerates root windows around phase 2');
|
|
1446
|
+
assert(/newWindows/.test(cb), 'commit_batch does not report newWindows');
|
|
1447
|
+
assert(/indicatorPid/.test(cb), 'commit_batch cannot exclude the indicator overlay process from the diff');
|
|
1448
|
+
const tools = readFileSync(join(ROOT, 'src', 'tools.js'), 'utf8');
|
|
1449
|
+
const note = tools.match(/function newWindowNote\([\s\S]*?\n\}/)?.[0] ?? '';
|
|
1450
|
+
assert(note !== '', 'tools.js has no newWindowNote renderer');
|
|
1451
|
+
assert(/dsh-yuping-indicator/.test(note), 'newWindowNote does not exclude the indicator overlay window');
|
|
1452
|
+
assert(/indicatorPid/.test(note), 'newWindowNote does not filter the indicator pid');
|
|
1453
|
+
assert(/newWindowNote\(committed\.newWindows/.test(tools), 'computer_run never renders the window diff');
|
|
1454
|
+
return 'hwnd diff around phase 2 with indicator-pid exclusion; renderer filters again and renders nothing when clean';
|
|
1455
|
+
});
|
|
1456
|
+
|
|
1457
|
+
await Promise.all(inflight); // async gates must settle before the summary counts them
|
|
1458
|
+
console.log(`\n${results.length} gates: ${results.filter((r) => r.verdict === 'PASS').length} PASS / ${results.filter((r) => r.verdict === 'SKIP').length} SKIP / ${failed} FAIL`);
|
|
1459
|
+
process.exit(failed > 0 ? 1 : 0);
|