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.
@@ -17,7 +17,6 @@ export function registerPointer(d) {
17
17
  if (await ensureArmed(exec?.agent, exec?.signal)) return true;
18
18
  return DISARMED_MSG;
19
19
  };
20
- const GATE_MSG = DISARMED_MSG;
21
20
  // One normaliser for every tool that takes held keys: array or "ctrl+shift" string both work, and
22
21
  // the worker re-validates (an unknown modifier becomes bad_arg there, not a silent no-op here).
23
22
  const normMods = (value) => {
@@ -40,15 +39,36 @@ export function registerPointer(d) {
40
39
  return classify({ action: 'invoke', descriptor: { title: under?.title, className: under?.class ?? under?.hitClass, name: under?.app } });
41
40
  };
42
41
  const pointArgs = (args) => ({ x: Number(args.x), y: Number(args.y) });
43
- const needPoint = (args) => (typeof args.x !== 'number' || typeof args.y !== 'number' ? '需要数值坐标 x、y(物理像素,和快照 rect / find_text center 同一坐标空间)' : null);
42
+ // A ref is a better pointer target than arithmetic: the centre comes from the element's own rect,
43
+ // read fresh through the worker's describe (Resolve-Ref re-binds and refuses a stale ref), so a
44
+ // row that moved or a list that scrolled cannot turn into a click at the old coordinates. x/y
45
+ // stays for surfaces with no element at all (canvas, OCR hit).
46
+ const refPoint = async (ref) => {
47
+ const d = await worker.call('describe', { ref: String(ref) });
48
+ const r = d?.rect;
49
+ if (!r || !(r.w > 0) || !(r.h > 0)) return null;
50
+ return { x: Math.round(r.x + r.w / 2), y: Math.round(r.y + r.h / 2), controlType: d.controlType, name: d.name };
51
+ };
52
+ const resolvePoint = async (args) => {
53
+ if (args.ref !== undefined && String(args.ref) !== '') {
54
+ const p = await refPoint(args.ref);
55
+ if (p === null) return { error: `ref ${args.ref} 没有可点的矩形(元素已不可见或没有布局框):改用 x,y,或重新 computer_snapshot 后再操作` };
56
+ return p;
57
+ }
58
+ if (typeof args.x !== 'number' || typeof args.y !== 'number') {
59
+ return { error: '需要 ref(推荐,中心由元素 rect 现算)或数值坐标 x、y(物理像素,和快照 rect / find_text center 同一坐标空间)' };
60
+ }
61
+ return pointArgs(args);
62
+ };
44
63
 
45
64
 
46
65
  d.disposers.push(register(defineTool({
47
66
  name: 'computer_click',
48
- description: 'Move the real cursor to a physical (x,y) and click. Use for apps whose controls are not in the UIA tree (self-drawn UIs like WeChat) or when you want the action to be visible. Coordinates come from a snapshot element rect center, find_text center, or a screenshot you can see. windowId is required and the click is refused if that window is not actually under the point.',
67
+ description: 'Move the real cursor and click. Target it EITHER with ref (preferred: the centre is computed from the element\'s own rect on this call, so a moved row or a scrolled list still lands correctly) OR with physical (x,y) for surfaces that have no element (canvas, OCR hit, screenshot). Use it for self-drawn UIs (WeChat), for right/double/triple clicks, or when the action must be visible. windowId is required and the click is refused if that window is not actually under the point.',
49
68
  parameters: {
50
- windowId: { ...STR, required: true, description: 'The window you expect to be under (x,y); used as the target gate' },
51
- x: { ...INT, required: true }, y: { ...INT, required: true },
69
+ windowId: { ...STR, required: true, description: 'The window you expect to be under the point; used as the target gate' },
70
+ ref: { ...STR, description: 'Element ref from the newest snapshot of this window — alternative to x,y; the (x,y) is derived from its current rect' },
71
+ x: { ...INT, description: 'physical x (omit when passing ref)' }, y: { ...INT, description: 'physical y (omit when passing ref)' },
52
72
  button: { type: 'string', enum: ['left', 'right', 'middle'], description: 'default left' },
53
73
  double: { ...BOOL, description: 'double-click' },
54
74
  triple: { ...BOOL, description: 'triple-click (select a paragraph / whole line); implies not double' },
@@ -59,31 +79,35 @@ export function registerPointer(d) {
59
79
  timeoutMs: 30000,
60
80
  async execute(args, exec) {
61
81
  await aborted(exec.signal);
62
- if (!(await gate(exec))) return GATE_MSG;
63
- const bad = needPoint(args); if (bad) return bad;
64
- const { x, y } = pointArgs(args);
82
+ if (!(await gate(exec))) return DISARMED_MSG;
83
+ const p = await resolvePoint(args);
84
+ if (p.error) return p.error;
85
+ const { x, y } = p;
65
86
  const outcome = await classifyPoint(x, y);
66
87
  if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_click', ...args });
67
88
  const r = await worker.call('pointer_click', { x, y, button: args.button, double: args.double, triple: args.triple, mods: normMods(args.modifiers), durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
68
89
  store.actionDone(1);
69
- store.step({ label: `点击 (${x},${y})`, kind: 'pointer', status: 'passed', ms: r.ms, detail: `via=${r.via} under=${str(r.under?.title ?? r.under?.class, 40)}` });
90
+ store.step({ label: `点击 ${args.ref ? args.ref : ''}(${x},${y})`, kind: 'pointer', status: 'passed', ms: r.ms, detail: `via=${r.via} under=${str(r.under?.title ?? r.under?.class, 40)}` });
70
91
  const held = r.mods ? ` 按住 ${r.mods}` : '';
71
92
  const kind = r.triple ? ' 三击' : r.double ? ' 双击' : '';
93
+ const on = args.ref ? ` ${args.ref}${p.name ? `「${str(p.name, 30)}」` : ''}` : '';
72
94
  // Same point, same button, over and over: the third repeat is a stuck loop, not a retry.
73
95
  const tally = store.noteAttempt(`click:${x},${y}:${args.button ?? 'left'}`, true);
74
96
  const stuck = stuckNote('repeat', tally.total);
75
- return `已点击 (${x},${y}) ${args.button || 'left'}${kind}${held},耗时 ${r.ms}ms,落点窗口 "${str(r.under?.title ?? '', 50)}"${stuck}`;
97
+ return `已点击${on} (${x},${y}) ${args.button || 'left'}${kind}${held},耗时 ${r.ms}ms,落点窗口 "${str(r.under?.title ?? '', 50)}"${stuck}`;
76
98
  },
77
99
  })));
78
100
 
79
101
 
80
102
  d.disposers.push(register(defineTool({
81
103
  name: 'computer_drag',
82
- description: 'Press at (fromX,fromY), move to (toX,toY), release — for sliders, repositioning, marquee-select. Both endpoints must be inside windowId.',
104
+ description: 'Press at a start point, move to an end point, release — for sliders, repositioning, marquee-select. Either point can be a ref (centre derived from its current rect) or explicit physical coordinates; both must be inside windowId.',
83
105
  parameters: {
84
106
  windowId: { ...STR, required: true },
85
- fromX: { ...INT, required: true }, fromY: { ...INT, required: true },
86
- toX: { ...INT, required: true }, toY: { ...INT, required: true },
107
+ ref: { ...STR, description: 'ref to press at (alternative to fromX/fromY)' },
108
+ fromX: { ...INT, description: 'physical start x (omit when passing ref)' }, fromY: { ...INT, description: 'physical start y (omit when passing ref)' },
109
+ toRef: { ...STR, description: 'ref to release at (alternative to toX/toY)' },
110
+ toX: { ...INT, description: 'physical end x (omit when passing toRef)' }, toY: { ...INT, description: 'physical end y (omit when passing toRef)' },
87
111
  button: { type: 'string', enum: ['left', 'right', 'middle'] },
88
112
  durationMs: { ...INT },
89
113
  },
@@ -91,25 +115,28 @@ export function registerPointer(d) {
91
115
  timeoutMs: 30000,
92
116
  async execute(args, exec) {
93
117
  await aborted(exec.signal);
94
- if (!(await gate(exec))) return GATE_MSG;
95
- const nums = [args.fromX, args.fromY, args.toX, args.toY];
96
- if (nums.some((n) => typeof n !== 'number')) return '需要数值 fromX/fromY/toX/toY';
97
- const outcome = await classifyPoint(args.fromX, args.fromY);
118
+ if (!(await gate(exec))) return DISARMED_MSG;
119
+ const from = await resolvePoint({ ref: args.ref, x: args.fromX, y: args.fromY });
120
+ if (from.error) return `起点:${from.error}`;
121
+ const to = await resolvePoint({ ref: args.toRef, x: args.toX, y: args.toY });
122
+ if (to.error) return `终点:${to.error}`;
123
+ const outcome = await classifyPoint(from.x, from.y);
98
124
  if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_drag', ...args });
99
- const r = await worker.call('pointer_drag', { from: { x: args.fromX, y: args.fromY }, to: { x: args.toX, y: args.toY }, button: args.button, durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
125
+ const r = await worker.call('pointer_drag', { from: { x: from.x, y: from.y }, to: { x: to.x, y: to.y }, button: args.button, durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
100
126
  store.actionDone(1);
101
- store.step({ label: `拖拽 (${args.fromX},${args.fromY})→(${args.toX},${args.toY})`, kind: 'pointer', status: 'passed', ms: r.ms });
102
- return `已拖拽 (${args.fromX},${args.fromY}) → (${args.toX},${args.toY}),耗时 ${r.ms ?? '?'}ms`;
127
+ store.step({ label: `拖拽 (${from.x},${from.y})→(${to.x},${to.y})`, kind: 'pointer', status: 'passed', ms: r.ms });
128
+ return `已拖拽 (${from.x},${from.y}) → (${to.x},${to.y}),耗时 ${r.ms ?? '?'}ms`;
103
129
  },
104
130
  })));
105
131
 
106
132
 
107
133
  d.disposers.push(register(defineTool({
108
134
  name: 'computer_scroll',
109
- description: 'Scroll the mouse wheel at a physical (x,y): direction up|down|left|right, clicks = notches (default 3). windowId gates the point.',
135
+ description: 'Scroll the mouse wheel at a point: direction up|down|left|right, clicks = notches (default 3). The point is either a ref (its rect centre) or physical (x,y); windowId gates it.',
110
136
  parameters: {
111
137
  windowId: { ...STR, required: true },
112
- x: { ...INT, required: true }, y: { ...INT, required: true },
138
+ ref: { ...STR, description: 'ref whose centre to scroll over (alternative to x,y)' },
139
+ x: { ...INT, description: 'physical x (omit when passing ref)' }, y: { ...INT, description: 'physical y (omit when passing ref)' },
113
140
  direction: { type: 'string', enum: ['up', 'down', 'left', 'right'] },
114
141
  clicks: { ...INT, description: 'wheel notches, 1..50' },
115
142
  modifiers: { type: 'array', items: { type: 'string' }, description: 'held during the scroll: ["ctrl"] = zoom, ["shift"] = horizontal pan' },
@@ -118,9 +145,10 @@ export function registerPointer(d) {
118
145
  timeoutMs: 20000,
119
146
  async execute(args, exec) {
120
147
  await aborted(exec.signal);
121
- if (!(await gate(exec))) return GATE_MSG;
122
- const bad = needPoint(args); if (bad) return bad;
123
- const { x, y } = pointArgs(args);
148
+ if (!(await gate(exec))) return DISARMED_MSG;
149
+ const p = await resolvePoint(args);
150
+ if (p.error) return p.error;
151
+ const { x, y } = p;
124
152
  const outcome = await classifyPoint(x, y);
125
153
  if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_scroll', ...args });
126
154
  const r = await worker.call('pointer_scroll', { x, y, direction: args.direction, clicks: args.clicks, mods: normMods(args.modifiers), expect: { windowId: String(args.windowId) } });
@@ -144,7 +172,7 @@ export function registerPointer(d) {
144
172
  timeoutMs: 20000,
145
173
  async execute(args, exec) {
146
174
  await aborted(exec.signal);
147
- if (!(await gate(exec))) return GATE_MSG;
175
+ if (!(await gate(exec))) return DISARMED_MSG;
148
176
  const t = String(args.text ?? '');
149
177
  if (t === '') return 'text 为空';
150
178
  const via = args.via === 'clipboard' ? 'clipboard' : 'keyboard';
@@ -172,7 +200,7 @@ export function registerPointer(d) {
172
200
  timeoutMs: 15000,
173
201
  async execute(args, exec) {
174
202
  await aborted(exec.signal);
175
- if (!(await gate(exec))) return GATE_MSG;
203
+ if (!(await gate(exec))) return DISARMED_MSG;
176
204
  const combo = String(args.keys ?? '').trim().toLowerCase();
177
205
  if (combo === '') return 'keys 为空';
178
206
  // The combo has no UIA descriptor to feed the name table, so classification runs on the combo
@@ -198,9 +226,10 @@ export function registerPointer(d) {
198
226
  name: 'computer_mouse',
199
227
  description: 'Everything a click cannot express: hover (action:"move" and release nothing), press-and-hold across calls (action:"down" then a later action:"up" — marquee select, staged drag, holding a scrollbar), and reading where the cursor is (action:"position"). down/up act at the current cursor; the store tracks the pairing so a dangling press is visible.',
200
228
  parameters: {
201
- action: { type: 'string', enum: ['move', 'down', 'up', 'position'], required: true, description: 'move = hover to (x,y); down/up = press or release a button at the current cursor; position = read the cursor' },
202
- x: { ...INT, description: 'move only: physical x' },
203
- y: { ...INT, description: 'move only: physical y' },
229
+ action: { type: 'string', enum: ['move', 'down', 'up', 'position'], required: true, description: 'move = hover to a ref or (x,y); down/up = press or release a button at the current cursor; position = read the cursor' },
230
+ ref: { ...STR, description: 'move only: hover this element (its rect centre) instead of x,y' },
231
+ x: { ...INT, description: 'move only: physical x (omit when passing ref)' },
232
+ y: { ...INT, description: 'move only: physical y (omit when passing ref)' },
204
233
  button: { type: 'string', enum: ['left', 'right', 'middle'], description: 'down/up only, default left' },
205
234
  durationMs: { ...INT, description: 'move only: glide time (default auto by distance)' },
206
235
  windowId: { ...STR, description: 'gates the point: the window that must be under the cursor / destination' },
@@ -209,7 +238,7 @@ export function registerPointer(d) {
209
238
  timeoutMs: 30000,
210
239
  async execute(args, exec) {
211
240
  await aborted(exec.signal);
212
- if (!(await gate(exec))) return GATE_MSG;
241
+ if (!(await gate(exec))) return DISARMED_MSG;
213
242
  const action = String(args.action ?? 'position').toLowerCase();
214
243
  // Every cursor-moving/pressing branch needs the target gate. The worker refuses an unnamed
215
244
  // target on purpose (that is what stops a stray physical click), so say so here instead of
@@ -220,8 +249,9 @@ export function registerPointer(d) {
220
249
  : null;
221
250
  if (action === 'move') {
222
251
  if (targetNeeded) return targetNeeded;
223
- const bad = needPoint(args); if (bad) return bad;
224
- const { x, y } = pointArgs(args);
252
+ const p = await resolvePoint(args);
253
+ if (p.error) return p.error;
254
+ const { x, y } = p;
225
255
  const outcome = await classifyPoint(x, y);
226
256
  if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_mouse', ...args });
227
257
  const r = await worker.call('pointer_mouse', { action, x, y, durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
@@ -266,7 +296,7 @@ export function registerPointer(d) {
266
296
  const op = String(args.op ?? '').toLowerCase();
267
297
  // write/clear mutate shared state, so they pass the permission gate; read stays ungated (it
268
298
  // already has its own stricter ctrl+c precondition).
269
- if (op !== 'read' && !(await gate(exec))) return GATE_MSG;
299
+ if (op !== 'read' && !(await gate(exec))) return DISARMED_MSG;
270
300
  if (op === 'read') {
271
301
  if (!store.ctrlCAt) {
272
302
  return '剪贴板读取被拦:本轮还没有自己按过 ctrl+c。先用 computer_key keys:"ctrl+c" 复制目标内容(或让用户自己复制后由用户告知),再读;这样读到的才是本轮的产物,而不是用户之前的剪贴板。';
@@ -295,4 +325,4 @@ export function registerPointer(d) {
295
325
  },
296
326
  })));
297
327
 
298
- }
328
+ }
@@ -13,13 +13,15 @@ export function renderWindows(windows) {
13
13
  // verbs computer_act accepts. Dropping the rest cut the rendered tree by roughly a third without
14
14
  // removing a single actionable fact — the model reads a smaller tree and finds the control faster.
15
15
  export const ACTIONABLE = new Set([
16
- 'Invoke', 'Value', 'Toggle', 'SelectionItem', 'ExpandCollapse', 'RangeValue', 'Scroll', 'Text',
16
+ 'Invoke', 'Value', 'Toggle', 'SelectionItem', 'ExpandCollapse', 'RangeValue', 'Scroll', 'ScrollItem', 'Text',
17
17
  'GridItem', 'Selection', 'ItemContainer',
18
18
  ]);
19
19
 
20
20
  // The verbs a model can actually put in computer_act; narrower than ACTIONABLE, which also carries
21
21
  // read-only patterns. A node listed here is one the model can act on without a second look.
22
- export const ACT_VERBS = new Set(['Invoke', 'Value', 'Toggle', 'SelectionItem', 'ExpandCollapse', 'RangeValue', 'Scroll']);
22
+ // RangeValue and ScrollItem joined when set_range / scroll_to became real verbs: before that they
23
+ // would have promised actions that did not exist.
24
+ export const ACT_VERBS = new Set(['Invoke', 'Value', 'Toggle', 'SelectionItem', 'ExpandCollapse', 'Scroll', 'RangeValue', 'ScrollItem']);
23
25
 
24
26
  /**
25
27
  * A one-line map of what is actionable, printed before the tree.
@@ -45,6 +47,35 @@ export function renderActionables(nodes, max = 24) {
45
47
  return `可操作元素 ${acts.length} 个(@=中心坐标,同名时可直接填进 by.nearPoint 消歧):${shown.join('、')}${rest}\n`;
46
48
  }
47
49
 
50
+ /**
51
+ * The node's own state, in the same line as the node.
52
+ *
53
+ * Before this, a snapshot carried one string per node (`value`), so a checked and an unchecked
54
+ * checkbox rendered identically, a selected tab looked like any other tab, an expanded tree node
55
+ * and a collapsed one were the same row, and a slider at 40% said "40" with no range to judge it
56
+ * against. These come from the worker's cached patterns, so they cost no extra round-trip.
57
+ */
58
+ function stateText(st) {
59
+ if (!st || typeof st !== 'object') return '';
60
+ const bits = [];
61
+ if (st.toggle) bits.push(String(st.toggle));
62
+ if (st.selected === true) bits.push('选中');
63
+ if (st.expanded) bits.push(String(st.expanded));
64
+ if (st.range && Number.isFinite(Number(st.range.value))) {
65
+ const r = st.range;
66
+ const range = Number.isFinite(Number(r.min)) && Number.isFinite(Number(r.max))
67
+ ? `/${Math.round(Number(r.min))}-${Math.round(Number(r.max))}`
68
+ : '';
69
+ bits.push(`${Math.round(Number(r.value))}${range}`);
70
+ }
71
+ if (st.scroll) {
72
+ const axis = (v) => (Number(v) >= 0 ? `${Math.round(Number(v))}%` : '-');
73
+ bits.push(`滚动 ${axis(st.scroll.h)}/${axis(st.scroll.v)}`);
74
+ }
75
+ if (bits.length === 0) return '';
76
+ return ` {${bits.join(' ')}}`;
77
+ }
78
+
48
79
  export function renderTree(nodes, { compact = false, elide = true } = {}) {
49
80
  if (nodes.length === 0) return '快照返回 0 个元素';
50
81
  const shown = elide ? elideRedundantContainers(nodes) : nodes;
@@ -56,10 +87,17 @@ export function renderTree(nodes, { compact = false, elide = true } = {}) {
56
87
  // `disabled` and `offscreen` are the two flags that change whether acting makes sense; the
57
88
  // compact form still carries them because they are decision-relevant, unlike class names.
58
89
  const flags = [n.enabled === false ? 'disabled' : '', n.isOffscreen === true ? 'offscreen' : ''].filter(Boolean).join(' ');
59
- const value = n.value === undefined || n.value === '' ? '' : ` val="${str(n.value, compact ? 24 : 40)}"`;
90
+ const st = stateText(n.state);
91
+ // A toggle/expand node's state already IS its value (the worker reads ToggleState as the
92
+ // value); printing both would make one fact look like two.
93
+ const value = n.value === undefined || n.value === '' || (st && (n.state?.toggle === n.value || n.state?.expanded === n.value))
94
+ ? ''
95
+ : ` val="${str(n.value, compact ? 24 : 40)}"`;
60
96
  const pat = acts.length === 0 ? '' : ` [${acts.join(',')}]`;
61
97
  const name = str(n.name, compact ? 32 : 48);
62
- return `${pad}${n.ref} ${n.controlType} "${name}"${value}${pat}${flags ? ` ${flags}` : ''}`;
98
+ // Where the walk stopped, per node: this is the exact element to drill into with root=<ref>.
99
+ const cut = n.cut === true ? ' [cut]' : '';
100
+ return `${pad}${n.ref} ${n.controlType} "${name}"${value}${st}${pat}${flags ? ` ${flags}` : ''}${cut}`;
63
101
  })
64
102
  .join('\n');
65
103
  }
@@ -99,10 +137,9 @@ export function renderEffect(r) {
99
137
  return r.before === r.after ? ` 效果=属性未变(已送达${tip})` : ' 效果=属性已变';
100
138
  }
101
139
 
102
- // Single source for the not_executed wording: the worker only ships the status (uia-worker.ps1
103
- // keeps an English placeholder because this file is parsed as ANSI there), and BOTH batch tools
104
- // render the tail through renderResults — one constant here keeps computer_run and computer_replay
105
- // from drifting apart.
140
+ // Single source for the not_executed wording: the worker ships only the status, and BOTH batch
141
+ // tools render the tail through renderResults — one constant here keeps computer_run and
142
+ // computer_replay from drifting apart.
106
143
  export const NOT_EXECUTED_TEXT = '未执行:前序步骤失败/被取消';
107
144
 
108
145
  export function renderResults(results, performed) {
@@ -64,17 +64,14 @@ export function registerTools(ctx, { worker, store, dataDir, owned, finishRun: f
64
64
  reason: `策略拒绝:${outcome.refusal}`,
65
65
  raw: extra ?? null,
66
66
  });
67
- // The confirm family is not banned, it is held for a person: saying "禁止" there would tell the
68
- // model the action is impossible instead of telling it how the action can legitimately happen.
69
- if (outcome.category === 'confirm') {
70
- return `[已拦截 ${entry.id}] 「${outcome.refusal}」要先问过在场的人。${outcome.advice}`;
71
- }
67
+ // One wording for every refusal: the policy has no interactive verdict, so a refusal always
68
+ // means "this will not happen through this plugin".
72
69
  return `[已拦截 ${entry.id}] ${outcome.refusal} 被本插件策略禁止。${outcome.advice}`;
73
70
  };
74
71
 
75
72
  /**
76
73
  * One registration point, so "did the model touch the desktop?" is answered once for all
77
- * eighteen tools instead of in every execute(). The wrapper keeps the original `this`, the
74
+ * twenty-one tools instead of in every execute(). The wrapper keeps the original `this`, the
78
75
  * marker that `defineTool` puts on the definition, and the return value; it only observes.
79
76
  */
80
77
  const register = (definition) => {
package/src/tools/ocr.js CHANGED
@@ -10,7 +10,7 @@ export const isCjk = (ch) => ch !== undefined && ch !== '' && CJK.test(ch);
10
10
  * so one target is one phrase.
11
11
  *
12
12
  * Grouping is deliberately conservative: same line (>=60% vertical overlap), horizontal gap no
13
- * larger than 1.6 character widths (so separate columns never merge), and only the few recent
13
+ * larger than 2.0 character widths (so separate columns never merge), and only the few recent
14
14
  * lines are considered (so interleaved baselines cannot chain unrelated rows together).
15
15
  */
16
16
  export function groupOcrWords(words, { maxGapFactor = 2.0, lineOverlap = 0.6 } = {}) {
@@ -15,10 +15,16 @@ export async function saveRecipe(dir, recipe) {
15
15
  // removed them, and each carries the full step list. Captures were already pruned to the newest
16
16
  // twelve; do the same for recipes so a long-lived install cannot fill the disk. Best-effort:
17
17
  // a failed prune must never fail the batch the user asked for.
18
+ //
19
+ // Ordered by the timestamp in the name, NOT lexicographically: names are `<slug>-<epoch>`, so a
20
+ // plain string sort groups by slug and would delete the newest recipe of one app while keeping
21
+ // the oldest of another.
18
22
  try {
19
- const names = (await readdir(dir)).filter((n) => n.endsWith('.json')).sort();
20
23
  const keep = Math.max(1, Number(process.env.DSH_NATIVE_UIA_RECIPE_KEEP ?? 50));
21
- for (const stale of names.slice(0, Math.max(0, names.length - keep))) {
24
+ const names = (await readdir(dir)).filter((n) => n.endsWith('.json'));
25
+ const stamp = (n) => Number(/(\d{10,})\.json$/.exec(n)?.[1] ?? 0);
26
+ names.sort((a, b) => stamp(b) - stamp(a));
27
+ for (const stale of names.slice(keep)) {
22
28
  try { await unlink(join(dir, stale)); } catch { /* already gone */ }
23
29
  }
24
30
  } catch { /* readdir/unlink failed; the recipe is still saved */ }
@@ -40,5 +46,4 @@ export async function loadRecipe(dir, name) {
40
46
  } catch {
41
47
  return null;
42
48
  }
43
- }
44
-
49
+ }
@@ -34,10 +34,10 @@ export class ReadOnlyError extends Error {
34
34
  }
35
35
  }
36
36
 
37
- /** Every command that can put input on the desktop, so the control page switches
38
- * are enforced here rather than remembered per tool. The pixel/keyboard commands belong
39
- * here too: they move the real cursor and type, so they must claim the activity overlay and
40
- * honour the kill latch exactly like act/commit_batch do. */
37
+ /** Every command that can put input on the desktop, so the session gates (read-only, the
38
+ * permission card, the kill latch) are enforced here rather than remembered per tool. The
39
+ * pixel/keyboard commands belong here too: they move the real cursor and type, so they must
40
+ * claim the activity overlay and honour the kill latch exactly like act/commit_batch do. */
41
41
  const ACTION_COMMANDS = new Set([
42
42
  'act', 'commit_batch', 'launch', 'close_window',
43
43
  'pointer_click', 'pointer_drag', 'pointer_scroll', 'pointer_mouse', 'type_text', 'key', 'window_action',
@@ -1,8 +1,8 @@
1
- # 02-uia.ps1 -- UIA plumbing: patterns, rects, process names
2
- #
3
- # Part of worker/uia-worker.ps1, dot-sourced by it in the order scripts/lib/sources.mjs declares.
4
- # It lives in its own file only so a section can be read without scrolling the whole RPC server.
5
- # Dot-sourcing shares the entry's script scope, so a helper here may use $script:W and may call
1
+ # 02-uia.ps1 -- UIA plumbing: patterns, rects, process names
2
+ #
3
+ # Part of worker/uia-worker.ps1, dot-sourced by it in the order scripts/lib/sources.mjs declares.
4
+ # It lives in its own file only so a section can be read without scrolling the whole RPC server.
5
+ # Dot-sourcing shares the entry's script scope, so a helper here may use $script:W and may call
6
6
  # any function from any other part: neighbour order is not a dependency.
7
7
  # ---------------------------------------------------------------- uiA plumbing
8
8
  $script:ctCache = @{}
@@ -100,7 +100,7 @@ function PatternsOf($el) {
100
100
  # (probe-verified: all exist; IsLegacyIAccessiblePatternAvailableProperty does not — there is no
101
101
  # managed wrapper type for that pattern, so it can neither be requested nor reported here, and
102
102
  # LegacyIAccessible is deliberately absent from a cached pattern list: the capability table
103
- # computer_act checks (tools.js NEEDED) never names it and the rendered tree filters patterns
103
+ # computer_act checks never names it and the rendered tree filters patterns
104
104
  # through ACTIONABLE, which never showed it either).
105
105
  $script:cachedPatProps = @(
106
106
  'IsDockPatternAvailableProperty', 'IsExpandCollapsePatternAvailableProperty', 'IsGridItemPatternAvailableProperty',
@@ -140,6 +140,9 @@ $patternTypes = @{
140
140
  Transform = [System.Windows.Automation.TransformPattern]
141
141
  Text = [System.Windows.Automation.TextPattern]
142
142
  GridItem = [System.Windows.Automation.GridItemPattern]
143
+ # ScrollItem only became useful with the scroll_to verb; before that its absence was invisible
144
+ # (nothing asked for it) and adding it would have been a dead table entry.
145
+ ScrollItem = [System.Windows.Automation.ScrollItemPattern]
143
146
  }
144
147
 
145
148
  function GetPattern($el, $name) {
@@ -1,8 +1,8 @@
1
- # 05-value.ps1 -- value/state reads and descriptor projection
2
- #
3
- # Part of worker/uia-worker.ps1, dot-sourced by it in the order scripts/lib/sources.mjs declares.
4
- # It lives in its own file only so a section can be read without scrolling the whole RPC server.
5
- # Dot-sourcing shares the entry's script scope, so a helper here may use $script:W and may call
1
+ # 05-value.ps1 -- value/state reads and descriptor projection
2
+ #
3
+ # Part of worker/uia-worker.ps1, dot-sourced by it in the order scripts/lib/sources.mjs declares.
4
+ # It lives in its own file only so a section can be read without scrolling the whole RPC server.
5
+ # Dot-sourcing shares the entry's script scope, so a helper here may use $script:W and may call
6
6
  # any function from any other part: neighbour order is not a dependency.
7
7
  # ---------------------------------------------------------------- values
8
8
  # Reads one value-bearing property from the element's CACHE (GetCachedPattern + pattern.Cached).
@@ -72,6 +72,111 @@ function Read-Value($el, $patterns, $refRec, $useCached) {
72
72
  return ''
73
73
  }
74
74
 
75
+ # ---------------------------------------------------------------- node state
76
+ # A snapshot used to hand the model ONE string per node (`value`), so every state-bearing control
77
+ # read the same: an unchecked checkbox and a checked one both said "Toggle", a selected tab said
78
+ # nothing, an expanded tree node said nothing, a slider at 40% said 40 without its range, and a
79
+ # scrolled list said nothing at all. The model then had to guess or drive blind.
80
+ #
81
+ # $useCached reads the state out of the CacheRequest the snapshot already materialised (no
82
+ # cross-process round-trip). Some providers — Explorer's shell items, several MSAA-bridged apps —
83
+ # answer the pattern lookup and then hand back an EMPTY cached struct; for those the caller may
84
+ # retry this function with $useCached=$false ONCE per node, which is a real round-trip and is
85
+ # therefore budgeted by the snapshot (see Build-SnapshotNode), not spent freely.
86
+ # Did the cached read leave a state we KNOW is readable on the table? Called before spending the
87
+ # one budgeted live read per node. Scroll is deliberately absent: a list that cannot scroll reports
88
+ # NoScroll on both axes and legitimately produces no `scroll` key, so demanding one would burn the
89
+ # whole budget on unscrollable nodes.
90
+ function State-Missing($patterns, $st) {
91
+ if ($null -eq $patterns -or $patterns.Count -eq 0) { return $false }
92
+ $want = @(
93
+ @{ pattern = 'Toggle'; key = 'toggle' },
94
+ @{ pattern = 'SelectionItem'; key = 'selected' },
95
+ @{ pattern = 'ExpandCollapse'; key = 'expanded' },
96
+ @{ pattern = 'RangeValue'; key = 'range' }
97
+ )
98
+ foreach ($w in $want) {
99
+ if ($patterns -contains $w.pattern) {
100
+ if ($null -eq $st -or -not $st.Contains($w.key)) { return $true }
101
+ }
102
+ }
103
+ return $false
104
+ }
105
+
106
+ function Get-StatePattern($el, $type, $useCached) {
107
+ if ($null -eq $el) { return $null }
108
+ try {
109
+ if ($useCached) { return $el.GetCachedPattern($type) }
110
+ return $el.GetCurrentPattern($type)
111
+ } catch { return $null }
112
+ }
113
+
114
+ function State-Of($el, $patterns, $useCached) {
115
+ if ($null -eq $el -or $null -eq $patterns -or $patterns.Count -eq 0) { return $null }
116
+ $st = [ordered]@{}
117
+ if ($patterns -contains 'Toggle') {
118
+ $c = $null
119
+ $p = Get-StatePattern $el ([System.Windows.Automation.TogglePattern]::Pattern) $useCached
120
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
121
+ if ($null -ne $c) {
122
+ # A provider can answer the lookup and still refuse the struct: the field then reads as '',
123
+ # and publishing `"expanded": ""` is worse than publishing nothing — it looks like a state
124
+ # called empty.
125
+ $sv = ''
126
+ try { $sv = [string]$c.ToggleState } catch { }
127
+ if ($sv -ne '') { $st['toggle'] = $sv }
128
+ }
129
+ }
130
+ if ($patterns -contains 'SelectionItem') {
131
+ $c = $null
132
+ $p = Get-StatePattern $el ([System.Windows.Automation.SelectionItemPattern]::Pattern) $useCached
133
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
134
+ if ($null -ne $c) { try { $st['selected'] = [bool]$c.IsSelected } catch { } }
135
+ }
136
+ if ($patterns -contains 'ExpandCollapse') {
137
+ $c = $null
138
+ $p = Get-StatePattern $el ([System.Windows.Automation.ExpandCollapsePattern]::Pattern) $useCached
139
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
140
+ if ($null -ne $c) {
141
+ $sv = ''
142
+ try { $sv = [string]$c.ExpandCollapseState } catch { }
143
+ if ($sv -ne '') { $st['expanded'] = $sv }
144
+ }
145
+ }
146
+ if ($patterns -contains 'RangeValue') {
147
+ $c = $null
148
+ $p = Get-StatePattern $el ([System.Windows.Automation.RangeValuePattern]::Pattern) $useCached
149
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
150
+ if ($null -ne $c) {
151
+ # Minimum/Maximum are what turn "40" into "40 of 0..100" — without them the model cannot tell
152
+ # a slider at 40% from one pinned at its floor.
153
+ $rv = [double]$c.Value
154
+ if (-not [double]::IsNaN($rv)) {
155
+ $st['range'] = @{ value = $rv; min = [double]$c.Minimum; max = [double]$c.Maximum }
156
+ }
157
+ }
158
+ }
159
+ if ($patterns -contains 'Scroll') {
160
+ $c = $null
161
+ $p = Get-StatePattern $el ([System.Windows.Automation.ScrollPattern]::Pattern) $useCached
162
+ if ($null -ne $p) { try { $c = if ($useCached) { $p.Cached } else { $p.Current } } catch { $c = $null } }
163
+ if ($null -ne $c) {
164
+ $h = [double]$c.HorizontalScrollPercent
165
+ $v = [double]$c.VerticalScrollPercent
166
+ # -1 is ScrollPattern.NoScroll: an axis that cannot move is a fact worth keeping only when the
167
+ # other axis can.
168
+ if ($h -ge 0 -or $v -ge 0) {
169
+ $st['scroll'] = @{
170
+ h = $(if ($h -ge 0) { [Math]::Round($h, 0) } else { -1 })
171
+ v = $(if ($v -ge 0) { [Math]::Round($v, 0) } else { -1 })
172
+ }
173
+ }
174
+ }
175
+ }
176
+ if ($st.Count -eq 0) { return $null }
177
+ return $st
178
+ }
179
+
75
180
  function SupportedActionOf($patterns) {
76
181
  if ($null -eq $patterns) { return 'focus' }
77
182
  if ($patterns -contains 'Invoke') { return 'invoke' }
@@ -135,7 +240,7 @@ function DescriptorOf($re, $live) {
135
240
  if ($v.Length -gt 200) { $d['valueTruncated'] = $true }
136
241
  }
137
242
  }
138
- # Attach the owning window so a saved recipe can rebind to it later. tools.js reads
243
+ # Attach the owning window so a saved recipe can rebind to it later. src/tools/defs/act.js reads
139
244
  # descriptors[0].ownerWindow to populate recipe.window; without it the recipe falls back to
140
245
  # the store's window list, which is empty for a batch taken before any computer_windows call,
141
246
  # and the recipe then replays with no windowId.