dsh-native-uia 0.4.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.
package/src/state.js CHANGED
@@ -38,7 +38,6 @@ export class Store extends EventEmitter {
38
38
  // cached in the client, so a future re-ask (panel button) applies to the next call immediately.
39
39
  armed = false;
40
40
  running = false;
41
- visionRoute = false;
42
41
  counters = { stepsRun: 0, actions: 0, blocked: 0, refused: 0, stepMsTotal: 0, stepSamples: 0 };
43
42
  // Mouse buttons currently held down by computer_mouse action:"down". A dangling press is a stuck
44
43
  // desktop (every later click becomes a drag), so it is tracked here and released on run end.
@@ -210,14 +209,12 @@ export class Store extends EventEmitter {
210
209
  armed: this.armed === true,
211
210
  target: this.#targetView(),
212
211
  policy,
213
- remoteChannel: this.remoteChannel ?? 'pending',
214
212
  stats: {
215
213
  stepsRun: c.stepsRun,
216
214
  actions: c.actions,
217
215
  blocked: c.blocked,
218
216
  refused: c.refused,
219
217
  avgStepMs: c.stepSamples > 0 ? Math.round(c.stepMsTotal / c.stepSamples) : 0,
220
- visionRoute: this.visionRoute,
221
218
  },
222
219
  },
223
220
  windows: this.#windowsView(),
package/src/themes.js CHANGED
@@ -11,16 +11,13 @@
11
11
  */
12
12
 
13
13
  /**
14
- * Two palettes. `ring*` paints the screen-edge glow; `pill*` stays identical in both.
14
+ * Two palettes. `ring*` paints the screen-edge glow; `pill*` is identical in both, because the
15
+ * capsule shell colour is not part of what a theme changes.
15
16
  *
16
- * `brand` is the brand black: a near-black ramp, which is what the name means and what the shell
17
- * already is. It is deliberately dark -- the ambient is a dark rim that reads as a vignette on a
18
- * light wallpaper, not as a bright line. `graphite` is the silver one, and the two are chosen for
19
- * different walls.
20
- *
21
- * The bug that made "switching does nothing" was NOT these numbers: the renderer built its ring
22
- * from `pillBorder` (identical in both palettes) instead of from `ringFrom`/`ringTo`, so no value
23
- * here could ever reach the screen. That is fixed in Build-Ring; these are the values it now uses.
17
+ * `brand` is the brand black: a near-black ramp that reads as a vignette on a light wallpaper, not
18
+ * as a bright line. `graphite` is the cool blue-silver one, for a dark desktop where a dark rim
19
+ * would vanish. The renderer must paint the ring from `ringFrom`/`ringTo` only — `pillBorder` is
20
+ * identical in both palettes, so a ring built from it makes the switch look dead.
24
21
  */
25
22
  export const THEMES = Object.freeze([
26
23
  Object.freeze({ id: 'brand', name: '品牌黑', ringFrom: '#2A2E34', ringTo: '#000000', pillBg: '#0B0D10', pillBorder: '#A9B4C4', pillText: '#F2F5FA' }),
@@ -31,23 +28,18 @@ export const THEMES = Object.freeze([
31
28
  /**
32
29
  * The capsule shapes the worker can actually build.
33
30
  *
34
- * This list is the panel's catalog, so it has to match `Build-Pill` in the worker exactly: an id
35
- * the worker cannot build is a switch that silently does nothing, and an id missing here is a shape
36
- * the person cannot reach at all -- which is what happened when only `orb` was listed while the
37
- * renderer already had four.
38
- *
39
- * `compact` says which heights the worker gives it (44 DIP single line, 56 DIP with the second
40
- * line), so the panel does not have to describe sizes in prose.
31
+ * This list is the panel's catalog, so it has to match the worker's style switch exactly: an id the
32
+ * worker cannot build is a switch that silently does nothing, and an id missing here is a shape the
33
+ * person cannot reach. All four are the same size (172×44 DIP) — a shape changes the shell's look,
34
+ * never the silhouette.
41
35
  */
42
36
  export const STYLES = Object.freeze([
43
- // `orb` is the historical id; the mark has been the DSH whale for a long time, and "光球" (the
44
- // glass bead it started as) described something that is no longer drawn. The name the person
45
- // reads is the whale, so the label says so. The id stays: it is persisted in settings.json and
46
- // pinned by the gates.
47
- Object.freeze({ id: 'orb', name: '深黑', compact: true, hint: '深黑壳,白鲸直接画在壳上' }),
48
- Object.freeze({ id: 'wave', name: '声波', compact: true, hint: '三根声波条' }),
49
- Object.freeze({ id: 'mark', name: '标块', compact: true, hint: '浅色圆角块 + 深鲸' }),
50
- Object.freeze({ id: 'inverse', name: '反白', compact: true, hint: '白壳黑字,浅色壁纸' }),
37
+ // `orb` keeps its historical id because settings.json persists it and the gates pin it; the label
38
+ // says what is actually drawn (the DSH whale cut out of a near-black shell).
39
+ Object.freeze({ id: 'orb', name: '深黑', hint: '深黑壳,白鲸直接画在壳上' }),
40
+ Object.freeze({ id: 'wave', name: '声波', hint: '三根声波条' }),
41
+ Object.freeze({ id: 'mark', name: '标块', hint: '浅色圆角块 + 深鲸' }),
42
+ Object.freeze({ id: 'inverse', name: '反白', hint: '白壳黑字,浅色壁纸' }),
51
43
  ]);
52
44
 
53
45
  export const DEFAULT_THEME = 'brand';
@@ -1,4 +1,4 @@
1
- import { classify, classifyBatch } from '../../guard.js';
1
+ import { classify, classifyBatch, classifyKeys } from '../../guard.js';
2
2
  import { noteHint } from '../../notes.js';
3
3
  import { writeFile } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
@@ -19,12 +19,12 @@ export function registerAct(d) {
19
19
 
20
20
  d.disposers.push(register(defineTool({
21
21
  name: 'computer_act',
22
- description: 'Perform one UI Automation action on one element by its ref from a current snapshot: invoke | set_value | toggle | select | expand | collapse | scroll_up | scroll_down | focus | text_append. Delivered in the background: the cursor does not move and focus is not stolen.',
22
+ description: 'Perform one UI Automation action on one element by its ref from a current snapshot: invoke | set_value | toggle | select | deselect | add_to_selection | expand | collapse | scroll_up | scroll_down | scroll_to | set_range | focus | text_append. Delivered in the background: the cursor does not move and focus is not stolen. deselect/add_to_selection extend a multi-select list; scroll_to uses ScrollItem.ScrollIntoView (the provider moves the exact container); set_range takes a number in `value` and clamps to the control Min/Max.',
23
23
  parameters: {
24
24
  windowId: { ...STR, required: true },
25
25
  ref: { ...STR, required: true, description: 'Element ref from the newest snapshot of this window' },
26
- action: { type: 'string', enum: ['invoke', 'set_value', 'toggle', 'select', 'expand', 'collapse', 'scroll_up', 'scroll_down', 'focus', 'text_append'], required: true },
27
- value: { ...STR, description: 'Text for set_value / text_append' },
26
+ action: { type: 'string', enum: ['invoke', 'set_value', 'toggle', 'select', 'deselect', 'add_to_selection', 'expand', 'collapse', 'scroll_up', 'scroll_down', 'scroll_to', 'set_range', 'focus', 'text_append'], required: true },
27
+ value: { ...STR, description: 'Text for set_value / text_append; a number for set_range (e.g. "40" or "0.5")' },
28
28
  revision: { ...INT, description: 'The revision the ref came from; omit to use the newest snapshot' },
29
29
  verify: { type: 'json', description: 'Optional {type, expect, timeoutMs} check run locally right after the action' },
30
30
  scrollIntoView: { ...BOOL, description: 'when the element is offscreen, scroll it into view first (default true); false acts without moving the viewport' },
@@ -104,10 +104,14 @@ export function registerAct(d) {
104
104
  text_append: ['Value'],
105
105
  toggle: ['Toggle'],
106
106
  select: ['SelectionItem'],
107
+ deselect: ['SelectionItem'],
108
+ add_to_selection: ['SelectionItem'],
107
109
  expand: ['ExpandCollapse'],
108
110
  collapse: ['ExpandCollapse'],
109
111
  scroll_up: ['Scroll'],
110
112
  scroll_down: ['Scroll'],
113
+ scroll_to: ['ScrollItem'],
114
+ set_range: ['RangeValue'],
111
115
  };
112
116
  const have = Array.isArray(described?.availablePatterns) ? described.availablePatterns : [];
113
117
  const need = NEEDED[String(args.action)] ?? [];
@@ -136,6 +140,104 @@ export function registerAct(d) {
136
140
  })));
137
141
 
138
142
 
143
+ // Steps the batch can only run one at a time (lazy): they act on pixels/keys, not on a ref of a
144
+ // resolvable element, so the classic "resolve every target, then commit against one revision"
145
+ // shape cannot express them. Every one still goes through the same policy table and the same
146
+ // per-step stop rule as a UIA step.
147
+ const POINTER_STEPS = new Set(['click', 'double_click', 'right_click', 'hover', 'type', 'key', 'scroll', 'drag', 'wait']);
148
+ const modsOf = (value) => {
149
+ if (value === undefined || value === null || value === '') return [];
150
+ return (Array.isArray(value) ? value : String(value).split('+')).map((m) => String(m).trim().toLowerCase()).filter(Boolean);
151
+ };
152
+ // One target resolver for pointer steps: a ref (centre from its live rect) or explicit x,y.
153
+ // Returns {error} instead of throwing so the step result can say what was wrong.
154
+ const pointOfStep = async (step, fallbackWindow) => {
155
+ if (step.ref !== undefined && step.ref !== null && String(step.ref) !== '') {
156
+ let d = null;
157
+ try { d = await worker.call('describe', { ref: String(step.ref) }); } catch (error) {
158
+ return { error: `ref ${step.ref} 解析失败(${error?.code ?? 'worker_error'}):${error?.message ?? error}` };
159
+ }
160
+ const r = d?.rect;
161
+ if (!r || !(r.w > 0) || !(r.h > 0)) return { error: `ref ${step.ref} 没有可点矩形(元素不可见或没有布局框)` };
162
+ return { x: Math.round(r.x + r.w / 2), y: Math.round(r.y + r.h / 2), windowId: String(d?.windowId ?? fallbackWindow ?? ''), descriptor: d };
163
+ }
164
+ if (typeof step.x === 'number' && typeof step.y === 'number') {
165
+ const wid = String(step.windowId ?? fallbackWindow ?? '');
166
+ let under = null;
167
+ try {
168
+ const t = await worker.call('pointer_target', { x: step.x, y: step.y });
169
+ under = t?.under ?? t;
170
+ } catch { under = null; }
171
+ return {
172
+ x: step.x, y: step.y, windowId: wid,
173
+ descriptor: { title: under?.title, className: under?.class ?? under?.hitClass, name: under?.app },
174
+ };
175
+ }
176
+ return { error: '这一步需要 ref(推荐)或 x,y' };
177
+ };
178
+ const runPointerStep = async (step, fallbackWindow) => {
179
+ const action = String(step.action ?? '').toLowerCase();
180
+ const started = Date.now();
181
+ const done = (detail, performed = 1) => ({ status: 'passed', ms: Date.now() - started, detail, performed });
182
+ if (action === 'wait') {
183
+ const cond = step.condition ?? step.verify ?? null;
184
+ if (cond === null) return { status: 'failed', detail: 'wait 步需要 condition(与 computer_wait 的 condition 同形)' };
185
+ const r = await worker.call('wait', { windowId: step.windowId ?? '', condition: cond, timeoutMs: step.timeoutMs ?? 10000 }, { timeoutMs: 98000 });
186
+ return {
187
+ status: r.matched === true ? 'passed' : 'failed',
188
+ ms: Date.now() - started,
189
+ detail: r.matched === true ? `条件命中${r.observed !== undefined ? ` observed=${JSON.stringify(r.observed)}` : ''}` : `等待超时(${r.error ?? 'no match'})`,
190
+ performed: 0,
191
+ };
192
+ }
193
+ if (action === 'key') {
194
+ const combo = String(step.keys ?? '').trim().toLowerCase();
195
+ if (combo === '') return { status: 'failed', detail: 'key 步需要 keys(如 "ctrl+s")' };
196
+ // Same policy as computer_key: the combo text goes through guard's keyboard table.
197
+ const verdict = classifyKeys(combo);
198
+ if (verdict.verdict === 'deny') return { status: 'blocked', detail: verdict.refusal, performed: 0 };
199
+ const r = await worker.call('key', { keys: combo, repeat: step.repeat, holdMs: step.holdMs });
200
+ if (/(?:^|\+)ctrl\+c(?:\+|$)/.test(combo)) store.ctrlCAt = Date.now();
201
+ return done(`按键 ${combo}${r?.repeat > 1 ? ` ×${r.repeat}` : ''}`, 1);
202
+ }
203
+ if (action === 'type') {
204
+ const text0 = String(step.text ?? step.value ?? '');
205
+ if (text0 === '') return { status: 'failed', detail: 'type 步需要 text' };
206
+ const via = step.via === 'clipboard' ? 'clipboard' : 'keyboard';
207
+ await worker.call('type_text', { text: text0, windowId: step.windowId ? String(step.windowId) : '', via });
208
+ return done(`输入 ${text0.length} 字(${via}${via === 'clipboard' ? ',已覆盖剪贴板' : ''})`, 1);
209
+ }
210
+ const pt = await pointOfStep(step, fallbackWindow);
211
+ if (pt.error) return { status: 'failed', detail: pt.error, performed: 0 };
212
+ if (pt.windowId === '') return { status: 'failed', detail: '这一步没有窗口可归属:给 ref 或 windowId', performed: 0 };
213
+ // The same destructive-target table the pointer tools use: a coordinate or a ref both resolve
214
+ // to what is actually at that point, and an entry the policy refuses never gets a press.
215
+ const verdict = classify({ action: 'invoke', descriptor: pt.descriptor ?? {} });
216
+ if (verdict.verdict === 'deny') return { status: 'blocked', detail: verdict.refusal, performed: 0 };
217
+ const expect = { windowId: pt.windowId };
218
+ if (action === 'click' || action === 'double_click' || action === 'right_click') {
219
+ const button = action === 'right_click' ? 'right' : (step.button ?? 'left');
220
+ const double = action === 'double_click' || step.double === true;
221
+ await worker.call('pointer_click', { x: pt.x, y: pt.y, button, double, triple: step.triple === true, mods: modsOf(step.modifiers), durationMs: step.durationMs, expect });
222
+ return done(`点击 ${pt.x},${pt.y} ${button}${double ? ' 双击' : ''}`, 1);
223
+ }
224
+ if (action === 'hover') {
225
+ await worker.call('pointer_mouse', { action: 'move', x: pt.x, y: pt.y, durationMs: step.durationMs, expect });
226
+ return done(`悬停 ${pt.x},${pt.y}`, 1);
227
+ }
228
+ if (action === 'scroll') {
229
+ const r = await worker.call('pointer_scroll', { x: pt.x, y: pt.y, direction: step.direction, clicks: step.clicks, mods: modsOf(step.modifiers), expect });
230
+ return done(`滚动 ${step.direction ?? 'down'} ${r?.clicks ?? step.clicks ?? 3} 格 @${pt.x},${pt.y}`, 1);
231
+ }
232
+ if (action === 'drag') {
233
+ const end = await pointOfStep({ ref: step.toRef, x: step.toX, y: step.toY }, fallbackWindow);
234
+ if (end.error) return { status: 'failed', detail: `终点:${end.error}`, performed: 0 };
235
+ await worker.call('pointer_drag', { from: { x: pt.x, y: pt.y }, to: { x: end.x, y: end.y }, button: step.button, durationMs: step.durationMs, expect });
236
+ return done(`拖拽 ${pt.x},${pt.y} → ${end.x},${end.y}`, 1);
237
+ }
238
+ return { status: 'failed', detail: `未知的指针步骤 ${action}`, performed: 0 };
239
+ };
240
+
139
241
  // Lazy mode: resolve → policy-check → deliver each step on its own, so step N+1 may target UI that
140
242
  // step N just created (menu items, dialogs, a row that only exists after a search). The classic
141
243
  // batch must resolve every target up front and therefore cannot express that flow at all.
@@ -155,6 +257,29 @@ export function registerAct(d) {
155
257
  if (store.killed === true) { stopReason = '用户已终止本轮(Esc/面板)'; stopIndex = i; break; }
156
258
  const one = [steps[i]];
157
259
  const label = `第 ${i + 1} 步 ${steps[i]?.action ?? '?'}`;
260
+ // A pointer/keyboard step runs on its own and skips the resolve/commit pair entirely: it has no
261
+ // element to resolve against one revision, and its target may be the UI the previous step just
262
+ // created. Same stop rule, same policy table, one line in the panel.
263
+ if (POINTER_STEPS.has(String(steps[i]?.action ?? '').toLowerCase())) {
264
+ let pr;
265
+ try {
266
+ pr = await runPointerStep(steps[i], args.windowId);
267
+ } catch (error) {
268
+ pr = { status: 'failed', performed: 0, detail: `执行失败(${error?.code ?? 'worker_error'}):${error?.message ?? error}` };
269
+ }
270
+ descriptors.push(null);
271
+ results.push({ index: i, action: String(steps[i].action), status: pr.status, ms: pr.ms, detail: pr.detail, performed: pr.performed === 1 });
272
+ performed += pr.performed ?? 0;
273
+ store.step({ label, status: pr.status, ms: pr.ms, detail: pr.detail });
274
+ if (pr.status !== 'passed') {
275
+ stopReason = pr.status === 'blocked'
276
+ ? `策略拒绝:${pr.detail}`
277
+ : `第 ${i + 1} 步未通过(${pr.status}):${pr.detail}`;
278
+ stopIndex = i;
279
+ break;
280
+ }
281
+ continue;
282
+ }
158
283
  let prep = null;
159
284
  try {
160
285
  prep = await worker.call('prepare_batch', { steps: one, windowId: args.windowId }, { timeoutMs: 60000 });
@@ -202,8 +327,12 @@ export function registerAct(d) {
202
327
  }
203
328
  store.actionDone(performed);
204
329
  const allPassed = stopIndex === -1 && results.length === steps.length && results.every((r) => r.status === 'passed');
205
- let recipeNote = '';
206
- if (allPassed && args.saveRecipe !== false) {
330
+ // A mixed batch is not saved as a recipe: its pointer steps target coordinates or whatever is at
331
+ // a point, and a recipe replayed on another layout would click the wrong place. The UIA path
332
+ // keeps saving because its by-descriptors survive layout drift.
333
+ const mixed = steps.some((s) => POINTER_STEPS.has(String(s?.action ?? '').toLowerCase()));
334
+ let recipeNote = mixed && args.saveRecipe !== false ? '\n(含指针步骤的批次不存配方:坐标会随布局漂移,回放会点错位置)' : '';
335
+ if (allPassed && args.saveRecipe !== false && !mixed) {
207
336
  const name = await saveRecipe(recipeDir, {
208
337
  goal: args.goal,
209
338
  window: descriptors[0]?.ownerWindow ?? windowOf(store, args.windowId),
@@ -226,11 +355,11 @@ export function registerAct(d) {
226
355
 
227
356
  d.disposers.push(register(defineTool({
228
357
  name: 'computer_run',
229
- description: 'Execute a planned batch of desktop actions in one call. All targets must already exist before the batch starts; split a menu-opening action from actions on its newly created items — or set lazy:true, which resolves and delivers one step at a time so a later step can target what an earlier step just created. Use refs or by descriptors with name, nameExact (default true), controlType, className, automationId, nth or nearPoint. For changing labels, use a stable substring with nameExact:false. Every step is policy-checked; performedCount counts delivered actions even if their verification fails.',
358
+ description: 'Execute a planned batch of desktop actions in one call. All targets must already exist before the batch starts; split a menu-opening action from actions on its newly created items — or set lazy:true, which resolves and delivers one step at a time so a later step can target what an earlier step just created. UIA steps use refs or by descriptors with name, nameExact (default true), controlType, className, automationId, nth or nearPoint. In lazy mode the batch also accepts pointer steps: click / double_click / right_click / hover (target by ref or x,y), type (text, via), key (keys, repeat), scroll (direction, clicks), drag (ref or fromX/fromY → toRef or toX/toY), wait (condition) — so one call can click a field, type, press enter, and verify, stopping at the first failure. Every step is policy-checked; performedCount counts delivered actions even if their verification fails. A batch containing pointer steps is not saved as a recipe (coordinates drift).',
230
359
  parameters: {
231
360
  windowId: { ...STR, required: true },
232
361
  goal: { ...STR, required: true, description: 'One sentence describing the outcome this batch produces; stored with the recipe' },
233
- steps: { ...JSON_ARR, required: true, description: '[{ref|by, action, value?, verify?, timeoutMs?}]' },
362
+ steps: { ...JSON_ARR, required: true, description: '[{ref|by, action, value?, verify?, timeoutMs?}] — with lazy:true also [{action:"click"|"double_click"|"right_click"|"hover", ref|x,y, ...}]、[{action:"type", text, via?}]、[{action:"key", keys, repeat?, holdMs?}]、[{action:"scroll", ref|x,y, direction?, clicks?}]、[{action:"drag", ref|fromX,fromY, toRef|toX,toY}]、[{action:"wait", condition, timeoutMs?}]' },
234
363
  lazy: { ...BOOL, description: 'resolve→check→deliver each step separately (default false). Costs one round trip per step; use it when step N+1 targets UI that step N creates (menu items, dialogs)' },
235
364
  saveRecipe: { ...BOOL, description: 'Save a replayable recipe when every step passes (default true)' },
236
365
  },
@@ -243,6 +372,15 @@ export function registerAct(d) {
243
372
  }
244
373
  const steps = Array.isArray(args.steps) ? args.steps : [];
245
374
  if (steps.length === 0) return 'computer_run 需要非空的 steps 数组';
375
+ const mixed = [...new Set(steps.filter((s) => POINTER_STEPS.has(String(s?.action ?? '').toLowerCase())).map((s) => String(s.action)))];
376
+ if (mixed.length > 0 && args.lazy !== true) {
377
+ // Not a policy refusal: the classic batch resolves every target BEFORE it performs anything
378
+ // and then commits against ONE revision. A pointer/keyboard step has no element to resolve
379
+ // and may target what an earlier step creates, so it can only run in the per-step path.
380
+ return `这一批里有指针/键盘步骤(${mixed.join('、')}),非 lazy 批次做不到:它要求所有目标在执行前就已存在,并把每一步对同一个 revision 校验,而指针步骤没有可解析的元素。\n`
381
+ + '两种改法:加 `lazy: true` 用逐段模式重跑这一批(每步单独解析、执行、校验,后一步可以用前一步刚做出来的界面);'
382
+ + '或者把这些步骤拆出去交给 computer_click / computer_type / computer_key / computer_wait,UIA 步骤留在这一批。';
383
+ }
246
384
  if (args.lazy === true) return runLazy(args, steps, exec);
247
385
  const prepared = await worker.call('prepare_batch', { steps, windowId: args.windowId }, { timeoutMs: 188000 });
248
386
  const prepError = preparationFailure(prepared, steps.length);
@@ -458,8 +596,8 @@ export function registerAct(d) {
458
596
  const prepared = await worker.call('prepare_batch', { steps, windowId, rebindBy: true });
459
597
  const prepError = preparationFailure(prepared, steps.length);
460
598
  if (prepError) {
461
- // A failed replay used to return invisibly to the control page: without a store.step the
462
- // console showed nothing about the replay the model just attempted.
599
+ // A failed replay must leave a step in the store: without one the panel showed nothing
600
+ // about the replay the model just attempted.
463
601
  store.step({ label: `回放 ${args.name}`, kind: 'batch', status: 'failed', detail: prepError });
464
602
  return prepError;
465
603
  }
@@ -469,7 +607,7 @@ export function registerAct(d) {
469
607
  let committed;
470
608
  try {
471
609
  // mode rides on every act/commit_batch (the worker's declared contract): without it a
472
- // replay after a control-page kill always ran background and UIA-hostile elements lost
610
+ // replay after an Esc stop always ran background and UIA-hostile elements lost
473
611
  // their pixel fallback.
474
612
  committed = await worker.call('commit_batch', { revision: prepared.revision, steps, windowId, mode: store.pointerMode, indicatorPid: activity?.indicator?.proc?.pid ?? 0 });
475
613
  } catch (error) {
@@ -181,8 +181,8 @@ export function registerLifecycle(d) {
181
181
  store.setTarget(null);
182
182
  // Three endings get three words: only outcome=done may say 已完成 — a blocked/failed run
183
183
  // rendered as "任务完成" taught the panel (and the model's own next turn) a lie. The panel
184
- // already colours both 'blocked' and 'failed' steps as bad (control.html isBad), so the
185
- // status values below need no panel change.
184
+ // already draws both 'blocked' and 'failed' steps as bad, so the status values below need no
185
+ // panel change.
186
186
  const tail = reason ? `(原因:${reason})` : summary ? `(${summary})` : '';
187
187
  const verdicts = {
188
188
  done: { status: 'passed', label: '任务完成,收起指示层', text: `已完成并收起御屏指示层${summary ? `(${summary})` : ''}。` },
@@ -43,14 +43,16 @@ export function registerObserve(d) {
43
43
 
44
44
  d.disposers.push(register(defineTool({
45
45
  name: 'computer_snapshot',
46
- description: 'Read a window UI Automation tree and return its interactive elements with short refs (e1, e2, ...). Refs belong to one revision of one window: a newer snapshot invalidates the older refs. This is the primary observation channel and needs no vision model. Rhythm on large windows: take a shallow pass first (depth=4-5) to see the structural skeleton, locate the target container, then either computer_find_text into it or dig deeper with a higher depth/maxNodes — a deep pass over a big tree burns both latency and tokens.',
46
+ description: 'Read a window UI Automation tree and return its elements with short refs (e1, e2, ...) plus each one\'s state (toggle/selected/expanded/range/scroll). Refs belong to one revision of one window: a newer whole-window snapshot invalidates older refs (a root=<ref> subtree pass does not). This is the primary observation channel and needs no vision model. Rhythm on large windows: take a shallow pass first (depth=4-5) to see the structural skeleton, then either computer_find_text with within=<container ref> or computer_snapshot root=<container ref> to dig into exactly that container — a deep pass over a whole big tree burns both latency and tokens. If the tree stops at a Pane with nothing inside, try view="raw": ControlView hides plumbing elements that raw exposes.',
47
47
  parameters: {
48
48
  windowId: { ...STR, required: true, description: 'windowId from computer_windows' },
49
49
  controlType: { ...STR, description: 'Keep only these control types, e.g. "Button,Edit,MenuItem"' },
50
50
  nameContains: { ...STR, description: 'Keep only elements whose name contains this text' },
51
51
  includeOffscreen: { ...BOOL, description: 'Include offscreen elements (default false)' },
52
- depth: { ...INT, description: 'Max tree depth to walk. Omit = worker default 30 (near-full depth, not infinite). Recommended rhythm: depth=4-5 for a skeleton pass on a large window, then find_text into the located container or raise depth/maxNodes to dig into it.' },
52
+ depth: { ...INT, description: 'Max tree depth to walk. Omit = worker default 30 (near-full depth, not infinite). Recommended rhythm: depth=4-5 for a skeleton pass on a large window, then root=<ref> or find_text within=<ref> to dig into the located container.' },
53
53
  maxNodes: { ...INT, description: 'Node budget for one snapshot (default 200). Raise it only when a truncated tree actually hid the control you need.' },
54
+ view: { type: 'string', enum: ['control', 'raw', 'content'], description: 'Which UIA view to walk. control (default) = the curated tree providers publish for assistive tech; raw = every element including the plumbing panes ControlView hides (often 3-10x more nodes, walker-paced, so keep depth/maxNodes tight); content = content elements only.' },
55
+ root: { ...STR, description: 'Optional ref to walk only that element\'s subtree. Refs minted by the pass join the current revision, so a skeleton snapshot stays usable. This is the cheap way to open one container: root=<container ref> instead of raising depth over the whole window.' },
54
56
  compact: { ...BOOL, description: 'Tighter rendering: shorter names and values. Use on large trees you are only scanning.' },
55
57
  },
56
58
  output: { schema: STR, render: (_args, value) => text(value) },
@@ -67,6 +69,8 @@ export function registerObserve(d) {
67
69
  // Pass-through: JSON.stringify drops the key when depth is omitted, so the worker keeps
68
70
  // its own default (maxDepth=30) — an omitted argument changes nothing downstream.
69
71
  maxDepth: args.depth,
72
+ view: args.view,
73
+ root: args.root,
70
74
  filter: {
71
75
  controlType: args.controlType,
72
76
  nameContains: args.nameContains,
@@ -76,7 +80,14 @@ export function registerObserve(d) {
76
80
  const nodes = result.nodes ?? [];
77
81
  store.setTree(nodes, { windowId: args.windowId, revision: result.revision });
78
82
  store.setTarget(windowOf(store, args.windowId) ?? { windowId: args.windowId });
79
- const head = `窗口 ${args.windowId} 第 ${result.revision} 版:${nodes.length} 个元素${result.truncated === true ? '(已截断——收紧过滤条件、用 find_text 定位、提高 maxNodes,或先浅 depth=4-5 看骨架再局部深挖)' : ''}`;
83
+ // Say which tree this actually is. A raw-view pass and a subtree pass read completely
84
+ // differently from a full control-view snapshot, and a model that does not know which one it
85
+ // holds mis-reads "only 8 elements" as "this window has 8 elements".
86
+ const scopeNote = [
87
+ result.subtree === true ? `子树 root=${result.rootRef ?? args.root}` : '',
88
+ result.view && result.view !== 'control' ? `视图=${result.view}` : '',
89
+ ].filter(Boolean).join(',');
90
+ const head = `窗口 ${args.windowId} 第 ${result.revision} 版:${nodes.length} 个元素${scopeNote ? `(${scopeNote})` : ''}${result.truncated === true ? '(已截断——收紧过滤条件、用 find_text 的 within 定位、用 root 深挖子容器、提高 maxNodes/深 depth,或先浅 depth=4-5 看骨架)' : ''}`;
80
91
  // 位置元数据(前台/焦点/采集耗时):动作后下一次观察的焦点变化即零成本「动作生效证据」,
81
92
  // 焦点不在目标窗时附一句修正指引。全部为 advisory 字段,worker 探测失败时不渲染。
82
93
  // 底部这一行是提示注入防线:屏幕上的任何文本都只是被观察的数据(聊天、网页、文档都可能
@@ -88,11 +99,12 @@ export function registerObserve(d) {
88
99
 
89
100
  d.disposers.push(register(defineTool({
90
101
  name: 'computer_find_text',
91
- description: 'Find elements by visible text in one window WITHOUT pulling the whole tree: returns each match with its clickable screen center and a `by` descriptor. Use it to locate one control in a big window (a full snapshot would be huge), to get coordinates for computer_click, or to build computer_run steps whose `by` survives layout drift. This is the named command the click guidance refers to ("find_text center"). Cost note: it enumerates the window\'s whole element tree (about 1-3 ms per element), so on a window with thousands of elements prefer a specific text fragment; a budget/max overrun returns the collected hits marked truncated with the total match count.',
102
+ description: 'Find elements by visible text in one window (or inside one container) WITHOUT pulling the whole tree: returns each match with its clickable screen center and a `by` descriptor. Use it to locate one control in a big window (a full snapshot would be huge), to get coordinates for computer_click, or to build computer_run steps whose `by` survives layout drift. This is the named command the click guidance refers to ("find_text center"). Pass within=<container ref> to search only that subtree — that is what turns a shallow skeleton pass into a cheap drill-down. Cost note: it enumerates the whole element tree of the scope (about 1-3 ms per element), so on a window with thousands of elements prefer a specific text fragment or a within scope; a budget/max overrun returns the collected hits marked truncated with the total match count.',
92
103
  parameters: {
93
104
  windowId: { ...STR, required: true, description: 'windowId from computer_windows' },
94
105
  text: { ...STR, required: true, description: 'text to look for in element names/values' },
95
106
  exact: { ...BOOL, description: 'exact match instead of substring (default false)' },
107
+ within: { ...STR, description: 'Optional ref: search only that element\'s subtree (the container a skeleton snapshot located). Cheaper and more precise than scanning the whole window.' },
96
108
  max: { ...INT, description: 'max matches to return (default 60)' },
97
109
  },
98
110
  output: { schema: STR, render: (_args, value) => text(value) },
@@ -105,14 +117,18 @@ export function registerObserve(d) {
105
117
  windowId: args.windowId,
106
118
  text: text0,
107
119
  exact: args.exact === true,
120
+ within: args.within,
108
121
  max: args.max,
109
122
  });
110
123
  const matches = result.matches ?? [];
124
+ // The scope belongs in every reply, including the zero-hit one: "扫描 4 个元素,没有命中" reads
125
+ // as "the text does not exist" unless the line also says the search only covered one container.
126
+ const scopeText = result.within ? `(范围 within=${result.within} 的子树)` : '';
111
127
  if (matches.length === 0) {
112
128
  const zeroTail = result.truncated === true
113
129
  ? '(注意:搜索在请求预算内没有扫完整棵树,已有命中已随截断丢弃——收紧 text、换更独特的片段,或分窗口再搜)'
114
130
  : '';
115
- return `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素:没有包含 "${str(text0, 40)}" 的元素${args.exact === true ? '(精确匹配模式)' : ''}${zeroTail}`;
131
+ return `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素${scopeText}:没有包含 "${str(text0, 40)}" 的元素${args.exact === true ? '(精确匹配模式)' : ''}${zeroTail}`;
116
132
  }
117
133
  // Ranking, not just filtering. Searching "插件" in this very window returns the window's own
118
134
  // Pane and Document first — both carry the title, both are 1941x1243, and clicking either just
@@ -156,7 +172,7 @@ export function registerObserve(d) {
156
172
  const refStr = m.ref ? ` ref=${m.ref}` : '';
157
173
  return `${i + 1}. ${m.controlType} "${str(m.name, 48)}" 中心=(${m.center?.x},${m.center?.y})${refStr}${actStr}${m.className ? ` class=${str(m.className, 24)}` : ''}${flags ? ` ${flags}` : ''}${hint}${twinHint} by=${JSON.stringify(m.by)}`;
158
174
  });
159
- const head = `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素,命中 ${matches.length} 个"${str(text0, 40)}"${args.exact === true ? '(精确)' : ''}(可见命令元素在前,容器/侧栏行/屏外元素在后):`;
175
+ const head = `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素${scopeText},命中 ${matches.length} 个"${str(text0, 40)}"${args.exact === true ? '(精确)' : ''}(可见命令元素在前,容器/侧栏行/屏外元素在后):`;
160
176
  // Observation parity with snapshot's truncation report: the worker now counts EVERY match
161
177
  // (matchedTotal) and flags max/budget cuts, so silently dropped hits become visible. The
162
178
  // ranking happens on the returned subset, so dropped hits cannot be rescued here — the