dsh-native-uia 0.2.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +81 -398
  2. package/client/client.js +236 -48
  3. package/cordis.patch.yml +7 -8
  4. package/locale/en.json +2 -2
  5. package/locale/zh.json +2 -2
  6. package/package.json +8 -17
  7. package/scripts/check-lease.mjs +1 -1
  8. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  9. package/scripts/lib/load-tools-source.mjs +17 -16
  10. package/scripts/lib/sources.mjs +62 -0
  11. package/scripts/load-tools.mjs +74 -0
  12. package/scripts/measure-parse.mjs +2 -2
  13. package/scripts/regression-tools.mjs +155 -6
  14. package/scripts/regression-worker.ps1 +29 -0
  15. package/scripts/verify-live-style.mjs +46 -0
  16. package/scripts/verify-live.mjs +12 -18
  17. package/scripts/verify.mjs +953 -192
  18. package/src/activity-window.js +71 -7
  19. package/src/dashboard.js +27 -69
  20. package/src/guard.js +39 -10
  21. package/src/index.js +187 -77
  22. package/src/notes.js +83 -0
  23. package/src/state.js +97 -10
  24. package/src/themes.js +66 -0
  25. package/src/tools/defs/act.js +671 -0
  26. package/src/tools/defs/lifecycle.js +205 -0
  27. package/src/tools/defs/observe.js +325 -0
  28. package/src/tools/defs/pointer.js +328 -0
  29. package/src/tools/format.js +338 -0
  30. package/src/tools/index.js +125 -0
  31. package/src/tools/ocr.js +91 -0
  32. package/src/tools/recipes.js +49 -0
  33. package/src/tools/runtime.js +42 -0
  34. package/src/worker-client.js +32 -10
  35. package/worker/assets/dsh-whale.path +1 -0
  36. package/worker/indicator-server.ps1 +1107 -72
  37. package/worker/lib/01-core.ps1 +64 -0
  38. package/worker/lib/02-uia.ps1 +224 -0
  39. package/worker/lib/03-window.ps1 +194 -0
  40. package/worker/lib/04-match.ps1 +435 -0
  41. package/worker/lib/05-value.ps1 +254 -0
  42. package/worker/lib/06-snapshot.ps1 +412 -0
  43. package/worker/lib/07-action.ps1 +329 -0
  44. package/worker/lib/08-command.ps1 +1495 -0
  45. package/worker/lib/09-pointer.ps1 +840 -0
  46. package/worker/lib/10-dispatch.ps1 +132 -0
  47. package/worker/ps-stdio.ps1 +7 -2
  48. package/worker/uia-worker.ps1 +599 -4220
  49. package/locale/desktop/en.json +0 -6
  50. package/locale/desktop/zh.json +0 -6
  51. package/scripts/regression-halt-latch.mjs +0 -100
  52. package/src/native-uia-remote.js +0 -80
  53. package/src/panel-face.js +0 -14
  54. package/src/tools.js +0 -1482
  55. package/web/control.html +0 -1413
@@ -9,10 +9,19 @@ const root = dirname(dirname(fileURLToPath(import.meta.url)));
9
9
  const registerTools = await loadToolsSource('registerTools');
10
10
  const dataDir = join(root, '.test-output', 'tools');
11
11
  await fs.mkdir(dataDir, { recursive: true });
12
- function fixture(call) {
12
+ function fixture(call, activity, { armed = true } = {}) {
13
13
  const tools = new Map();
14
- const store = { running: false, windows: [], pointerMode: 'background', counters: {}, step() {}, actionDone() {}, setTree(nodes, meta) { this.tree = { nodes, ...meta }; }, setTarget(target) { this.target = target; } };
15
- const dispose = registerTools({ tools: { register(def) { tools.set(def.name, def); return () => {}; } } }, { worker: { call, epoch: 1 }, store, dataDir, owned: new Map() });
14
+ const store = { running: false, windows: [], pointerMode: 'background', counters: { refused: 0 }, heldButtons: new Set(), attempts: new Map(), ctrlCAt: 0, block() { return { id: 1 }; }, line() {}, step() {}, actionDone() {}, setWindows(w) { this.windows = w; }, holdButton(b) { this.heldButtons.add(b); }, releaseButton(b) { return this.heldButtons.delete(b); }, noteAttempt(sig, ok) { const cur = this.attempts.get(sig) ?? { total: 0, misses: 0 }; cur.total += 1; cur.misses = ok ? 0 : cur.misses + 1; this.attempts.set(sig, cur); return cur; }, clearAttempts() { this.attempts.clear(); }, setTree(nodes, meta) { this.tree = { nodes, ...meta }; }, setTarget(target) { this.target = target; } };
15
+ const dispose = registerTools({ tools: { register(def) { tools.set(def.name, def); return () => {}; } } }, {
16
+ worker: { call, epoch: 1 },
17
+ store,
18
+ dataDir,
19
+ owned: new Map(),
20
+ // The session permission gate is a callback in production (ctx.userQuestions behind it); the
21
+ // fixtures default to an armed session so tool bodies stay the thing under test.
22
+ ensureArmed: async () => armed,
23
+ ...(activity === undefined ? {} : { activity }),
24
+ });
16
25
  return { tools, store, dispose, execute: (name, args) => tools.get(name).execute(args, { signal: new AbortController().signal }) };
17
26
  }
18
27
  let passed = 0;
@@ -39,7 +48,8 @@ await test('recipe retains substring, duplicate index and proximity selector', a
39
48
  try { const result = await f.execute('computer_run', { windowId: 'w1', goal: 'selector-regression', steps: [{ by, action: 'invoke' }] }); const name = result.match(/已存配方:([^(\n]+)/)[1]; const recipe = JSON.parse(await fs.readFile(join(dataDir, 'recipes', name + '.json'), 'utf8')); assert.deepEqual(recipe.steps[0].by, by); } finally { f.dispose(); }
40
49
  });
41
50
  await test('verification failure reports delivered action without object-string noise', async () => {
42
- const f = fixture(async (cmd) => cmd === 'prepare_batch' ? { allResolved: true, revision: 1, descriptors: [{ name: 'Submit', controlType: 'Button' }] } : { stoppedAt: 0, performedCount: 1, results: [{ index: 0, action: 'invoke', performed: true, status: 'verify_failed', verify: { type: 'element_appears', matched: false } }] });
51
+ // Name is deliberately neutral: "Submit" would (correctly) stop at the confirm gate now.
52
+ const f = fixture(async (cmd) => cmd === 'prepare_batch' ? { allResolved: true, revision: 1, descriptors: [{ name: 'Run', controlType: 'Button' }] } : { stoppedAt: 0, performedCount: 1, results: [{ index: 0, action: 'invoke', performed: true, status: 'verify_failed', verify: { type: 'element_appears', matched: false } }] });
43
53
  try { const result = await f.execute('computer_run', { windowId: 'w1', goal: 'verify', steps: [{ by: { name: 'Submit' }, action: 'invoke' }] }); assert.match(result, /performedCount=1/); assert.match(result, /勿直接重试/); assert.match(result, /未命中\(element_appears\)/); assert.doesNotMatch(result, /\[object Object\]/); } finally { f.dispose(); }
44
54
  });
45
55
  await test('computer_snapshot depth is an optional integer forwarded as maxDepth', async () => {
@@ -76,8 +86,8 @@ await test('computer_done declares done/blocked/failed endings distinctly', asyn
76
86
  const failed = await f.execute('computer_done', { outcome: 'failed', reason: '目标窗口持续失焦' });
77
87
  assert.match(failed, /失败放弃/);
78
88
  assert.doesNotMatch(failed, /已完成/, 'a failed ending must not render as 已完成');
79
- // The panel step carries the three statuses verbatim (control.html already colours
80
- // blocked/failed as bad); only the done ending counts as passed.
89
+ // The step records carry the three statuses verbatim (the panel colours blocked/failed as
90
+ // bad); only the done ending counts as passed.
81
91
  assert.deepEqual(steps.map((s) => s.status), ['passed', 'blocked', 'failed']);
82
92
  assert.deepEqual(steps.map((s) => s.label), ['任务完成,收起指示层', '受阻未完成,收起指示层', '失败放弃,收起指示层']);
83
93
  // An unknown/omitted outcome falls back to done.
@@ -85,4 +95,143 @@ await test('computer_done declares done/blocked/failed endings distinctly', asyn
85
95
  assert.match(fallback, /已完成并收起御屏指示层/);
86
96
  } finally { f.dispose(); }
87
97
  });
98
+ await test('lazy batches resolve and deliver one step at a time', async () => {
99
+ const calls = [];
100
+ const f = fixture(async (cmd) => {
101
+ calls.push(cmd);
102
+ if (cmd === 'prepare_batch') return { allResolved: true, revision: 7, descriptors: [{ index: 0, name: '确定', controlType: 'Button', availablePatterns: ['Invoke'], rect: { x: 1, y: 1, w: 10, h: 10 } }] };
103
+ if (cmd === 'commit_batch') return { results: [{ index: 0, status: 'passed', performed: true, action: 'invoke', ms: 2 }], performedCount: 1 };
104
+ return {};
105
+ });
106
+ try {
107
+ const res = await f.execute('computer_run', { windowId: 'w1', goal: '两级菜单', lazy: true, saveRecipe: false, steps: [{ by: { name: '文件' }, action: 'invoke' }, { by: { name: '新建' }, action: 'invoke' }] });
108
+ assert.deepEqual(calls, ['prepare_batch', 'commit_batch', 'prepare_batch', 'commit_batch'], 'lazy mode must not pre-resolve the whole batch');
109
+ assert.match(res, /逐段模式/);
110
+ assert.match(res, /performedCount=2/);
111
+ assert.doesNotMatch(res, /逐段执行在第/);
112
+ } finally { f.dispose(); }
113
+ });
114
+
115
+ await test('repeating the same failing action is called out instead of invited', async () => {
116
+ let n = 0;
117
+ const f = fixture(async (cmd) => {
118
+ if (cmd === 'describe') return { name: '确定', controlType: 'Button', availablePatterns: ['Invoke'], rect: { x: 1, y: 1, w: 10, h: 10 } };
119
+ if (cmd === 'act') { n += 1; return { applied: true, via: 'uia', ms: 2, verify: { type: 'value_equals', matched: false, observed: 'unchanged' } }; }
120
+ return {};
121
+ });
122
+ try {
123
+ const runs = [];
124
+ for (let i = 0; i < 4; i += 1) runs.push(await f.execute('computer_act', { windowId: 'w1', ref: 'e1', action: 'invoke' }));
125
+ assert.doesNotMatch(runs[0], /停止重复调用/);
126
+ assert.doesNotMatch(runs[1], /停止重复调用/);
127
+ assert.match(runs[2], /连续 3 次校验未命中/);
128
+ assert.match(runs[2], /computer_done outcome="blocked"/);
129
+ assert.equal(n, 4, 'the watchdog must not suppress the action itself');
130
+ } finally { f.dispose(); }
131
+ });
132
+ await test('a send action is delivered when armed, and refused before the worker when not', async () => {
133
+ let acted = 0;
134
+ const send = { name: '发送', controlType: 'Button', availablePatterns: ['Invoke'], rect: { x: 1, y: 1, w: 10, h: 10 } };
135
+ const armed = fixture(async (cmd) => { if (cmd === 'describe') return send; if (cmd === 'act') { acted += 1; return { applied: true, via: 'uia', ms: 2 }; } return {}; });
136
+ try {
137
+ // The confirm family is gone: sending is ordinary work now, delivered without asking anyone.
138
+ const result = await armed.execute('computer_act', { windowId: 'w1', ref: 'e1', action: 'invoke' });
139
+ assert.match(result, /已执行/);
140
+ assert.doesNotMatch(result, /已拦截|ctrl\+alt\+y/);
141
+ assert.equal(acted, 1, 'an armed session must deliver the action');
142
+ } finally { armed.dispose(); }
143
+ const calls = [];
144
+ const disarmed = fixture(async (cmd) => { calls.push(cmd); if (cmd === 'describe') return send; return {}; }, undefined, { armed: false });
145
+ try {
146
+ const result = await disarmed.execute('computer_act', { windowId: 'w1', ref: 'e1', action: 'invoke' });
147
+ assert.match(result, /桌面控制未获准/);
148
+ assert.deepEqual(calls, [], 'a disarmed session must not reach the worker at all');
149
+ } finally { disarmed.dispose(); }
150
+ });
151
+
152
+ await test('clipboard read is gated on this run having copied something itself', async () => {
153
+ const calls = [];
154
+ const f = fixture(async (cmd) => {
155
+ calls.push(cmd);
156
+ if (cmd === 'key') return { ms: 1, repeat: 1 };
157
+ if (cmd === 'clipboard_read') return { text: 'hello', length: 5, empty: false };
158
+ return {};
159
+ });
160
+ try {
161
+ const denied = await f.execute('computer_clipboard', { op: 'read' });
162
+ assert.match(denied, /读取被拦/);
163
+ assert.match(denied, /ctrl\+c/);
164
+ assert.equal(calls.filter((c) => c === 'clipboard_read').length, 0, 'a gated read must not reach the worker');
165
+ await f.execute('computer_key', { keys: 'ctrl+c' });
166
+ assert.ok(f.store.ctrlCAt > 0, 'ctrl+c did not open the clipboard gate');
167
+ const got = await f.execute('computer_clipboard', { op: 'read' });
168
+ assert.match(got, /hello/);
169
+ assert.equal(calls.filter((c) => c === 'clipboard_read').length, 1);
170
+ } finally { f.dispose(); }
171
+ });
172
+
173
+ await test('a finished run can leave a note that the next observation brings back', async () => {
174
+ const f = fixture(async () => ({}));
175
+ try {
176
+ const done = await f.execute('computer_done', { summary: '画了一棵树', note: '树控件是自绘的,直接用 computer_parse', app: 'mspaint' });
177
+ assert.match(done, /已记下 mspaint 的笔记/);
178
+ const file = join(dataDir, 'notes', 'mspaint.json');
179
+ const saved = JSON.parse(await fs.readFile(file, 'utf8'));
180
+ assert.equal(saved.notes[0].text, '树控件是自绘的,直接用 computer_parse');
181
+ // The same sentence twice must not double-store it.
182
+ await f.execute('computer_done', { note: '树控件是自绘的,直接用 computer_parse', app: 'mspaint' });
183
+ const again = JSON.parse(await fs.readFile(file, 'utf8'));
184
+ assert.equal(again.notes.length, 1);
185
+ } finally { f.dispose(); }
186
+ const g = fixture(async (cmd) => cmd === 'list_windows' ? { windows: [{ windowId: 'w1', pid: 4, appName: 'mspaint', title: '未命名 - 画图', rect: { w: 800, h: 600 } }] } : {});
187
+ try {
188
+ const list = await g.execute('computer_windows', {});
189
+ assert.match(list, /笔记(mspaint)/);
190
+ assert.match(list, /computer_parse/);
191
+ } finally { g.dispose(); }
192
+ });
193
+
194
+ await test('a click can name a ref instead of coordinates, and the centre comes from its rect now', async () => {
195
+ const calls = [];
196
+ const f = fixture(async (cmd, body) => {
197
+ calls.push({ cmd, body });
198
+ if (cmd === 'describe') return { ref: 'e3', windowId: 'w1', name: '保存', controlType: 'Button', availablePatterns: ['Invoke'], rect: { x: 100, y: 200, w: 40, h: 20 } };
199
+ if (cmd === 'pointer_target') return { under: { title: 'w1', class: 'Button' } };
200
+ if (cmd === 'pointer_click') return { ms: 3, via: 'physical', under: { title: 'w1' }, mods: [] };
201
+ return {};
202
+ });
203
+ try {
204
+ const result = await f.execute('computer_click', { windowId: 'w1', ref: 'e3' });
205
+ const click = calls.find((c) => c.cmd === 'pointer_click');
206
+ assert.ok(click, 'the click never reached the worker');
207
+ assert.equal(click.body.x, 120, 'x must be the rect centre, not 0');
208
+ assert.equal(click.body.y, 210, 'y must be the rect centre, not 0');
209
+ assert.match(result, /已点击 e3/);
210
+ } finally { f.dispose(); }
211
+ });
212
+
213
+ await test('a mixed batch runs pointer steps in lazy mode and refuses to pretend otherwise', async () => {
214
+ const calls = [];
215
+ const f = fixture(async (cmd, body) => {
216
+ calls.push({ cmd, body });
217
+ if (cmd === 'describe') return { ref: 'e3', windowId: 'w1', name: '搜索', controlType: 'Edit', availablePatterns: ['Value'], rect: { x: 10, y: 10, w: 100, h: 20 } };
218
+ if (cmd === 'pointer_target') return { under: { title: 'w1', class: 'Edit' } };
219
+ return {};
220
+ });
221
+ try {
222
+ // Non-lazy: the whole point of that mode is that every target resolves before anything runs.
223
+ const refused = await f.execute('computer_run', { windowId: 'w1', goal: '混动作', steps: [{ action: 'click', ref: 'e3' }] });
224
+ assert.match(refused, /lazy: true/);
225
+ assert.deepEqual(calls, [], 'a refused mixed batch must not touch the worker');
226
+ // Lazy: click → type → key, each delivered on its own, stopping only on failure.
227
+ const result = await f.execute('computer_run', {
228
+ windowId: 'w1', goal: '混动作', lazy: true, saveRecipe: true,
229
+ steps: [{ action: 'click', ref: 'e3' }, { action: 'type', text: 'hello' }, { action: 'key', keys: 'enter' }],
230
+ });
231
+ assert.deepEqual(calls.map((c) => c.cmd), ['describe', 'pointer_click', 'type_text', 'key']);
232
+ assert.match(result, /performedCount=3/);
233
+ assert.match(result, /含指针步骤的批次不存配方/);
234
+ } finally { f.dispose(); }
235
+ });
236
+
88
237
  console.log(`${passed}/${passed} tool regressions passed (no desktop actions)`);
@@ -94,6 +94,25 @@ function Initialize-WorkerSource {
94
94
  }
95
95
  $all = $script:workerAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)
96
96
  foreach ($f in $all) { if (-not $script:fnAst.ContainsKey($f.Name)) { $script:fnAst[$f.Name] = $f } }
97
+ # The body was split into worker/lib (the entry dot-sources it in the order sources.mjs declares).
98
+ # Parse every part so Get-WorkerFunctionSource still finds the real definition; a part with a
99
+ # syntax error fails here instead of at the first live tool call.
100
+ $libDir = Join-Path (Split-Path -Parent $script:workerPath) 'lib'
101
+ $script:partAsts = New-Object System.Collections.Generic.List[object]
102
+ if (Test-Path -LiteralPath $libDir) {
103
+ foreach ($part in (Get-ChildItem -LiteralPath $libDir -Filter '*.ps1' | Sort-Object Name)) {
104
+ $tp = $null
105
+ $ep = $null
106
+ $partAst = [System.Management.Automation.Language.Parser]::ParseFile($part.FullName, [ref]$tp, [ref]$ep)
107
+ if ($ep.Count -gt 0) {
108
+ foreach ($e in $ep) { Write-Host ('PARSE ' + $part.Name + ' L' + $e.Extent.StartLineNumber + ': ' + $e.Message) }
109
+ throw ($part.Name + ' 解析失败, ' + $ep.Count + ' 个语法错误')
110
+ }
111
+ $script:partAsts.Add($partAst) | Out-Null
112
+ $allPart = $partAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)
113
+ foreach ($f in $allPart) { if (-not $script:fnAst.ContainsKey($f.Name)) { $script:fnAst[$f.Name] = $f } }
114
+ }
115
+ }
97
116
  # 共享 stdio 框架在 worker/ps-stdio.ps1(worker 在运行时 dot-source 它)。按函数名抽取
98
117
  # 也要把它的 FunctionDefinitionAst 并进来,否则 $workerDeps 里的 Dict/JsonOf/Split-Err/
99
118
  # Esc 等会在 Get-WorkerFunctionSource 报"worker 里没有函数 X"。
@@ -122,6 +141,14 @@ function Get-WorkerFunctionSource([string[]]$names) {
122
141
  }
123
142
 
124
143
  function Get-WorkerAssignmentValue([string]$leftText) {
144
+ # $handlers / $defaultBudget moved into worker/lib/10-dispatch.ps1 with the split: search every
145
+ # parsed part, not just the entry, or the dispatch tests read "no handler" and pass on nothing.
146
+ if ($null -ne $script:partAsts) {
147
+ foreach ($ast in $script:partAsts) {
148
+ $hit = $ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and $n.Left.Extent.Text -eq $leftText }, $true) | Select-Object -First 1
149
+ if ($null -ne $hit) { return (Invoke-Expression $hit.Right.Extent.Text) }
150
+ }
151
+ }
125
152
  $a = $script:workerAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and $n.Left.Extent.Text -eq $leftText }, $true) | Select-Object -First 1
126
153
  if ($null -eq $a) { return $null }
127
154
  return (Invoke-Expression $a.Right.Extent.Text)
@@ -383,6 +410,8 @@ $workerDeps = @(
383
410
  'DescriptorOf', 'Read-Value', 'SupportedActionOf', 'Resolve-Ref', 'New-Ref', 'RuntimeIdKey', 'Apply-ModeArg',
384
411
  # GetPattern 缓存层:Read-Value 第三参路由到这里,不加载就会在 commit 用例里 CommandNotFound。
385
412
  'Get-RefPattern',
413
+ # 屏外元素先滚动到可见:Cmd-CommitBatch 每步动作前都会调用它,缺了就在 15.x 里整批失败。
414
+ 'Ensure-InView',
386
415
  # verify 求值管道:Eval-Once(scroll_percent_changed 用例)/ Target-Element(其目标解析)/
387
416
  # Read-ScrollPercent(滚动百分比动作前读数)。
388
417
  'Eval-Once', 'Target-Element', 'Read-ScrollPercent',
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Drive the panel's own action channel and prove each shape reaches the renderer.
3
+ * This is the end-to-end check for "why can't I change the capsule": it posts exactly what the
4
+ * panel posts, then asks the running process what it built.
5
+ */
6
+ const BASE = process.env.UIA_CONTROL ?? 'http://127.0.0.1:3099';
7
+
8
+ async function json(path, options = {}) {
9
+ const res = await fetch(`${BASE}${path}`, options);
10
+ return { status: res.status, body: await res.json().catch(() => null) };
11
+ }
12
+ const post = (body) => json('/api/action', {
13
+ method: 'POST',
14
+ headers: { 'content-type': 'application/json', 'x-dsh-cua': '1' },
15
+ body: JSON.stringify(body),
16
+ });
17
+
18
+ const summary = await json('/api/summary');
19
+ const cfg = summary.body?.config;
20
+ if (!cfg) {
21
+ console.log('[FAIL] no config block: the plugin is not active on this port');
22
+ process.exit(1);
23
+ }
24
+ console.log(`catalog from the running process:`);
25
+ console.log(` themes: ${(cfg.themes ?? []).map((t) => t.id).join(', ')}`);
26
+ console.log(` styles: ${(cfg.styles ?? []).map((s) => s.id).join(', ')}`);
27
+
28
+ const wanted = ['orb', 'wave', 'mark', 'inverse'];
29
+ let bad = 0;
30
+ for (const id of wanted) {
31
+ const r = await post({ kind: 'style', style: id });
32
+ const state = await json('/api/summary');
33
+ const live = state.body?.style;
34
+ const ok = r.body?.ok === true && live === id;
35
+ if (!ok) bad++;
36
+ console.log(`[${ok ? 'PASS' : 'FAIL'}] style=${id} -> action.ok=${r.body?.ok} live=${live}`);
37
+ }
38
+ // A shape the worker cannot build must be refused, not silently accepted.
39
+ const junk = await post({ kind: 'style', style: 'nope' });
40
+ console.log(`[${junk.body?.ok === false ? 'PASS' : 'FAIL'}] unknown shape refused: ${JSON.stringify(junk.body)}`);
41
+ if (junk.body?.ok !== false) bad++;
42
+
43
+ // Restore the default so the person's capsule is not left on a test shape.
44
+ await post({ kind: 'style', style: cfg.defaultStyle ?? 'orb' });
45
+ console.log(`\n${wanted.length + 1 - bad}/${wanted.length + 1} checks passed`);
46
+ process.exit(bad === 0 ? 0 : 1);
@@ -4,7 +4,7 @@
4
4
  * asking the plugin's own loopback server. Nothing here passes on the strength
5
5
  * of a file existing — the answer has to come from the loaded process.
6
6
  */
7
- import { get, request } from 'node:http';
7
+ import { request } from 'node:http';
8
8
 
9
9
  const BASE = process.env.UIA_CONTROL ?? 'http://127.0.0.1:3099';
10
10
  const WAIT_MS = Number(process.env.WAIT_MS ?? 90000);
@@ -54,8 +54,13 @@ check('policy refusals are marked non-approvable', snapshot.session?.policy?.app
54
54
  check('vision route reported as a measured fact', typeof snapshot.session?.stats?.visionRoute === 'boolean', `visionRoute=${snapshot.session?.stats?.visionRoute}`);
55
55
  check('target starts unclaimed', snapshot.session?.target === null, JSON.stringify(snapshot.session?.target));
56
56
 
57
- const page = await httpJson('/control.html');
58
- check('control page is served', page.status === 200 && page.body.length > 20000, `${page.status} ${page.body.length} bytes`);
57
+ const summary = JSON.parse((await httpJson('/api/summary')).body);
58
+ check('the summary the plugin page polls answers', typeof summary.running === 'boolean' && 'lastStep' in summary && Array.isArray(summary.log),
59
+ `running=${summary.running} steps=${summary.steps} log=${(summary.log ?? []).length}`);
60
+ check('the summary carries no element tree or image', summary.tree === undefined && summary.windows === undefined && summary.screenshot === undefined,
61
+ Object.keys(summary).join(','));
62
+ check('the config block has the facts the page prints', typeof summary.config?.port === 'number' && typeof summary.config?.leaseMs === 'number' && typeof summary.config?.idleMs === 'number' && typeof summary.config?.readOnly === 'boolean',
63
+ JSON.stringify(summary.config));
59
64
 
60
65
  const approve = await httpJson('/api/action', {
61
66
  method: 'POST',
@@ -71,7 +76,8 @@ const unheadered = await httpJson('/api/action', {
71
76
  });
72
77
  check('POST without the plugin header is refused (MUST FIRE)', unheadered.status === 403, `${unheadered.status} ${unheadered.body.slice(0, 90)}`);
73
78
 
74
- check('no CORS header, so other local pages cannot read state', headers?.['access-control-allow-origin'] === undefined, `access-control-allow-origin=${headers?.['access-control-allow-origin'] ?? 'none'}`);
79
+ check('CORS is open to the app renderer, which is a different origin than the loopback port', headers?.['access-control-allow-origin'] === '*', `access-control-allow-origin=${headers?.['access-control-allow-origin'] ?? 'none'}`);
80
+ check('the removed control page is not served any more (MUST FIRE)', (await httpJson('/control.html')).status === 404, 'GET /control.html');
75
81
 
76
82
  const liveState = JSON.parse((await httpJson('/api/state')).body);
77
83
  check('the snapshot publishes the kill latch and no pause state', liveState.session.killed === false && liveState.session.paused === undefined, `killed=${liveState.session.killed} paused=${liveState.session.paused}`);
@@ -83,20 +89,8 @@ const pauseGone = await httpJson('/api/action', {
83
89
  });
84
90
  check('the pause switch is gone (unknown kind, MUST FIRE)', /"ok"\s*:\s*false/.test(pauseGone.body), `${pauseGone.status} ${pauseGone.body.slice(0, 110)}`);
85
91
 
86
- const sse = await new Promise((resolve) => {
87
- const req = get(`${BASE}/api/stream`, (res) => {
88
- let body = '';
89
- res.setEncoding('utf8');
90
- const timer = setTimeout(() => {
91
- req.destroy();
92
- resolve(body);
93
- }, 1200);
94
- timer.unref?.();
95
- res.on('data', (chunk) => (body += chunk));
96
- });
97
- req.on('error', () => resolve(''));
98
- });
99
- check('stream endpoint opens and announces a state frame', /^event: state/m.test(sse), `${sse.length} bytes before close`);
92
+ const preflight = await httpJson('/api/action', { method: 'OPTIONS' });
93
+ check('the preflight the panel needs is answered with the POST contract', preflight.status === 204 && String(preflight.headers['access-control-allow-methods'] ?? '').includes('POST'), `${preflight.status} ${preflight.headers['access-control-allow-methods'] ?? ''}`);
100
94
 
101
95
  // Code-generation gate: the running process must carry the lease/Esc/find_text contract fixes.
102
96
  // A restart is the only way the loaded build changes, so this answers "did it really happen?".