dsh-native-uia 0.4.0 → 0.6.1

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.
@@ -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',
@@ -57,7 +57,7 @@ const ACTION_COMMANDS = new Set([
57
57
  * This is a whitelist on purpose. Treating "not an action" as "an observation" looked equivalent
58
58
  * and was not: the Esc watchdog polls `escape_pressed` every 40 ms, so the else-branch fired a
59
59
  * beat ~25×/s. Each beat re-syncs the HWND, re-positions the pill and re-renders its text while
60
- * the pulse timer is pushing new opacity values every 100 ms, and the two interleave into a
60
+ * the pulse timer is pushing new opacity values on every tick (~30 Hz), and the two interleave into a
61
61
  * visible flicker on the ring. Internal probes are not observations and must stay silent here.
62
62
  */
63
63
  const OBSERVE_COMMANDS = new Set([