noracu 0.1.4 → 0.2.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.
- package/CHANGELOG.md +437 -0
- package/README.md +34 -22
- package/README.zh-CN.md +36 -24
- package/SECURITY.md +15 -8
- package/docs/architecture.md +58 -27
- package/docs/tools.md +45 -34
- package/docs/usage.md +180 -64
- package/imctl/README.md +16 -13
- package/imctl/pyproject.toml +1 -1
- package/imctl/src/imctl/__init__.py +1 -1
- package/imctl/src/imctl/cli.py +152 -38
- package/imctl/src/imctl/gestures.py +21 -25
- package/imctl/src/imctl/input.py +187 -50
- package/imctl/src/imctl/window.py +10 -3
- package/package.json +5 -4
- package/src/mac-ax.js +2494 -0
- package/src/server.mjs +1719 -483
package/src/mac-ax.js
ADDED
|
@@ -0,0 +1,2494 @@
|
|
|
1
|
+
// noracu macOS accessibility engine (JXA).
|
|
2
|
+
//
|
|
3
|
+
// Run: osascript -l JavaScript src/mac-ax.js (one JSON request on stdin → one JSON reply on stdout)
|
|
4
|
+
//
|
|
5
|
+
// It calls the macOS Accessibility C API (ApplicationServices: AXUIElement*) through the JXA
|
|
6
|
+
// Objective-C bridge instead of System Events: reading a Finder window of ~500 nodes takes about
|
|
7
|
+
// 0.15 s this way.
|
|
8
|
+
//
|
|
9
|
+
// Invariant 1 (argv / no code from data): this script is static. Every parameter, including any text
|
|
10
|
+
// to insert, arrives as JSON on stdin, so it never appears in a process list or inside script source.
|
|
11
|
+
//
|
|
12
|
+
// Element identity. An AXUIElement cannot outlive this process, so an element is described by evidence
|
|
13
|
+
// the server keeps between calls: the owning process (pid + bundle id), its container (a window, the
|
|
14
|
+
// menu bar, or the app), the child-index path from that container, and a fingerprint (role, subrole,
|
|
15
|
+
// AXIdentifier, stable name, frame). `resolve` walks the path and checks the fingerprint; if that fails
|
|
16
|
+
// it searches the container for exactly one element with the same fingerprint. Zero matches is
|
|
17
|
+
// STALE_REF, several is AMBIGUOUS_TARGET: it never guesses.
|
|
18
|
+
//
|
|
19
|
+
// AX return codes do not prove an effect (Finder returns success for an action that does not exist), so
|
|
20
|
+
// every action reads the element and its window again afterwards and reports delivery as
|
|
21
|
+
// delivered_verified (an observed change), delivered_unverified (the call succeeded, nothing observable
|
|
22
|
+
// changed), not_delivered (nothing was sent) or unknown (timed out or failed mid-action), together with
|
|
23
|
+
// whether a retry is safe.
|
|
24
|
+
|
|
25
|
+
ObjC.import('ApplicationServices');
|
|
26
|
+
ObjC.import('AppKit');
|
|
27
|
+
ObjC.import('CoreGraphics');
|
|
28
|
+
ObjC.import('Foundation');
|
|
29
|
+
|
|
30
|
+
// ── CF type ids and small bridges ──────────────────────────────────────────────────────────────
|
|
31
|
+
const TID = {
|
|
32
|
+
ax: Number($.AXUIElementGetTypeID()), val: Number($.AXValueGetTypeID()), str: Number($.CFStringGetTypeID()),
|
|
33
|
+
num: Number($.CFNumberGetTypeID()), bool: Number($.CFBooleanGetTypeID()), arr: Number($.CFArrayGetTypeID()),
|
|
34
|
+
};
|
|
35
|
+
const KS = {};
|
|
36
|
+
function ks(name) { return KS[name] || (KS[name] = $(name)); }
|
|
37
|
+
function cast(raw) { if (raw === null || raw === undefined) return null; try { return ObjC.castRefToObject(raw); } catch (e) { return null; } }
|
|
38
|
+
function tid(o) { try { return Number($.CFGetTypeID(o)); } catch (e) { return -1; } }
|
|
39
|
+
function sleep(ms) { $.NSThread.sleepForTimeInterval(ms / 1000); }
|
|
40
|
+
function now() { return Date.now(); }
|
|
41
|
+
|
|
42
|
+
// AXValue → plain data, parsed from its description ("{value = x:1.0 y:2.0 type = kAXValueCGPointType}").
|
|
43
|
+
// AXValueGetValue does not bridge in JXA (the out-pointer type is rejected), the description always does.
|
|
44
|
+
function axValue(o) {
|
|
45
|
+
let d = '';
|
|
46
|
+
try { d = o.description.js; } catch (e) { return null; }
|
|
47
|
+
const type = (d.match(/type = kAXValue(\w+?)Type/) || [])[1] || '';
|
|
48
|
+
const num = {};
|
|
49
|
+
const re = /(x|y|w|h|location|length|error):(-?[\d.]+)/g;
|
|
50
|
+
let m;
|
|
51
|
+
while ((m = re.exec(d))) num[m[1]] = Number(m[2]);
|
|
52
|
+
if (type === 'AXError') return { error: num.error };
|
|
53
|
+
if (type === 'CGPoint') return { x: num.x, y: num.y };
|
|
54
|
+
if (type === 'CGSize') return { w: num.w, h: num.h };
|
|
55
|
+
if (type === 'CGRect') return { x: num.x, y: num.y, w: num.w, h: num.h };
|
|
56
|
+
if (type === 'CFRange') return { location: num.location, length: num.length };
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Any AX attribute value → JS. Elements are returned as { el } so callers can keep using them.
|
|
61
|
+
function jsv(o, depth) {
|
|
62
|
+
if (o === null || o === undefined) return null;
|
|
63
|
+
const t = tid(o);
|
|
64
|
+
if (t === TID.str) return o.js;
|
|
65
|
+
if (t === TID.bool) return Boolean(o.js);
|
|
66
|
+
if (t === TID.num) return Number(o.js);
|
|
67
|
+
if (t === TID.val) return axValue(o);
|
|
68
|
+
if (t === TID.ax) return { el: o };
|
|
69
|
+
if (t === TID.arr) {
|
|
70
|
+
if ((depth || 0) > 0) return null;
|
|
71
|
+
const out = [];
|
|
72
|
+
const n = Number(o.count);
|
|
73
|
+
for (let i = 0; i < n; i++) out.push(jsv(o.objectAtIndex(i), 1));
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
try { const s = o.js; if (typeof s === 'string') return s; } catch (e) { /* attributed string etc. */ }
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function attrErr(el, name) {
|
|
81
|
+
const r = Ref();
|
|
82
|
+
const e = Number($.AXUIElementCopyAttributeValue(el, ks(name), r));
|
|
83
|
+
return { err: e, raw: e === 0 ? r[0] : null };
|
|
84
|
+
}
|
|
85
|
+
function attr(el, name) { const a = attrErr(el, name); return a.err === 0 ? jsv(cast(a.raw)) : null; }
|
|
86
|
+
function children(el) {
|
|
87
|
+
const a = attrErr(el, 'AXChildren');
|
|
88
|
+
if (a.err !== 0) return [];
|
|
89
|
+
const arr = cast(a.raw);
|
|
90
|
+
if (!arr) return [];
|
|
91
|
+
const n = Number(arr.count);
|
|
92
|
+
const out = [];
|
|
93
|
+
for (let i = 0; i < n; i++) out.push(arr.objectAtIndex(i));
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
function elemsOf(el, name) {
|
|
97
|
+
const a = attrErr(el, name);
|
|
98
|
+
if (a.err !== 0) return [];
|
|
99
|
+
const o = cast(a.raw);
|
|
100
|
+
if (!o) return [];
|
|
101
|
+
if (tid(o) === TID.ax) return [o];
|
|
102
|
+
if (tid(o) !== TID.arr) return [];
|
|
103
|
+
const out = [];
|
|
104
|
+
const n = Number(o.count);
|
|
105
|
+
for (let i = 0; i < n; i++) out.push(o.objectAtIndex(i));
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
function actionNames(el) {
|
|
109
|
+
const r = Ref();
|
|
110
|
+
if (Number($.AXUIElementCopyActionNames(el, r)) !== 0) return [];
|
|
111
|
+
const arr = cast(r[0]);
|
|
112
|
+
if (!arr) return [];
|
|
113
|
+
const out = [];
|
|
114
|
+
const n = Number(arr.count);
|
|
115
|
+
for (let i = 0; i < n; i++) { try { out.push(arr.objectAtIndex(i).js); } catch (e) { /* skip */ } }
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
function settable(el, name) {
|
|
119
|
+
const r = Ref();
|
|
120
|
+
return Number($.AXUIElementIsAttributeSettable(el, ks(name), r)) === 0 && Boolean(r[0]);
|
|
121
|
+
}
|
|
122
|
+
function same(a, b) { try { return Boolean($.CFEqual(a, b)); } catch (e) { return false; } }
|
|
123
|
+
|
|
124
|
+
const READ = ['AXRole', 'AXSubrole', 'AXTitle', 'AXDescription', 'AXValue', 'AXIdentifier', 'AXFrame',
|
|
125
|
+
'AXEnabled', 'AXFocused', 'AXSelected', 'AXExpanded', 'AXPlaceholderValue', 'AXChildren'];
|
|
126
|
+
let READ_NS = null;
|
|
127
|
+
// One IPC round trip for every attribute a snapshot needs; missing ones come back as AXError values.
|
|
128
|
+
function readNode(el) {
|
|
129
|
+
if (!READ_NS) READ_NS = $(READ);
|
|
130
|
+
const r = Ref();
|
|
131
|
+
const e = Number($.AXUIElementCopyMultipleAttributeValues(el, READ_NS, 0, r));
|
|
132
|
+
const v = {};
|
|
133
|
+
if (e !== 0) { v.__err = e; return v; }
|
|
134
|
+
const arr = cast(r[0]);
|
|
135
|
+
if (!arr) { v.__err = -1; return v; }
|
|
136
|
+
for (let i = 0; i < READ.length; i++) {
|
|
137
|
+
const o = arr.objectAtIndex(i);
|
|
138
|
+
if (READ[i] === 'AXChildren') {
|
|
139
|
+
const t = tid(o);
|
|
140
|
+
const kids = [];
|
|
141
|
+
if (t === TID.arr) { const n = Number(o.count); for (let k = 0; k < n; k++) kids.push(o.objectAtIndex(k)); }
|
|
142
|
+
v.AXChildren = kids;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const j = jsv(o);
|
|
146
|
+
if (j && typeof j === 'object' && 'error' in j && Object.keys(j).length === 1) continue;
|
|
147
|
+
v[READ[i]] = j;
|
|
148
|
+
}
|
|
149
|
+
return v;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ── roles, names, states ─────────────────────────────────────────────────────────────────────────
|
|
153
|
+
const INTERACTIVE_ROLES = new Set(['AXButton', 'AXCheckBox', 'AXRadioButton', 'AXPopUpButton', 'AXMenuButton',
|
|
154
|
+
'AXComboBox', 'AXTextField', 'AXTextArea', 'AXSlider', 'AXIncrementor', 'AXLink', 'AXMenuItem', 'AXMenuBarItem',
|
|
155
|
+
'AXDisclosureTriangle', 'AXColorWell', 'AXDateField', 'AXDockItem', 'AXSearchField', 'AXSwitch', 'AXStepper',
|
|
156
|
+
'AXRow', 'AXCell', 'AXTab', 'AXScrollArea', 'AXSegmentedControl', 'AXLevelIndicator', 'AXRuler']);
|
|
157
|
+
const PRIMARY_ACTIONS = new Set(['AXPress', 'AXConfirm', 'AXPick', 'AXOpen', 'AXShowMenu', 'AXIncrement', 'AXDecrement']);
|
|
158
|
+
const TEXT_ROLES = new Set(['AXTextField', 'AXTextArea', 'AXComboBox', 'AXSearchField']);
|
|
159
|
+
const TOGGLE_ROLES = new Set(['AXCheckBox', 'AXRadioButton', 'AXSwitch']);
|
|
160
|
+
const WRAPPER_ROLES = new Set(['AXGroup', 'AXUnknown', 'AXSplitGroup', 'AXLayoutArea', 'AXLayoutItem', 'AXList', 'AXSection', 'AXGenericElement']);
|
|
161
|
+
|
|
162
|
+
function nameOf(v) {
|
|
163
|
+
const t = v.AXTitle, d = v.AXDescription, p = v.AXPlaceholderValue;
|
|
164
|
+
if (typeof t === 'string' && t) return t;
|
|
165
|
+
if (typeof d === 'string' && d) return d;
|
|
166
|
+
if (typeof p === 'string' && p) return p;
|
|
167
|
+
return '';
|
|
168
|
+
}
|
|
169
|
+
function valueOf(v, max) {
|
|
170
|
+
const x = v.AXValue;
|
|
171
|
+
if (typeof x === 'string') return x.length > max ? x.slice(0, max) + '…' : x;
|
|
172
|
+
if (typeof x === 'number' || typeof x === 'boolean') return x;
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
function statesOf(v) {
|
|
176
|
+
const s = [];
|
|
177
|
+
if (v.AXEnabled === false) s.push('disabled');
|
|
178
|
+
if (v.AXFocused === true) s.push('focused');
|
|
179
|
+
if (v.AXSelected === true) s.push('selected');
|
|
180
|
+
if (v.AXExpanded === true) s.push('expanded'); else if (v.AXExpanded === false && v.AXRole !== 'AXWindow') s.push('collapsed');
|
|
181
|
+
if (TOGGLE_ROLES.has(v.AXRole) || v.AXSubrole === 'AXSwitch' || v.AXSubrole === 'AXToggle') {
|
|
182
|
+
if (v.AXValue === 1 || v.AXValue === true) s.push('checked'); else if (v.AXValue === 2) s.push('mixed');
|
|
183
|
+
}
|
|
184
|
+
return s;
|
|
185
|
+
}
|
|
186
|
+
function frameOf(v) {
|
|
187
|
+
const f = v.AXFrame;
|
|
188
|
+
if (f && Number.isFinite(f.x) && Number.isFinite(f.w)) return [Math.round(f.x), Math.round(f.y), Math.round(f.w), Math.round(f.h)];
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
function roleKey(v) { return v.AXSubrole === 'AXSearchField' ? 'AXSearchField' : v.AXSubrole === 'AXSwitch' ? 'AXSwitch' : v.AXSubrole === 'AXTabButton' ? 'AXTab' : v.AXRole; }
|
|
192
|
+
function isInteractive(v, actions) {
|
|
193
|
+
if (INTERACTIVE_ROLES.has(roleKey(v)) || INTERACTIVE_ROLES.has(v.AXRole)) return true;
|
|
194
|
+
for (const a of actions) if (PRIMARY_ACTIONS.has(a)) return true;
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
// A web/layout wrapper that carries nothing of its own: walked through, not shown in compact output,
|
|
198
|
+
// and not counted against the depth limit.
|
|
199
|
+
function isWrapper(v, actions) {
|
|
200
|
+
if (!WRAPPER_ROLES.has(v.AXRole)) return false;
|
|
201
|
+
if (nameOf(v) || (typeof v.AXValue === 'string' && v.AXValue) || v.AXIdentifier) return false;
|
|
202
|
+
for (const a of actions) if (PRIMARY_ACTIONS.has(a)) return false;
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
// A label identifies an element, content does not. nameOf reads only labels (title, description,
|
|
206
|
+
// placeholder), so a text field keeps its label as its name while its value changes; static text has
|
|
207
|
+
// nothing but content, so it has no stable name.
|
|
208
|
+
function stableName(v) { return v.AXRole === 'AXStaticText' ? '' : nameOf(v).slice(0, 120); }
|
|
209
|
+
|
|
210
|
+
// ── apps ─────────────────────────────────────────────────────────────────────────────────────────
|
|
211
|
+
function runningApps() {
|
|
212
|
+
const a = $.NSWorkspace.sharedWorkspace.runningApplications;
|
|
213
|
+
const out = [];
|
|
214
|
+
const n = Number(a.count);
|
|
215
|
+
for (let i = 0; i < n; i++) {
|
|
216
|
+
const x = a.objectAtIndex(i);
|
|
217
|
+
let name = '', bundle = '';
|
|
218
|
+
try { name = x.localizedName.js || ''; } catch (e) { /* none */ }
|
|
219
|
+
try { bundle = x.bundleIdentifier.js || ''; } catch (e) { /* none */ }
|
|
220
|
+
out.push({ ns: x, name, bundle, pid: Number(x.processIdentifier), policy: Number(x.activationPolicy), active: Boolean(x.active), hidden: Boolean(x.hidden) });
|
|
221
|
+
}
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
function frontApp() {
|
|
225
|
+
const x = $.NSWorkspace.sharedWorkspace.frontmostApplication;
|
|
226
|
+
if (!x || x.isNil()) return null;
|
|
227
|
+
let bundle = '';
|
|
228
|
+
try { bundle = x.bundleIdentifier.js || ''; } catch (e) { /* none */ }
|
|
229
|
+
return { ns: x, name: x.localizedName.js, bundle, pid: Number(x.processIdentifier) };
|
|
230
|
+
}
|
|
231
|
+
function findApp(spec) {
|
|
232
|
+
if (!spec) return frontApp();
|
|
233
|
+
const apps = runningApps();
|
|
234
|
+
const want = String(spec);
|
|
235
|
+
if (/^\/.+\.app\/?$/.test(want)) {
|
|
236
|
+
const p = want.replace(/\/$/, '');
|
|
237
|
+
const hit = apps.filter(a => { try { return a.ns.bundleURL && !a.ns.bundleURL.isNil() && a.ns.bundleURL.path.js === p; } catch (e) { return false; } });
|
|
238
|
+
return hit.length ? hit.sort((a, b) => b.pid - a.pid)[0] : null;
|
|
239
|
+
}
|
|
240
|
+
const lower = want.toLowerCase();
|
|
241
|
+
let hit = apps.filter(a => a.name === want || a.bundle === want);
|
|
242
|
+
if (!hit.length) hit = apps.filter(a => a.name.toLowerCase() === lower || a.bundle.toLowerCase() === lower);
|
|
243
|
+
if (!hit.length) return null;
|
|
244
|
+
hit.sort((a, b) => (a.policy - b.policy) || (b.active - a.active));
|
|
245
|
+
return hit[0];
|
|
246
|
+
}
|
|
247
|
+
const POLICY = ['foreground', 'background', 'helper'];
|
|
248
|
+
|
|
249
|
+
const AX_MSG_TIMEOUT_S = 3.0;
|
|
250
|
+
function appElement(app) {
|
|
251
|
+
const el = $.AXUIElementCreateApplication(app.pid);
|
|
252
|
+
$.AXUIElementSetMessagingTimeout(el, AX_MSG_TIMEOUT_S);
|
|
253
|
+
return el;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Chromium and Electron apps build their web accessibility tree only when asked to.
|
|
257
|
+
const CHROMIUM_MARKERS = ['Electron Framework.framework', 'Chromium Embedded Framework.framework'];
|
|
258
|
+
function rendererOf(app) {
|
|
259
|
+
try {
|
|
260
|
+
const url = app.ns.bundleURL;
|
|
261
|
+
if (!url || url.isNil()) return null;
|
|
262
|
+
const dir = url.path.js + '/Contents/Frameworks';
|
|
263
|
+
const list = $.NSFileManager.defaultManager.contentsOfDirectoryAtPathError(dir, null);
|
|
264
|
+
if (!list || list.isNil()) return null;
|
|
265
|
+
const names = [];
|
|
266
|
+
const n = Number(list.count);
|
|
267
|
+
for (let i = 0; i < n; i++) names.push(list.objectAtIndex(i).js);
|
|
268
|
+
if (names.some(x => CHROMIUM_MARKERS.indexOf(x) >= 0 || /(Chrome|Chromium|Edge|Brave|Vivaldi|Opera|Arc).* Framework\.framework$/.test(x))) return 'chromium';
|
|
269
|
+
} catch (e) { /* unknown */ }
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
function enableWebAccessibility(appEl) {
|
|
273
|
+
if (attr(appEl, 'AXManualAccessibility') === true) return 'already_on';
|
|
274
|
+
if (setAttr(appEl, 'AXManualAccessibility', YES()) === 0) { sleep(600); return 'enabled'; }
|
|
275
|
+
return 'unsupported';
|
|
276
|
+
}
|
|
277
|
+
// Google Chrome refuses AXManualAccessibility (-25205), yet exposes its pages when started with
|
|
278
|
+
// --force-renderer-accessibility (device probe 2026-11-06: AXWebArea and the page's button readable,
|
|
279
|
+
// while the setter still said unsupported). So for a
|
|
280
|
+
// window the status says what the tree holds: 'exposed' when a web area is found under it. Other
|
|
281
|
+
// surfaces cannot be judged and keep the setter's answer.
|
|
282
|
+
function webAxStatus(setter, rootEl, rootPath, isWindow) {
|
|
283
|
+
if (setter !== 'unsupported' || !isWindow) return setter;
|
|
284
|
+
const w = walk(rootEl, rootPath, { depth: 60, maxNodes: 100000, budgetMs: 1500, maxVisit: 5000, find: { role: 'AXWebArea', limit: 1 }, pruneMenuBar: true, rootIsContainer: true });
|
|
285
|
+
return w.nodes.length ? 'exposed' : 'unsupported';
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ── containers (where a path starts) ─────────────────────────────────────────────────────────────
|
|
289
|
+
function windowsOf(appEl) { return elemsOf(appEl, 'AXWindows'); }
|
|
290
|
+
// The CGWindowID behind an AX window (HIServices' _AXUIElementGetWindow, bound at run time). It is the
|
|
291
|
+
// window's identity for its whole life, so an element is only ever re-found inside the very window it was
|
|
292
|
+
// seen in. null when the function is unavailable or the element is not a real window.
|
|
293
|
+
let AXGW = null;
|
|
294
|
+
function axWindowId(w) {
|
|
295
|
+
if (AXGW === null) { try { ObjC.bindFunction('_AXUIElementGetWindow', ['int', ['id', 'void *']]); AXGW = true; } catch (e) { AXGW = false; } }
|
|
296
|
+
if (!AXGW) return null;
|
|
297
|
+
try { const r = Ref('I'); return Number($._AXUIElementGetWindow(w, r)) === 0 && Number(r[0]) > 0 ? Number(r[0]) : null; } catch (e) { return null; }
|
|
298
|
+
}
|
|
299
|
+
function windowInfo(w, n) {
|
|
300
|
+
const v = readNode(w);
|
|
301
|
+
return { kind: 'window', n, wid: axWindowId(w), title: typeof v.AXTitle === 'string' ? v.AXTitle : '', subrole: v.AXSubrole || '', frame: frameOf(v), focused: v.AXFocused === true, main: attr(w, 'AXMain') === true, minimized: attr(w, 'AXMinimized') === true };
|
|
302
|
+
}
|
|
303
|
+
function rectNear(a, b, tol) { return a && b && Math.abs(a[0] - b[0]) <= tol && Math.abs(a[1] - b[1]) <= tol && Math.abs(a[2] - b[2]) <= tol && Math.abs(a[3] - b[3]) <= tol; }
|
|
304
|
+
|
|
305
|
+
// Pick the window a snapshot is about: an explicit index/title, else the focused or main window,
|
|
306
|
+
// else the only window. Several candidates and no way to choose → AMBIGUOUS_WINDOW with the list.
|
|
307
|
+
function pickWindow(appEl, req) {
|
|
308
|
+
const ws = windowsOf(appEl);
|
|
309
|
+
const infos = ws.map((w, i) => windowInfo(w, i));
|
|
310
|
+
if (!ws.length) return { error: { code: 'WINDOW_NOT_FOUND', message: 'the app has no window that accessibility can read (not open, minimized to the Dock, or on another Space)' } };
|
|
311
|
+
if (req.window_id !== undefined && req.window_id !== null) {
|
|
312
|
+
const hit = infos.filter(x => x.wid === Number(req.window_id));
|
|
313
|
+
if (hit.length === 1) return { el: ws[hit[0].n], info: hit[0] };
|
|
314
|
+
return { error: { code: 'WINDOW_NOT_FOUND', message: `window_id ${req.window_id} is not one of this app's windows`, details: { windows: infos.map(summaryOfWindow) } } };
|
|
315
|
+
}
|
|
316
|
+
if (req.window !== undefined && req.window !== null && req.window !== '') {
|
|
317
|
+
const want = req.window;
|
|
318
|
+
if (typeof want === 'number') {
|
|
319
|
+
if (want >= 0 && want < ws.length) return { el: ws[want], info: infos[want] };
|
|
320
|
+
return { error: { code: 'WINDOW_NOT_FOUND', message: `window ${want} does not exist (the app has ${ws.length})`, details: { windows: infos.map(summaryOfWindow) } } };
|
|
321
|
+
}
|
|
322
|
+
const hits = infos.filter(x => x.title === want);
|
|
323
|
+
const loose = hits.length ? hits : infos.filter(x => x.title.toLowerCase().indexOf(String(want).toLowerCase()) >= 0);
|
|
324
|
+
if (loose.length === 1) return { el: ws[loose[0].n], info: loose[0] };
|
|
325
|
+
return { error: { code: loose.length ? 'AMBIGUOUS_WINDOW' : 'WINDOW_NOT_FOUND', message: `${loose.length || 'no'} window(s) match "${want}"`, details: { windows: infos.map(summaryOfWindow) } } };
|
|
326
|
+
}
|
|
327
|
+
const f = infos.filter(x => x.focused);
|
|
328
|
+
if (f.length === 1) return { el: ws[f[0].n], info: f[0] };
|
|
329
|
+
const m = infos.filter(x => x.main);
|
|
330
|
+
if (m.length === 1) return { el: ws[m[0].n], info: m[0] };
|
|
331
|
+
const vis = infos.filter(x => !x.minimized);
|
|
332
|
+
if (vis.length === 1) return { el: ws[vis[0].n], info: vis[0] };
|
|
333
|
+
if (ws.length === 1) return { el: ws[0], info: infos[0] };
|
|
334
|
+
return { error: { code: 'AMBIGUOUS_WINDOW', message: `the app has ${ws.length} windows and none is focused — pass window (an index or title)`, details: { windows: infos.map(summaryOfWindow) } } };
|
|
335
|
+
}
|
|
336
|
+
function summaryOfWindow(x) { return { n: x.n, window_id: x.wid, title: x.title.slice(0, 80), frame: x.frame, minimized: x.minimized }; }
|
|
337
|
+
|
|
338
|
+
function surfaceRoot(appEl, win, surface) {
|
|
339
|
+
if (surface === 'menubar') { const mb = attr(appEl, 'AXMenuBar'); return mb && mb.el ? { el: mb.el, container: { kind: 'menubar' } } : { error: { code: 'SURFACE_ABSENT', message: 'the app exposes no menu bar' } }; }
|
|
340
|
+
if (surface === 'menu') {
|
|
341
|
+
// an open menu hangs below a pop-up button or a context-menu target, or (menu bar menus, while open)
|
|
342
|
+
// below its AXMenuBarItem; it is its own container, identified by its frame
|
|
343
|
+
const found = openMenus(appEl);
|
|
344
|
+
if (!found.length) return { error: { code: 'SURFACE_ABSENT', message: 'no menu is open' } };
|
|
345
|
+
return { el: found[0], container: { kind: 'menu', frame: frameOf(readNode(found[0])) }, path: [] };
|
|
346
|
+
}
|
|
347
|
+
if (surface === 'focused') {
|
|
348
|
+
const f = attr(appEl, 'AXFocusedUIElement');
|
|
349
|
+
if (!f || !f.el) return { error: { code: 'SURFACE_ABSENT', message: 'the app reports no focused element' } };
|
|
350
|
+
return { el: f.el, container: null }; // path is computed upward from the window by the caller
|
|
351
|
+
}
|
|
352
|
+
if (surface === 'sheet' || surface === 'alert' || surface === 'popover' || surface === 'dialog') {
|
|
353
|
+
if (!win) return { error: { code: 'WINDOW_NOT_FOUND', message: 'no window to look for a ' + surface + ' in' } };
|
|
354
|
+
const want = surface === 'sheet' ? ['AXSheet'] : surface === 'popover' ? ['AXPopover'] : ['AXSheet', 'AXDialog', 'AXSystemDialog'];
|
|
355
|
+
const found = [];
|
|
356
|
+
const visit = (el, d, path) => { if (d > 6 || found.length) return; const kids = children(el); for (let i = 0; i < kids.length; i++) { const v = readNode(kids[i]); if (want.indexOf(v.AXRole) >= 0 || want.indexOf(v.AXSubrole) >= 0) { found.push({ el: kids[i], path: path.concat(i) }); return; } visit(kids[i], d + 1, path.concat(i)); } };
|
|
357
|
+
visit(win.el, 0, []);
|
|
358
|
+
if (!found.length && surface !== 'sheet' && surface !== 'popover') {
|
|
359
|
+
// a dialog or alert can also be a window of its own
|
|
360
|
+
const ws = windowsOf(appEl);
|
|
361
|
+
for (let i = 0; i < ws.length; i++) { const sr = attr(ws[i], 'AXSubrole'); if (sr === 'AXDialog' || sr === 'AXSystemDialog') return { el: ws[i], container: windowInfo(ws[i], i), path: [] }; }
|
|
362
|
+
}
|
|
363
|
+
return found.length ? { el: found[0].el, container: win.info, path: found[0].path } : { error: { code: 'SURFACE_ABSENT', message: 'no ' + surface + ' is open' } };
|
|
364
|
+
}
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// child-index path from `top` down to `el`, by walking AXParent upward
|
|
369
|
+
function pathUp(el, top) {
|
|
370
|
+
const path = [];
|
|
371
|
+
let cur = el;
|
|
372
|
+
for (let guard = 0; guard < 200; guard++) {
|
|
373
|
+
if (same(cur, top)) return path.reverse();
|
|
374
|
+
const p = attr(cur, 'AXParent');
|
|
375
|
+
if (!p || !p.el) return null;
|
|
376
|
+
const kids = children(p.el);
|
|
377
|
+
let idx = -1;
|
|
378
|
+
for (let i = 0; i < kids.length; i++) if (same(kids[i], cur)) { idx = i; break; }
|
|
379
|
+
if (idx < 0) return null;
|
|
380
|
+
path.push(idx);
|
|
381
|
+
cur = p.el;
|
|
382
|
+
}
|
|
383
|
+
return null;
|
|
384
|
+
}
|
|
385
|
+
function windowOfElement(appEl, el) {
|
|
386
|
+
const w = attr(el, 'AXWindow');
|
|
387
|
+
const ws = windowsOf(appEl);
|
|
388
|
+
if (w && w.el) for (let i = 0; i < ws.length; i++) if (same(ws[i], w.el)) return { el: ws[i], info: windowInfo(ws[i], i) };
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// ── walk ─────────────────────────────────────────────────────────────────────────────────────────
|
|
393
|
+
// Short digest of a value (length + hash): enough to tell two contents apart, small enough to carry
|
|
394
|
+
// between calls (observeState compares values through it, so a 10 MB document never travels).
|
|
395
|
+
function vhash(x) {
|
|
396
|
+
if (x === undefined || x === null) return null;
|
|
397
|
+
if (typeof x !== 'string') return typeof x === 'object' ? null : String(x);
|
|
398
|
+
let h = 5381;
|
|
399
|
+
for (let i = 0; i < x.length; i++) h = ((h << 5) + h + x.charCodeAt(i)) | 0;
|
|
400
|
+
return x.length + ':' + (h >>> 0).toString(36);
|
|
401
|
+
}
|
|
402
|
+
function makeNode(v, ldepth, path, actions, interactive) {
|
|
403
|
+
const role = v.AXRole || '?';
|
|
404
|
+
const node = { d: ldepth, role, path, fp: { role, subrole: v.AXSubrole || '', id: v.AXIdentifier || '', name: stableName(v) } };
|
|
405
|
+
if (v.AXSubrole) node.subrole = v.AXSubrole;
|
|
406
|
+
const nm = nameOf(v); if (nm) node.title = nm.length > 80 ? nm.slice(0, 80) + '…' : nm;
|
|
407
|
+
const val = valueOf(v, 120); if (val !== undefined && val !== '') node.value = val;
|
|
408
|
+
const fr = frameOf(v); if (fr) { node.frame = fr; node.fp.frame = fr; }
|
|
409
|
+
const st = statesOf(v); if (st.length) node.states = st;
|
|
410
|
+
if (v.AXIdentifier) node.id = String(v.AXIdentifier).slice(0, 80);
|
|
411
|
+
const acts = actions.filter(a => PRIMARY_ACTIONS.has(a) || a === 'AXScrollToVisible');
|
|
412
|
+
if (acts.length) node.actions = acts.map(a => a.replace(/^AX/, '').toLowerCase());
|
|
413
|
+
node.interactive = interactive;
|
|
414
|
+
return node;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// Returns flat nodes in document order. Each node carries what the server needs to show it and to
|
|
418
|
+
// find it again (path from the container root). Logical depth skips transparent wrappers.
|
|
419
|
+
function walk(rootEl, rootPath, opt) {
|
|
420
|
+
const nodes = [];
|
|
421
|
+
const deadline = now() + opt.budgetMs;
|
|
422
|
+
let visited = 0;
|
|
423
|
+
let complete = true;
|
|
424
|
+
const skeleton = Boolean(opt.skeleton);
|
|
425
|
+
const maxDepth = skeleton ? Math.min(opt.depth, 3) : opt.depth;
|
|
426
|
+
// anc: evidence about the path from the container down to this node (see pathEvidence, which re-derives
|
|
427
|
+
// it while resolving) — the child count at every level (shape), the labels of the ancestors (chain),
|
|
428
|
+
// and the text collectors of the nearest ITEM_LEVELS ancestors (item keys, see itemKeyOf)
|
|
429
|
+
function visit(el, path, ldepth, inMenuBar, anc) {
|
|
430
|
+
if (nodes.length >= opt.maxNodes || now() > deadline || visited >= opt.maxVisit) { complete = false; return 'stop'; }
|
|
431
|
+
visited++;
|
|
432
|
+
collect(anc.accs, null, true);
|
|
433
|
+
const v = readNode(el);
|
|
434
|
+
if (v.__err) { if (v.__err !== -25202) complete = false; return; } // vanished: skip; unanswered: incomplete
|
|
435
|
+
const role = v.AXRole || '?';
|
|
436
|
+
const isRoot = el === rootEl;
|
|
437
|
+
// a text field's value counts for an ancestor's item only through a cell or row (table content)
|
|
438
|
+
const t = itemText(v, true);
|
|
439
|
+
if (t) collect(anc.accs, t, false, TEXT_ROLES.has(role) ? anc.cells : null);
|
|
440
|
+
if (opt.pruneMenuBar && (role === 'AXMenuBar') && !inMenuBar) return;
|
|
441
|
+
// every visited element counts towards "is this fingerprint unique" — also the ones a filtered
|
|
442
|
+
// (find) or interactive-only snapshot does not show
|
|
443
|
+
const fid = fpKey(role, v.AXSubrole || '', v.AXIdentifier || '', stableName(v));
|
|
444
|
+
seen[fid] = (seen[fid] || 0) + 1;
|
|
445
|
+
const actions = actionNames(el);
|
|
446
|
+
const wrapper = isWrapper(v, actions);
|
|
447
|
+
const interactive = isInteractive(v, actions);
|
|
448
|
+
const kids = v.AXChildren || [];
|
|
449
|
+
const atLimit = ldepth >= maxDepth;
|
|
450
|
+
const show = !(opt.compact && wrapper) && (!opt.interactive || interactive || (skeleton && atLimit && kids.length));
|
|
451
|
+
if (opt.find ? matches(v, opt.find) : show) {
|
|
452
|
+
const node = makeNode(v, ldepth, path, actions, interactive);
|
|
453
|
+
if (anc.chain.length) node.fp.chain = chainKey(anc.chain);
|
|
454
|
+
node._shape = anc.shape.slice();
|
|
455
|
+
node._accs = anc.accs;
|
|
456
|
+
node._el = el;
|
|
457
|
+
if (!opt.find && atLimit && kids.length) { node.children_count = kids.length; node.truncated = true; }
|
|
458
|
+
nodes.push(node);
|
|
459
|
+
if (opt.find && nodes.length >= opt.find.limit) { complete = false; return 'stop'; }
|
|
460
|
+
}
|
|
461
|
+
if (atLimit && !opt.find) { if (kids.length && !skeleton) complete = false; if (kids.length) for (const a of anc.accs) if (!a.full) a.cut = true; return; }
|
|
462
|
+
const nextDepth = wrapper ? ldepth : ldepth + 1;
|
|
463
|
+
const name = isRoot && opt.rootIsContainer ? '' : chainName(v);
|
|
464
|
+
// the container itself is never an item (its texts are the whole window's: toolbars, status lines),
|
|
465
|
+
// nor are page-, toolbar- or pane-level groups
|
|
466
|
+
const own = { texts: [], seen: 0, full: false, cut: false, closed: false, noItem: (isRoot && Boolean(opt.rootIsContainer)) || ITEM_SKIP_ROLES.has(role) };
|
|
467
|
+
if (nodes.length && nodes[nodes.length - 1]._el === el) nodes[nodes.length - 1]._own = own;
|
|
468
|
+
const cell = CELL_ROLES.has(role);
|
|
469
|
+
const childAnc = { shape: anc.shape.concat(kids.length), chain: name ? anc.chain.concat(name) : anc.chain, accs: [own].concat(anc.accs).slice(0, ITEM_LEVELS), cells: [cell].concat(anc.cells.map(c => c || cell)).slice(0, ITEM_LEVELS) };
|
|
470
|
+
if (atLimit) own.cut = true;
|
|
471
|
+
for (let i = 0; i < kids.length; i++) {
|
|
472
|
+
if (visit(kids[i], path.concat(i), nextDepth, inMenuBar || role === 'AXMenuBar', childAnc) === 'stop') return 'stop';
|
|
473
|
+
}
|
|
474
|
+
own.closed = true;
|
|
475
|
+
}
|
|
476
|
+
const pre = opt.evidence || { shape: [], chain: [] };
|
|
477
|
+
const seen = {};
|
|
478
|
+
visit(rootEl, rootPath.slice(), 0, false, { shape: pre.shape.slice(), chain: pre.chain.slice(), accs: [], cells: [] });
|
|
479
|
+
// Elements that share their fingerprint with another one in the container (several "Delete" buttons,
|
|
480
|
+
// one per list item) are told apart by their surroundings: the path shape, and the item key. Uniqueness
|
|
481
|
+
// is known only when the whole container was walked: a snapshot that stopped early, or one drilled into
|
|
482
|
+
// part of the container, may have missed look-alikes, so all its elements count as duplicated.
|
|
483
|
+
// Every labelled element also records its item key — the first texts under itself or its nearest
|
|
484
|
+
// ancestor (within ITEM_LEVELS, never the container) that has any — because a look-alike can appear
|
|
485
|
+
// after the snapshot (a second message arriving above the only one there was). Every element records
|
|
486
|
+
// its path shape. An item key that two look-alikes share (both rows climbed to the same section
|
|
487
|
+
// heading) tells nothing apart and is dropped.
|
|
488
|
+
const whole = complete && opt.rootIsContainer !== false;
|
|
489
|
+
const picked = new Map();
|
|
490
|
+
for (const n of nodes) {
|
|
491
|
+
const fid = fpKey(n.fp.role, n.fp.subrole, n.fp.id, n.fp.name);
|
|
492
|
+
const dup = !whole || seen[fid] > 1;
|
|
493
|
+
const anon = anonymousFp(n.fp);
|
|
494
|
+
n.fp.shape = n._shape;
|
|
495
|
+
if (dup) n.fp.dup = true;
|
|
496
|
+
if (dup || !anon) {
|
|
497
|
+
// its own texts first (a row's content is the row), then the nearest ancestors'
|
|
498
|
+
const accs = [n._own].concat(n._accs);
|
|
499
|
+
for (let k = 0; k < accs.length; k++) {
|
|
500
|
+
const a = accs[k];
|
|
501
|
+
if (a && a.closed && !a.cut && !a.noItem && a.texts.length) {
|
|
502
|
+
n.fp.item = `${k}:${a.texts.join('\u0001')}`;
|
|
503
|
+
n._acc = a;
|
|
504
|
+
if (dup) { if (!picked.has(fid)) picked.set(fid, new Map()); const m = picked.get(fid); m.set(a, (m.get(a) || 0) + 1); }
|
|
505
|
+
break;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
for (const n of nodes) {
|
|
511
|
+
if (n.fp.dup && n._acc) { const m = picked.get(fpKey(n.fp.role, n.fp.subrole, n.fp.id, n.fp.name)); if (m && m.get(n._acc) > 1) delete n.fp.item; }
|
|
512
|
+
delete n._shape; delete n._accs; delete n._el; delete n._own; delete n._acc;
|
|
513
|
+
}
|
|
514
|
+
return { nodes, complete, visited };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function textMatch(have, want, exact) {
|
|
518
|
+
if (want === undefined || want === null || want === '') return true;
|
|
519
|
+
if (have === undefined || have === null) return false;
|
|
520
|
+
const h = String(have).toLowerCase(), w = String(want).toLowerCase();
|
|
521
|
+
return exact ? h === w : h.indexOf(w) >= 0;
|
|
522
|
+
}
|
|
523
|
+
function matches(v, f) {
|
|
524
|
+
if (f.role) {
|
|
525
|
+
const r = String(f.role).toLowerCase().replace(/^ax/, '');
|
|
526
|
+
const rk = String(roleKey(v) || '').toLowerCase().replace(/^ax/, '');
|
|
527
|
+
const rr = String(v.AXRole || '').toLowerCase().replace(/^ax/, '');
|
|
528
|
+
const sr = String(v.AXSubrole || '').toLowerCase().replace(/^ax/, '');
|
|
529
|
+
if (r !== rk && r !== rr && r !== sr) return false;
|
|
530
|
+
}
|
|
531
|
+
if (f.title !== undefined && f.title !== '' && !textMatch(nameOf(v), f.title, f.exact)) return false;
|
|
532
|
+
if (f.value !== undefined && f.value !== '' && !textMatch(typeof v.AXValue === 'string' || typeof v.AXValue === 'number' ? v.AXValue : null, f.value, f.exact)) return false;
|
|
533
|
+
if (f.id && !textMatch(v.AXIdentifier, f.id, f.exact)) return false;
|
|
534
|
+
// text: the label or the value, each matched on its own (exact means the whole string, case-insensitive)
|
|
535
|
+
if (f.text !== undefined && f.text !== '' && !textMatch(nameOf(v), f.text, f.exact) && !textMatch(typeof v.AXValue === 'string' || typeof v.AXValue === 'number' ? v.AXValue : null, f.text, f.exact)) return false;
|
|
536
|
+
return Boolean(f.role || f.title || f.value || f.id || f.text);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// ── resolve (re-identify an element from stored evidence) ────────────────────────────────────────
|
|
540
|
+
// Fingerprint check. Role, subrole, AXIdentifier and stable name must match exactly in both directions
|
|
541
|
+
// (an element that gained or lost a label is not the one that was seen).
|
|
542
|
+
function fpOk(v, fp) {
|
|
543
|
+
if ((v.AXRole || '') !== fp.role) return false;
|
|
544
|
+
if ((v.AXSubrole || '') !== (fp.subrole || '')) return false;
|
|
545
|
+
if ((v.AXIdentifier || '') !== (fp.id || '')) return false;
|
|
546
|
+
if (stableName(v) !== (fp.name || '')) return false;
|
|
547
|
+
return true;
|
|
548
|
+
}
|
|
549
|
+
// An element with neither an identifier nor a label is told apart from its look-alikes only by where it
|
|
550
|
+
// is, so its position is part of its identity.
|
|
551
|
+
function anonymousFp(fp) { return !fp.id && !fp.name; }
|
|
552
|
+
// Frames are screen coordinates. Comparing them after subtracting how far the container (window or
|
|
553
|
+
// open menu) moved since the snapshot keeps a dragged window's elements identifiable; a change inside
|
|
554
|
+
// the window (scrolling, a row inserted above) still shows.
|
|
555
|
+
const POS_TOL = 4; // px: same element, re-laid-out by at most rounding
|
|
556
|
+
const PATH_NAMED_TOL = 48; // px: a named element still at its recorded path but moved further is re-searched
|
|
557
|
+
const SEARCH_NAMED_TOL = 64; // px: how far from its place a labelled element may be found by search
|
|
558
|
+
function frameNear(v, fp, shift, tol) {
|
|
559
|
+
if (!fp.frame) return true;
|
|
560
|
+
const f = frameOf(v);
|
|
561
|
+
if (!f) return false;
|
|
562
|
+
return rectNear([f[0] - shift[0], f[1] - shift[1], f[2], f[3]], fp.frame, tol);
|
|
563
|
+
}
|
|
564
|
+
// ── evidence along the path ──────────────────────────────────────────────────────────────────────
|
|
565
|
+
// Besides its own fingerprint an element is described by where it sits: the labels of its ancestors
|
|
566
|
+
// (chain; window-level titles such as a web page's are left out because they change with content, and
|
|
567
|
+
// digits are ignored so "Inbox (3)" stays "Inbox (#)"), and, when it has no label or shares its
|
|
568
|
+
// fingerprint with another element, the child count at every level of its path (shape: an item
|
|
569
|
+
// inserted or removed above it shows) and the first texts of the nearest ancestor that has any (item:
|
|
570
|
+
// a re-sorted or recycled list puts another item's content at the same place).
|
|
571
|
+
const ITEM_LEVELS = 4, ITEM_TEXTS = 6, ITEM_VISIT = 40;
|
|
572
|
+
const CELL_ROLES = new Set(['AXCell', 'AXRow']);
|
|
573
|
+
const ITEM_SKIP_ROLES = new Set(['AXWebArea', 'AXToolbar', 'AXScrollArea', 'AXSplitGroup', 'AXWindow', 'AXSheet', 'AXApplication']);
|
|
574
|
+
const VOLATILE_NAME_ROLES = new Set(['AXWebArea', 'AXWindow', 'AXSheet', 'AXScrollArea', 'AXApplication']);
|
|
575
|
+
// text that identifies a list item: static text, a link's label, and a text field's content only when
|
|
576
|
+
// the field is table content (a cell or row lies between the item and the field: a file name in
|
|
577
|
+
// Finder's name column) — a form field's value is what the user types, not where the element is; never
|
|
578
|
+
// a button title (every item has the same buttons)
|
|
579
|
+
function itemText(v, cellOk) {
|
|
580
|
+
const r = v.AXRole;
|
|
581
|
+
const field = TEXT_ROLES.has(r) && cellOk;
|
|
582
|
+
const t = r === 'AXStaticText' || field ? (typeof v.AXValue === 'string' ? v.AXValue : '') : r === 'AXLink' ? nameOf(v) : '';
|
|
583
|
+
return t.trim() ? t.trim().slice(0, 60) : '';
|
|
584
|
+
}
|
|
585
|
+
function fpKey(role, subrole, id, name) { return [role, subrole, id, name].join('\u0001'); }
|
|
586
|
+
// walk-side collection: every visited descendant counts against ITEM_VISIT (whether or not it answers),
|
|
587
|
+
// texts are kept in document order until ITEM_TEXTS — itemKeyOf counts the same way
|
|
588
|
+
function collect(accs, text, counting, mask) {
|
|
589
|
+
for (let j = 0; j < accs.length; j++) {
|
|
590
|
+
const a = accs[j];
|
|
591
|
+
if (a.full) continue;
|
|
592
|
+
if (counting) { if (++a.seen > ITEM_VISIT) a.full = true; continue; }
|
|
593
|
+
if (text && (!mask || mask[j])) { a.texts.push(text); if (a.texts.length >= ITEM_TEXTS) a.full = true; }
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
function chainName(v) { return VOLATILE_NAME_ROLES.has(v.AXRole) ? '' : stableName(v).replace(/\d+/g, '#'); }
|
|
597
|
+
function chainKey(chain) { return chain.join('\u0001').slice(0, 300); }
|
|
598
|
+
// the item key of `anc`, the k-th ancestor: the first ITEM_TEXTS texts among its first ITEM_VISIT
|
|
599
|
+
// descendants in document order (menu bars are skipped as in walk unless the container is the menu bar)
|
|
600
|
+
function itemKeyOf(anc, k, skipMenuBar) {
|
|
601
|
+
const texts = [];
|
|
602
|
+
let seen = 0, stop = false;
|
|
603
|
+
// cellOk: a cell or row lies between `anc` (inclusive) and this element (exclusive)
|
|
604
|
+
const visit = (e, cellOk) => {
|
|
605
|
+
if (stop) return;
|
|
606
|
+
if (++seen > ITEM_VISIT) { stop = true; return; }
|
|
607
|
+
const v = readNode(e);
|
|
608
|
+
if (v.__err) return;
|
|
609
|
+
const t = itemText(v, cellOk);
|
|
610
|
+
if (t) { texts.push(t); if (texts.length >= ITEM_TEXTS) { stop = true; return; } }
|
|
611
|
+
if (skipMenuBar && v.AXRole === 'AXMenuBar') return;
|
|
612
|
+
const below = cellOk || CELL_ROLES.has(v.AXRole);
|
|
613
|
+
for (const c of v.AXChildren || []) { visit(c, below); if (stop) return; }
|
|
614
|
+
};
|
|
615
|
+
const top = CELL_ROLES.has(attr(anc, 'AXRole'));
|
|
616
|
+
for (const c of children(anc)) { visit(c, top); if (stop) break; }
|
|
617
|
+
return `${k}:${texts.join('\u0001')}`;
|
|
618
|
+
}
|
|
619
|
+
// One child by index, and the child count, without bridging the whole AXChildren array (a 5,000-row
|
|
620
|
+
// outline would otherwise cross the bridge on every step); falls back to the full list.
|
|
621
|
+
function childCount(el) {
|
|
622
|
+
const r = Ref();
|
|
623
|
+
if (Number($.AXUIElementGetAttributeValueCount(el, ks('AXChildren'), r)) === 0) { const n = Number(r[0]); if (Number.isFinite(n)) return n; }
|
|
624
|
+
return children(el).length;
|
|
625
|
+
}
|
|
626
|
+
function childAt(el, i) {
|
|
627
|
+
const r = Ref();
|
|
628
|
+
if (Number($.AXUIElementCopyAttributeValues(el, ks('AXChildren'), i, 1, r)) === 0) { const a = cast(r[0]); if (a && Number(a.count) === 1) return a.objectAtIndex(0); }
|
|
629
|
+
const kids = children(el);
|
|
630
|
+
return i < kids.length ? kids[i] : null;
|
|
631
|
+
}
|
|
632
|
+
const LITE = ['AXRole', 'AXSubrole', 'AXTitle', 'AXDescription', 'AXPlaceholderValue', 'AXIdentifier'];
|
|
633
|
+
let LITE_NS = null;
|
|
634
|
+
// role and label attributes only (no children, no value) — for ancestors along a path
|
|
635
|
+
function readLite(el) {
|
|
636
|
+
if (!LITE_NS) LITE_NS = $(LITE);
|
|
637
|
+
const r = Ref();
|
|
638
|
+
if (Number($.AXUIElementCopyMultipleAttributeValues(el, LITE_NS, 0, r)) !== 0) return { __err: -1 };
|
|
639
|
+
const arr = cast(r[0]);
|
|
640
|
+
if (!arr) return { __err: -1 };
|
|
641
|
+
const v = {};
|
|
642
|
+
for (let i = 0; i < LITE.length; i++) { const j = jsv(arr.objectAtIndex(i)); if (j && typeof j === 'object' && 'error' in j) continue; v[LITE[i]] = j; }
|
|
643
|
+
return v;
|
|
644
|
+
}
|
|
645
|
+
// shape and chain of the element reached by following `path` from `root`; `els` are the elements along
|
|
646
|
+
// the way (root excluded, the element itself last)
|
|
647
|
+
function pathEvidence(root, path, skipMenuBar) {
|
|
648
|
+
const shape = [], chain = [], els = [];
|
|
649
|
+
let el = root;
|
|
650
|
+
for (let k = 0; k < path.length; k++) {
|
|
651
|
+
const n = childCount(el);
|
|
652
|
+
shape.push(n);
|
|
653
|
+
if (path[k] >= n) return { ok: false };
|
|
654
|
+
el = childAt(el, path[k]);
|
|
655
|
+
if (!el) return { ok: false };
|
|
656
|
+
els.push(el);
|
|
657
|
+
if (k < path.length - 1) {
|
|
658
|
+
const v = readLite(el);
|
|
659
|
+
if (v.__err) return { ok: false };
|
|
660
|
+
if (skipMenuBar && v.AXRole === 'AXMenuBar') return { ok: false };
|
|
661
|
+
const nm = chainName(v); if (nm) chain.push(nm);
|
|
662
|
+
} else if (skipMenuBar && k === 0 && attr(el, 'AXRole') === 'AXMenuBar') return { ok: false };
|
|
663
|
+
}
|
|
664
|
+
return { ok: true, el, shape, chain, els };
|
|
665
|
+
}
|
|
666
|
+
// chain, shape and nearest ancestors of an element found by search, climbing AXParent to the container
|
|
667
|
+
function climbEvidence(e, root) {
|
|
668
|
+
const chain = [], ancs = [], shape = [];
|
|
669
|
+
const p0 = attr(e, 'AXParent');
|
|
670
|
+
let cur = p0 && p0.el ? p0.el : null;
|
|
671
|
+
for (let g = 0; g < 200 && cur; g++) {
|
|
672
|
+
ancs.push(cur);
|
|
673
|
+
shape.unshift(childCount(cur));
|
|
674
|
+
if (same(cur, root)) return { chain, ancs, shape };
|
|
675
|
+
const v = readLite(cur);
|
|
676
|
+
if (v.__err) return null;
|
|
677
|
+
const n = chainName(v); if (n) chain.unshift(n);
|
|
678
|
+
const up = attr(cur, 'AXParent');
|
|
679
|
+
cur = up && up.el ? up.el : null;
|
|
680
|
+
}
|
|
681
|
+
return null;
|
|
682
|
+
}
|
|
683
|
+
// item key check: level 0 is the element itself, then its ancestors nearest first (the container last)
|
|
684
|
+
// A look-alike's item must match exactly ("Invoice 12" is not "Invoice 13"); a unique element's item
|
|
685
|
+
// ignores digits like the ancestor chain does (a counter or a relative time in the same group changes)
|
|
686
|
+
function itemSame(el, ancs, fp, skipMenuBar, exact) {
|
|
687
|
+
if (!fp.item) return true;
|
|
688
|
+
const k = itemLevel(fp);
|
|
689
|
+
const a = k === 0 ? el : ancs[k - 1];
|
|
690
|
+
if (!a) return false;
|
|
691
|
+
const live = itemKeyOf(a, k, skipMenuBar);
|
|
692
|
+
return fp.dup || exact ? live === fp.item : live.replace(/\d+/g, '#') === fp.item.replace(/\d+/g, '#');
|
|
693
|
+
}
|
|
694
|
+
function itemLevel(fp) { return fp.item ? Number(fp.item.slice(0, fp.item.indexOf(':'))) : -1; }
|
|
695
|
+
// open menus (a pop-up, a context menu, a menu bar menu while it is open)
|
|
696
|
+
function openMenus(appEl) {
|
|
697
|
+
const found = [];
|
|
698
|
+
const visit = (el, d) => { if (d > 30) return; const r = attr(el, 'AXRole'); if (r === 'AXMenu') { found.push(el); return; } for (const k of children(el)) visit(k, d + 1); };
|
|
699
|
+
for (const w of windowsOf(appEl)) visit(w, 0);
|
|
700
|
+
const mb = attr(appEl, 'AXMenuBar');
|
|
701
|
+
if (mb && mb.el) for (const item of children(mb.el)) if (attr(item, 'AXSelected') === true) for (const k of children(item)) if (attr(k, 'AXRole') === 'AXMenu') found.push(k);
|
|
702
|
+
return found;
|
|
703
|
+
}
|
|
704
|
+
function containerEl(appEl, c) {
|
|
705
|
+
if (!c || c.kind === 'app') return { el: appEl, shift: [0, 0] };
|
|
706
|
+
if (c.kind === 'menubar') { const mb = attr(appEl, 'AXMenuBar'); return mb && mb.el ? { el: mb.el, shift: [0, 0] } : { error: 'menubar_absent' }; }
|
|
707
|
+
if (c.kind === 'menu') {
|
|
708
|
+
// the same open menu: an AXMenu at the recorded frame; a closed menu is a stale reference, never a
|
|
709
|
+
// reason to look anywhere else (closed menu items can still be pressed, so a look-alike would run)
|
|
710
|
+
const hit = openMenus(appEl).filter(m => rectNear(frameOf(readNode(m)), c.frame, POS_TOL));
|
|
711
|
+
if (hit.length === 1) return { el: hit[0], shift: [0, 0] };
|
|
712
|
+
return { error: hit.length ? 'menu_ambiguous' : 'menu_closed' };
|
|
713
|
+
}
|
|
714
|
+
if (c.kind === 'window') {
|
|
715
|
+
const ws = windowsOf(appEl);
|
|
716
|
+
const shiftOf = (w) => { const f = frameOf(readNode(w)); return f && c.frame ? [f[0] - c.frame[0], f[1] - c.frame[1]] : [0, 0]; };
|
|
717
|
+
// exact: the same CGWindowID (survives title changes, never matches another window)
|
|
718
|
+
if (c.wid) {
|
|
719
|
+
for (const w of ws) if (axWindowId(w) === c.wid) return { el: w, shift: shiftOf(w) };
|
|
720
|
+
return { error: 'window_absent' };
|
|
721
|
+
}
|
|
722
|
+
// no id was available when the element was seen: same title, subrole and frame; a changed title or a
|
|
723
|
+
// moved window is a stale reference, not a reason to pick some other window
|
|
724
|
+
const infos = ws.map((w, i) => windowInfo(w, i));
|
|
725
|
+
const hits = infos.filter(x => x.title === c.title && x.subrole === c.subrole && (!c.frame || rectNear(x.frame, c.frame, POS_TOL)));
|
|
726
|
+
if (hits.length === 1) return { el: ws[hits[0].n], shift: [0, 0] };
|
|
727
|
+
return { error: hits.length ? 'window_ambiguous' : 'window_absent' };
|
|
728
|
+
}
|
|
729
|
+
return { error: 'container_unknown' };
|
|
730
|
+
}
|
|
731
|
+
const SEARCH_MAX_DEPTH = 150, SEARCH_MAX_VISIT = 20000;
|
|
732
|
+
function resolveTarget(t, budgetMs) {
|
|
733
|
+
if (!$.AXIsProcessTrusted()) return { error: permError() };
|
|
734
|
+
const apps = runningApps().filter(a => a.pid === t.pid);
|
|
735
|
+
if (!apps.length) return { error: { code: 'STALE_REF', message: `the app (pid ${t.pid}) is no longer running`, details: { kind: 'app_gone' } } };
|
|
736
|
+
const app = apps[0];
|
|
737
|
+
const appEl = appElement(app);
|
|
738
|
+
const kind = t.container && t.container.kind || 'app';
|
|
739
|
+
const c = containerEl(appEl, t.container);
|
|
740
|
+
if (c.error) {
|
|
741
|
+
const amb = /ambiguous/.test(c.error);
|
|
742
|
+
const what = kind === 'menu' ? 'the menu the element was in is closed' : 'the element\'s window is gone';
|
|
743
|
+
return { error: { code: amb ? 'AMBIGUOUS_TARGET' : 'STALE_REF', message: amb ? `several ${kind === 'menu' ? 'menus' : 'windows'} match the element's ${kind === 'menu' ? 'menu' : 'window'}` : what, details: { kind: c.error } } };
|
|
744
|
+
}
|
|
745
|
+
const anon = anonymousFp(t.fp);
|
|
746
|
+
// the menu bar is searched only for elements that were seen in it: a closed menu's items can still be
|
|
747
|
+
// pressed, so a vanished pop-up item must not turn into the menu bar item of the same name
|
|
748
|
+
const skipMenuBar = kind !== 'menubar';
|
|
749
|
+
const chainOk = (chain) => chainKey(chain) === (t.fp.chain || '');
|
|
750
|
+
const shapeOk = (shape) => !t.fp.shape || JSON.stringify(shape) === JSON.stringify(t.fp.shape);
|
|
751
|
+
// 1) the recorded path: the element there must carry the same fingerprint, sit where it sat (relative
|
|
752
|
+
// to its container) under the same labelled ancestors; an unlabelled or duplicated element must also
|
|
753
|
+
// keep its item key, or — without one — the shape of its path
|
|
754
|
+
const pe = pathEvidence(c.el, t.path, skipMenuBar);
|
|
755
|
+
if (pe.ok) {
|
|
756
|
+
const v = readNode(pe.el);
|
|
757
|
+
const ancs = pe.els.slice(0, -1).reverse().concat([c.el]);
|
|
758
|
+
// the shape of the path must hold unless the element's own item (itself or its parent) vouches for
|
|
759
|
+
// it word for word — an unlabelled element always needs it; a different shape sends a labelled one
|
|
760
|
+
// to the search (a row prepended above "Invoice 12" that reads "Invoice 13" is not a match)
|
|
761
|
+
const ownItem = !anon && itemLevel(t.fp) >= 0 && itemLevel(t.fp) <= 1;
|
|
762
|
+
const shaped = shapeOk(pe.shape);
|
|
763
|
+
if (!v.__err && fpOk(v, t.fp) && frameNear(v, t.fp, c.shift, anon ? POS_TOL : PATH_NAMED_TOL) && chainOk(pe.chain)
|
|
764
|
+
&& (shaped ? (!t.fp.item || itemSame(pe.el, ancs, t.fp, skipMenuBar)) : ownItem && itemSame(pe.el, ancs, t.fp, skipMenuBar, true))) {
|
|
765
|
+
return { el: pe.el, app, appEl, v, how: 'path', path: t.path.slice(), containerEl: c.el };
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
// An unlabelled element is identified only by where it is: when its path no longer leads to it, it is
|
|
769
|
+
// stale (a look-alike elsewhere is not evidence of anything).
|
|
770
|
+
if (anon) return { error: { code: 'STALE_REF', message: 'the element moved or was replaced since the snapshot (it has no label or identifier, so only its place identifies it)', details: { kind: 'saved_ref_moved' } } };
|
|
771
|
+
// 2) a labelled element: search the container for the same fingerprint
|
|
772
|
+
const deadline = now() + (budgetMs || 3000);
|
|
773
|
+
const hits = [];
|
|
774
|
+
let complete = true, visited = 0;
|
|
775
|
+
const visit = (e, d) => {
|
|
776
|
+
if (now() > deadline || d > SEARCH_MAX_DEPTH || visited >= SEARCH_MAX_VISIT) { complete = false; return; }
|
|
777
|
+
visited++;
|
|
778
|
+
const v = readNode(e);
|
|
779
|
+
if (v.__err) { if (v.__err !== -25202) complete = false; return; }
|
|
780
|
+
if (skipMenuBar && v.AXRole === 'AXMenuBar') return;
|
|
781
|
+
if (fpOk(v, t.fp)) hits.push({ el: e, v });
|
|
782
|
+
for (const k of v.AXChildren || []) visit(k, d + 1);
|
|
783
|
+
};
|
|
784
|
+
visit(c.el, 0);
|
|
785
|
+
const found = (h, how) => ({ el: h.el, app, appEl, v: h.v, how, path: null, containerEl: c.el });
|
|
786
|
+
const evOk = (h, withItem) => { const ev = climbEvidence(h.el, c.el); return Boolean(ev) && chainOk(ev.chain) && (!withItem || itemSame(h.el, ev.ancs, t.fp, skipMenuBar)); };
|
|
787
|
+
if (t.fp.dup) {
|
|
788
|
+
// one of several look-alikes (a Delete per list item): only its item's texts tell which one it was
|
|
789
|
+
if (!t.fp.item) return { error: { code: 'STALE_REF', message: 'the element moved and it has look-alikes that nothing tells apart — take a new snapshot', details: { kind: 'saved_ref_moved' } } };
|
|
790
|
+
const agree = hits.filter(h => evOk(h, true));
|
|
791
|
+
const pick = agree.length > 1 ? agree.filter(h => frameNear(h.v, t.fp, c.shift, POS_TOL)) : agree;
|
|
792
|
+
if (pick.length === 1 && (complete || agree.length === 1)) return found(pick[0], 'search+item');
|
|
793
|
+
if (agree.length > 1) return { error: { code: 'AMBIGUOUS_TARGET', message: `${agree.length} look-alikes now match this element and its item — take a new snapshot`, details: { kind: 'saved_ref_ambiguous' } } };
|
|
794
|
+
return { error: { code: 'STALE_REF', message: 'the element and its item are gone or changed since the snapshot', details: { kind: complete ? 'saved_ref_absent' : 'search_incomplete' } } };
|
|
795
|
+
}
|
|
796
|
+
// the only element with this identifier in the snapshot: unique in the whole container, under the same
|
|
797
|
+
// ancestors, is enough
|
|
798
|
+
if (t.fp.id && hits.length === 1 && complete && evOk(hits[0], true)) return found(hits[0], 'search');
|
|
799
|
+
// the only element with this label in the snapshot: it must still be close to where it was (a
|
|
800
|
+
// same-named control elsewhere — another panel's Delete after this panel closed — is not it), under the
|
|
801
|
+
// same ancestors and, when it has one, in the same item (a look-alike that arrived since is not it)
|
|
802
|
+
const close = hits.filter(h => frameNear(h.v, t.fp, c.shift, SEARCH_NAMED_TOL) && evOk(h, true));
|
|
803
|
+
if (close.length === 1 && (complete || frameNear(close[0].v, t.fp, c.shift, POS_TOL))) return found(close[0], 'search+frame');
|
|
804
|
+
if (close.length > 1) return { error: { code: 'AMBIGUOUS_TARGET', message: `${close.length} elements with this element's role and name are near where it was — take a new snapshot`, details: { kind: 'saved_ref_ambiguous' } } };
|
|
805
|
+
return { error: { code: 'STALE_REF', message: hits.length ? 'the element is no longer where it was (a control with the same name exists elsewhere, which is not taken for it)' : 'the element is gone or changed since the snapshot', details: { kind: complete ? (hits.length ? 'saved_ref_moved' : 'saved_ref_absent') : 'search_incomplete' } } };
|
|
806
|
+
}
|
|
807
|
+
// the live child-index path of a resolved element (the recorded one, or re-derived after a search)
|
|
808
|
+
function livePath(r) { return r.path || pathUp(r.el, r.containerEl); }
|
|
809
|
+
|
|
810
|
+
function permError() {
|
|
811
|
+
return { code: 'PERM_DENIED', message: 'Accessibility permission is missing for the app that runs noracu (the MCP host) — System Settings → Privacy & Security → Accessibility (on macOS 27: Device Control and Data Access), enable the host, then quit and reopen it' };
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// ── ops ──────────────────────────────────────────────────────────────────────────────────────────
|
|
815
|
+
function opSnapshot(req) {
|
|
816
|
+
if (!$.AXIsProcessTrusted()) return fail(permError());
|
|
817
|
+
const app = req.root ? (runningApps().find(a => a.pid === req.root.pid) || null) : appForRequest(req);
|
|
818
|
+
if (!app) return fail(req.root ? { code: 'STALE_REF', message: `the app (pid ${req.root.pid}) is no longer running`, details: { kind: 'app_gone' } } : appNotFound(req));
|
|
819
|
+
const appEl = appElement(app);
|
|
820
|
+
let webAx = null;
|
|
821
|
+
if (req.web_accessibility !== false && rendererOf(app) === 'chromium') webAx = enableWebAccessibility(appEl);
|
|
822
|
+
const opt = {
|
|
823
|
+
depth: clamp(req.depth, 1, 40, 12), maxNodes: clamp(req.max_nodes, 10, 2000, 400), budgetMs: clamp(req.budget_ms, 500, 20000, 8000),
|
|
824
|
+
maxVisit: 20000, interactive: Boolean(req.interactive), compact: req.compact !== false, skeleton: Boolean(req.skeleton),
|
|
825
|
+
pruneMenuBar: true,
|
|
826
|
+
};
|
|
827
|
+
// contEl: the element the container record stands for (where paths start); the root is walked
|
|
828
|
+
let root, container, basePath = [], winInfo = null, surface = req.surface || 'window', contEl = null;
|
|
829
|
+
if (req.root) {
|
|
830
|
+
const r = resolveTarget(req.root, 3000);
|
|
831
|
+
if (r.error) return fail(r.error);
|
|
832
|
+
// children are numbered from where the root is now, not from where it was (it may have been found
|
|
833
|
+
// by search after siblings moved)
|
|
834
|
+
const p = livePath(r);
|
|
835
|
+
if (!p) return fail({ code: 'STALE_REF', message: 'the element was found but could not be placed inside its container — take a new snapshot', details: { kind: 'unplaceable' } });
|
|
836
|
+
root = r.el; container = req.root.container; basePath = p; surface = 'root'; contEl = r.containerEl;
|
|
837
|
+
opt.pruneMenuBar = false;
|
|
838
|
+
} else if (surface === 'window' || surface === 'app') {
|
|
839
|
+
if (surface === 'app') { root = appEl; container = { kind: 'app' }; }
|
|
840
|
+
else {
|
|
841
|
+
const w = pickWindow(appEl, req);
|
|
842
|
+
if (w.error) return fail(w.error);
|
|
843
|
+
root = w.el; container = w.info; winInfo = w.info;
|
|
844
|
+
}
|
|
845
|
+
contEl = root;
|
|
846
|
+
} else {
|
|
847
|
+
let win = null;
|
|
848
|
+
if (surface === 'sheet' || surface === 'alert' || surface === 'popover' || surface === 'dialog') { const w = pickWindow(appEl, req); if (w.error) return fail(w.error); win = w; winInfo = w.info; }
|
|
849
|
+
const s = surfaceRoot(appEl, win, surface);
|
|
850
|
+
if (!s) return fail({ code: 'INVALID_ARGS', message: `unknown surface "${surface}"` });
|
|
851
|
+
if (s.error) return fail(s.error);
|
|
852
|
+
root = s.el; opt.pruneMenuBar = false;
|
|
853
|
+
if (surface === 'focused') {
|
|
854
|
+
const w = windowOfElement(appEl, s.el);
|
|
855
|
+
if (w) { container = w.info; winInfo = w.info; contEl = w.el; const p = pathUp(s.el, w.el); if (!p) return fail({ code: 'INTERNAL', message: 'could not place the element inside its window' }); basePath = p; }
|
|
856
|
+
else {
|
|
857
|
+
const mb = attr(appEl, 'AXMenuBar');
|
|
858
|
+
const pm = mb && mb.el ? pathUp(s.el, mb.el) : null;
|
|
859
|
+
if (pm) { container = { kind: 'menubar' }; basePath = pm; contEl = mb.el; }
|
|
860
|
+
else { const p = pathUp(s.el, appEl); if (!p) return fail({ code: 'INTERNAL', message: 'could not place the element inside its app' }); container = { kind: 'app' }; basePath = p; contEl = appEl; }
|
|
861
|
+
}
|
|
862
|
+
} else {
|
|
863
|
+
container = s.container; basePath = s.path || [];
|
|
864
|
+
// a sheet / popover / dialog inside a window starts its paths at the window; a dialog that is a
|
|
865
|
+
// window of its own, a menu or the menu bar is its own container
|
|
866
|
+
contEl = basePath.length && win ? win.el : root;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
// evidence of the path above the walk's root: none when the root is the container itself; for a drill
|
|
870
|
+
// or a surface inside a window, what resolve will re-derive along basePath
|
|
871
|
+
opt.rootIsContainer = !basePath.length || !contEl || same(root, contEl);
|
|
872
|
+
if (!opt.rootIsContainer) {
|
|
873
|
+
const ev = pathEvidence(contEl, basePath, false);
|
|
874
|
+
if (!ev.ok) return fail({ code: 'STALE_REF', message: 'the element moved while the snapshot started — take a new snapshot', details: { kind: 'unplaceable' } });
|
|
875
|
+
opt.evidence = { shape: ev.shape, chain: ev.chain };
|
|
876
|
+
}
|
|
877
|
+
const t0 = now();
|
|
878
|
+
const rv = readNode(root);
|
|
879
|
+
if (rv.__err === -25204) return fail({ code: 'APP_UNRESPONSIVE', message: `"${app.name}" did not answer accessibility in time (it may be busy or hung)` });
|
|
880
|
+
const w = walk(root, basePath, opt);
|
|
881
|
+
const out = {
|
|
882
|
+
ok: true, app: app.name, bundle_id: app.bundle, pid: app.pid, surface, complete: w.complete,
|
|
883
|
+
container: containerOut(container), nodes: w.nodes, visited: w.visited, ms: now() - t0,
|
|
884
|
+
};
|
|
885
|
+
if (req.root) out.root_path = basePath;
|
|
886
|
+
if (winInfo) out.window = { title: winInfo.title, frame: winInfo.frame, n: winInfo.n, window_id: winInfo.wid };
|
|
887
|
+
if (webAx) out.web_accessibility = webAxStatus(webAx, root, basePath, surface === 'window');
|
|
888
|
+
return out;
|
|
889
|
+
}
|
|
890
|
+
function containerOut(c) {
|
|
891
|
+
if (!c) return { kind: 'app' };
|
|
892
|
+
if (c.kind === 'window') return { kind: 'window', wid: c.wid, title: c.title, subrole: c.subrole, frame: c.frame, n: c.n };
|
|
893
|
+
if (c.kind === 'menu') return { kind: 'menu', frame: c.frame };
|
|
894
|
+
return { kind: c.kind };
|
|
895
|
+
}
|
|
896
|
+
// The app a request is about: app (name, bundle id or .app path), else the owner of window_id (a
|
|
897
|
+
// CGWindowID from mac_windows), else the frontmost app.
|
|
898
|
+
function appForRequest(req) {
|
|
899
|
+
if (!req.app && req.window_id !== undefined && req.window_id !== null) {
|
|
900
|
+
const cg = cgWindow(Number(req.window_id));
|
|
901
|
+
return cg ? runningApps().find(a => a.pid === cg.pid) || null : null;
|
|
902
|
+
}
|
|
903
|
+
return findApp(req.app);
|
|
904
|
+
}
|
|
905
|
+
function appNotFound(req) {
|
|
906
|
+
if (!req.app && req.window_id !== undefined && req.window_id !== null) return { code: 'WINDOW_NOT_FOUND', message: `no window with id ${req.window_id}` };
|
|
907
|
+
return { code: 'APP_NOT_FOUND', message: req.app ? `no running app named "${req.app}"` : 'no frontmost app' };
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
function opFind(req) {
|
|
911
|
+
if (!$.AXIsProcessTrusted()) return fail(permError());
|
|
912
|
+
const app = appForRequest(req);
|
|
913
|
+
if (!app) return fail(appNotFound(req));
|
|
914
|
+
const appEl = appElement(app);
|
|
915
|
+
let webAx = null;
|
|
916
|
+
if (req.web_accessibility !== false && rendererOf(app) === 'chromium') webAx = enableWebAccessibility(appEl);
|
|
917
|
+
let root, container, basePath = [];
|
|
918
|
+
const surface = req.surface || 'window';
|
|
919
|
+
if (surface === 'menubar') { const s = surfaceRoot(appEl, null, 'menubar'); if (s.error) return fail(s.error); root = s.el; container = { kind: 'menubar' }; }
|
|
920
|
+
else if (surface === 'app') { root = appEl; container = { kind: 'app' }; }
|
|
921
|
+
else { const w = pickWindow(appEl, req); if (w.error) return fail(w.error); root = w.el; container = w.info; }
|
|
922
|
+
const f = { role: req.role, title: req.title, value: req.value, id: req.id, text: req.text, exact: Boolean(req.exact), limit: clamp(req.limit, 1, 50, 10) };
|
|
923
|
+
if (!(f.role || f.title || f.value || f.id || f.text)) return fail({ code: 'INVALID_ARGS', message: 'give at least one of role, title, value, id, text' });
|
|
924
|
+
const w = walk(root, basePath, { depth: 60, maxNodes: 100000, budgetMs: clamp(req.budget_ms, 500, 20000, 8000), maxVisit: 30000, find: f, pruneMenuBar: surface !== 'menubar', rootIsContainer: true });
|
|
925
|
+
const out = { ok: true, app: app.name, bundle_id: app.bundle, pid: app.pid, surface, container: containerOut(container), nodes: w.nodes, complete: w.complete, visited: w.visited };
|
|
926
|
+
if (webAx) out.web_accessibility = webAxStatus(webAx, root, basePath, surface === 'window');
|
|
927
|
+
return out;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
function opGet(req) {
|
|
931
|
+
const r = resolveTarget(req.target, 3000);
|
|
932
|
+
if (r.error) return fail(r.error);
|
|
933
|
+
const v = r.v;
|
|
934
|
+
const out = { ok: true, how: r.how, role: v.AXRole, title: nameOf(v) };
|
|
935
|
+
if (v.AXSubrole) out.subrole = v.AXSubrole;
|
|
936
|
+
if (typeof v.AXDescription === 'string' && v.AXDescription && v.AXDescription !== out.title) out.description = v.AXDescription;
|
|
937
|
+
const val = valueOf(v, clamp(req.max_chars, 1, 100000, 4000)); if (val !== undefined) out.value = val;
|
|
938
|
+
const fr = frameOf(v); if (fr) out.frame = fr;
|
|
939
|
+
out.states = statesOf(v);
|
|
940
|
+
out.actions = actionNames(r.el).map(a => a.replace(/^AX/, '').toLowerCase());
|
|
941
|
+
if (v.AXIdentifier) out.id = v.AXIdentifier;
|
|
942
|
+
const help = attr(r.el, 'AXHelp'); if (typeof help === 'string' && help) out.help = help.slice(0, 300);
|
|
943
|
+
out.settable = { value: settable(r.el, 'AXValue'), selected_text: settable(r.el, 'AXSelectedText'), focused: settable(r.el, 'AXFocused') };
|
|
944
|
+
out.children = (v.AXChildren || []).length;
|
|
945
|
+
return out;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
function opApps(req) {
|
|
949
|
+
const front = frontApp();
|
|
950
|
+
const apps = runningApps().filter(a => req.all || a.policy <= 1).map(a => ({
|
|
951
|
+
name: a.name, pid: a.pid, bundle_id: a.bundle, presentation: POLICY[a.policy] || 'helper',
|
|
952
|
+
frontmost: Boolean(front && front.pid === a.pid), hidden: a.hidden,
|
|
953
|
+
}));
|
|
954
|
+
const f = req.filter ? String(req.filter).toLowerCase() : '';
|
|
955
|
+
return { ok: true, apps: f ? apps.filter(a => a.name.toLowerCase().indexOf(f) >= 0 || a.bundle_id.toLowerCase().indexOf(f) >= 0) : apps };
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
function displays() {
|
|
959
|
+
const s = $.NSScreen.screens;
|
|
960
|
+
const out = [];
|
|
961
|
+
const n = Number(s.count);
|
|
962
|
+
// AppKit's origin is bottom-left of the main screen; accessibility and cliclick use top-left
|
|
963
|
+
const mainH = n ? Number(s.objectAtIndex(0).frame.size.height) : 0;
|
|
964
|
+
for (let i = 0; i < n; i++) {
|
|
965
|
+
const sc = s.objectAtIndex(i);
|
|
966
|
+
const f = sc.frame;
|
|
967
|
+
const x = Number(f.origin.x), y = Number(f.origin.y), w = Number(f.size.width), h = Number(f.size.height);
|
|
968
|
+
let name = '';
|
|
969
|
+
try { name = sc.localizedName.js; } catch (e) { /* older macOS */ }
|
|
970
|
+
out.push({ index: i, name, frame: [Math.round(x), Math.round(mainH - y - h), Math.round(w), Math.round(h)], scale: Number(sc.backingScaleFactor), main: i === 0 });
|
|
971
|
+
}
|
|
972
|
+
return out;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
function opWindows(req) {
|
|
976
|
+
const opts = req.include_offscreen ? $.kCGWindowListOptionAll : ($.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements);
|
|
977
|
+
const info = cast($.CGWindowListCopyWindowInfo(opts, 0));
|
|
978
|
+
const front = frontApp();
|
|
979
|
+
const out = [];
|
|
980
|
+
let named = 0;
|
|
981
|
+
const n = info ? Number(info.count) : 0;
|
|
982
|
+
const wantApp = req.app ? String(req.app).toLowerCase() : '';
|
|
983
|
+
for (let i = 0; i < n; i++) {
|
|
984
|
+
const d = info.objectAtIndex(i);
|
|
985
|
+
const get = k => { const o = d.objectForKey(ks(k)); return o && !o.isNil() ? o : null; };
|
|
986
|
+
const layer = Number(get('kCGWindowLayer') ? get('kCGWindowLayer').js : 0);
|
|
987
|
+
if (layer !== 0 && !req.all_layers) continue;
|
|
988
|
+
const owner = get('kCGWindowOwnerName') ? get('kCGWindowOwnerName').js : '';
|
|
989
|
+
if (wantApp && owner.toLowerCase().indexOf(wantApp) < 0) continue;
|
|
990
|
+
const b = get('kCGWindowBounds');
|
|
991
|
+
const bounds = b ? [Math.round(Number(b.objectForKey(ks('X')).js)), Math.round(Number(b.objectForKey(ks('Y')).js)), Math.round(Number(b.objectForKey(ks('Width')).js)), Math.round(Number(b.objectForKey(ks('Height')).js))] : null;
|
|
992
|
+
const title = get('kCGWindowName') ? get('kCGWindowName').js : null;
|
|
993
|
+
if (title !== null) named++;
|
|
994
|
+
const pid = Number(get('kCGWindowOwnerPID') ? get('kCGWindowOwnerPID').js : 0);
|
|
995
|
+
out.push({ id: Number(get('kCGWindowNumber').js), app: owner, pid, title, bounds, onscreen: Boolean(get('kCGWindowIsOnscreen') && get('kCGWindowIsOnscreen').js), layer, frontmost_app: Boolean(front && front.pid === pid) });
|
|
996
|
+
}
|
|
997
|
+
// Without Screen Recording permission window titles are withheld; fill them from accessibility.
|
|
998
|
+
if ($.AXIsProcessTrusted()) {
|
|
999
|
+
const byPid = {};
|
|
1000
|
+
for (const w of out) if (w.title === null || w.title === '') (byPid[w.pid] = byPid[w.pid] || []).push(w);
|
|
1001
|
+
for (const pid of Object.keys(byPid)) {
|
|
1002
|
+
const appEl = $.AXUIElementCreateApplication(Number(pid));
|
|
1003
|
+
$.AXUIElementSetMessagingTimeout(appEl, 1.0);
|
|
1004
|
+
const ws = windowsOf(appEl);
|
|
1005
|
+
for (let i = 0; i < ws.length; i++) {
|
|
1006
|
+
const wi = windowInfo(ws[i], i);
|
|
1007
|
+
const hit = byPid[pid].find(x => rectNear(x.bounds, wi.frame, 2));
|
|
1008
|
+
if (hit) { hit.title = wi.title; hit.ax_index = i; }
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
return { ok: true, windows: out, displays: displays(), titles_from_screen_recording: named > 0 };
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
function opStatus(req) {
|
|
1016
|
+
const front = frontApp();
|
|
1017
|
+
let screenRecording = null;
|
|
1018
|
+
try {
|
|
1019
|
+
// window titles of other apps are visible only with Screen Recording permission
|
|
1020
|
+
const info = cast($.CGWindowListCopyWindowInfo($.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements, 0));
|
|
1021
|
+
const n = info ? Number(info.count) : 0;
|
|
1022
|
+
const me = Number($.NSProcessInfo.processInfo.processIdentifier);
|
|
1023
|
+
let others = 0, named = 0;
|
|
1024
|
+
for (let i = 0; i < n; i++) {
|
|
1025
|
+
const d = info.objectAtIndex(i);
|
|
1026
|
+
const pid = Number(d.objectForKey(ks('kCGWindowOwnerPID')).js);
|
|
1027
|
+
if (pid === me) continue;
|
|
1028
|
+
others++;
|
|
1029
|
+
const t = d.objectForKey(ks('kCGWindowName'));
|
|
1030
|
+
if (t && !t.isNil()) named++;
|
|
1031
|
+
}
|
|
1032
|
+
screenRecording = others ? named > 0 : null;
|
|
1033
|
+
} catch (e) { /* unknown */ }
|
|
1034
|
+
const ver = $.NSProcessInfo.processInfo.operatingSystemVersion;
|
|
1035
|
+
return {
|
|
1036
|
+
ok: true, accessibility: Boolean($.AXIsProcessTrusted()), screen_recording: screenRecording,
|
|
1037
|
+
frontmost: front ? { name: front.name, pid: front.pid, bundle_id: front.bundle } : null,
|
|
1038
|
+
macos: `${Number(ver.majorVersion)}.${Number(ver.minorVersion)}.${Number(ver.patchVersion)}`,
|
|
1039
|
+
displays: displays(),
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
function clamp(v, lo, hi, dflt) { const n = Number(v); if (!Number.isFinite(n)) return dflt; return Math.min(Math.max(Math.round(n), lo), hi); }
|
|
1044
|
+
function fail(e) { const o = { ok: false, code: e.code, message: e.message }; if (e.details) o.details = e.details; if (e.delivery) o.delivery = e.delivery; if (e.retry) o.retry = e.retry; return o; }
|
|
1045
|
+
|
|
1046
|
+
// ── actions ──────────────────────────────────────────────────────────────────────────────────────
|
|
1047
|
+
const YES = () => $.NSNumber.numberWithBool(true);
|
|
1048
|
+
const NO = () => $.NSNumber.numberWithBool(false);
|
|
1049
|
+
function perform(el, action) { return Number($.AXUIElementPerformAction(el, ks(action))); }
|
|
1050
|
+
function setAttr(el, name, value) { return Number($.AXUIElementSetAttributeValue(el, ks(name), value)); }
|
|
1051
|
+
function notDelivered(e) { return Object.assign({ delivery: 'not_delivered', retry: 'safe' }, e); }
|
|
1052
|
+
|
|
1053
|
+
// AX error code of a write or an action → what it means for delivery
|
|
1054
|
+
function axCallError(code, what) {
|
|
1055
|
+
if (code === -25204) return { code: 'APP_UNRESPONSIVE', message: `${what}: the app did not answer in time (it may still have acted, e.g. a menu that opened) — look before retrying`, delivery: 'unknown', retry: 'unsafe' };
|
|
1056
|
+
if (code === -25206) return notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${what}: the element does not support it` });
|
|
1057
|
+
if (code === -25205) return notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${what}: the element has no such attribute` });
|
|
1058
|
+
if (code === -25202) return notDelivered({ code: 'STALE_REF', message: `${what}: the element no longer exists`, details: { kind: 'invalid_element' } });
|
|
1059
|
+
if (code === -25211) return notDelivered(permError());
|
|
1060
|
+
if (code === -25201) return notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${what}: the app rejected the value` });
|
|
1061
|
+
return { code: 'ACTION_FAILED', message: `${what}: accessibility error ${code}`, delivery: 'unknown', retry: 'unsafe' };
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// Transient checks are polled until the budget runs out: the element must still exist and be enabled.
|
|
1065
|
+
function waitActionable(el, timeoutMs) {
|
|
1066
|
+
const end = now() + timeoutMs;
|
|
1067
|
+
for (;;) {
|
|
1068
|
+
const v = readNode(el);
|
|
1069
|
+
if (v.__err) return { error: notDelivered({ code: 'STALE_REF', message: 'the element disappeared', details: { kind: 'gone' } }) };
|
|
1070
|
+
if (v.AXEnabled !== false) return { v };
|
|
1071
|
+
if (now() >= end) return { error: notDelivered({ code: 'NOT_ACTIONABLE', message: 'the element is disabled', details: { kind: 'disabled' } }) };
|
|
1072
|
+
sleep(100);
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
function menuOpen(appEl) {
|
|
1077
|
+
const mb = attr(appEl, 'AXMenuBar');
|
|
1078
|
+
if (mb && mb.el) for (const item of children(mb.el)) if (attr(item, 'AXSelected') === true) return true;
|
|
1079
|
+
const f = attr(appEl, 'AXFocusedUIElement');
|
|
1080
|
+
if (f && f.el) { const r = attr(f.el, 'AXRole'); if (r === 'AXMenu' || r === 'AXMenuItem') return true; }
|
|
1081
|
+
return false;
|
|
1082
|
+
}
|
|
1083
|
+
// What an action could change, read before and after it. Comparing the two is the delivery evidence.
|
|
1084
|
+
function observeState(el, appEl) {
|
|
1085
|
+
const o = { gone: true };
|
|
1086
|
+
if (el) {
|
|
1087
|
+
const v = readNode(el);
|
|
1088
|
+
if (!v.__err) {
|
|
1089
|
+
o.gone = false;
|
|
1090
|
+
o.value = v.AXValue === undefined ? null : typeof v.AXValue === 'string' ? vhash(v.AXValue) : v.AXValue;
|
|
1091
|
+
o.selected = v.AXSelected === undefined ? null : v.AXSelected;
|
|
1092
|
+
o.expanded = v.AXExpanded === undefined ? null : v.AXExpanded;
|
|
1093
|
+
o.focused = v.AXFocused === undefined ? null : v.AXFocused;
|
|
1094
|
+
o.title = nameOf(v);
|
|
1095
|
+
o.enabled = v.AXEnabled === undefined ? null : v.AXEnabled;
|
|
1096
|
+
o.frame = frameOf(v);
|
|
1097
|
+
const sr = attr(el, 'AXSelectedTextRange'); if (sr) o.selection = sr;
|
|
1098
|
+
const sb = attr(el, 'AXVerticalScrollBar'); if (sb && sb.el) o.vscroll = attr(sb.el, 'AXValue');
|
|
1099
|
+
const hb = attr(el, 'AXHorizontalScrollBar'); if (hb && hb.el) o.hscroll = attr(hb.el, 'AXValue');
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
const ws = windowsOf(appEl);
|
|
1103
|
+
o.windows = ws.map(w => `${attr(w, 'AXSubrole') || ''}:${attr(w, 'AXTitle') || ''}`);
|
|
1104
|
+
o.sheets = 0;
|
|
1105
|
+
for (const w of ws) for (const k of children(w)) if (attr(k, 'AXRole') === 'AXSheet') o.sheets++;
|
|
1106
|
+
o.menu = menuOpen(appEl);
|
|
1107
|
+
const f = attr(appEl, 'AXFocusedUIElement');
|
|
1108
|
+
if (f && f.el) { const fv = readNode(f.el); o.focus = `${fv.AXRole || ''}:${nameOf(fv).slice(0, 60)}`; }
|
|
1109
|
+
const fw = attr(appEl, 'AXFocusedWindow');
|
|
1110
|
+
o.focusedWindow = fw && fw.el ? attr(fw.el, 'AXTitle') || '' : null;
|
|
1111
|
+
const fa = frontApp();
|
|
1112
|
+
o.frontmost = fa ? fa.pid : null;
|
|
1113
|
+
return o;
|
|
1114
|
+
}
|
|
1115
|
+
const STATE_KEYS = ['gone', 'value', 'selection', 'selected', 'expanded', 'focused', 'title', 'enabled', 'frame', 'vscroll', 'hscroll', 'menu', 'focus', 'focusedWindow', 'sheets', 'windows', 'frontmost'];
|
|
1116
|
+
const WEAK_STATE_KEYS = new Set(['frontmost', 'focusedWindow', 'focus']);
|
|
1117
|
+
function diffState(a, b, keys) {
|
|
1118
|
+
const changed = STATE_KEYS.filter(k => JSON.stringify(a[k] === undefined ? null : a[k]) !== JSON.stringify(b[k] === undefined ? null : b[k]));
|
|
1119
|
+
const allowed = Array.isArray(keys) ? new Set(keys) : null;
|
|
1120
|
+
const verified = changed.some(k => !WEAK_STATE_KEYS.has(k) && (!allowed || allowed.has(k)) && !(b.gone === true && k !== 'gone' && b[k] === undefined));
|
|
1121
|
+
const surfaces = [];
|
|
1122
|
+
if ((b.sheets || 0) > (a.sheets || 0)) surfaces.push('sheet');
|
|
1123
|
+
if (b.menu && !a.menu) surfaces.push('menu');
|
|
1124
|
+
for (const w of (b.windows || []).filter(x => (a.windows || []).indexOf(x) < 0)) {
|
|
1125
|
+
const [sub, ...t] = w.split(':');
|
|
1126
|
+
surfaces.push(`${/Dialog/.test(sub) ? 'dialog' : 'window'} "${t.join(':').slice(0, 60)}"`);
|
|
1127
|
+
}
|
|
1128
|
+
return { changed, verified, surfaces };
|
|
1129
|
+
}
|
|
1130
|
+
function verdict(before, after, extra, keys) {
|
|
1131
|
+
if (Array.isArray(extra) && keys === undefined) { keys = extra; extra = {}; }
|
|
1132
|
+
const d = diffState(before, after, keys);
|
|
1133
|
+
return Object.assign({ ok: true, delivery: d.verified ? 'delivered_verified' : 'delivered_unverified', retry: 'unsafe', changed: d.changed, surfaces: d.surfaces }, extra || {});
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
const PRESS_ACTIONS = ['AXPress', 'AXConfirm', 'AXPick', 'AXOpen'];
|
|
1137
|
+
// Semantic activation: the element's own action, never the pointer. `auto_press` picks the element's
|
|
1138
|
+
// primary action, or selects a row / cell / tab that has none.
|
|
1139
|
+
function opAct(req) {
|
|
1140
|
+
const r = resolveTarget(req.target, 3000);
|
|
1141
|
+
if (r.error) return fail(notDelivered(r.error));
|
|
1142
|
+
const w = waitActionable(r.el, clamp(req.timeout_ms, 0, 30000, 3000));
|
|
1143
|
+
if (w.error) return fail(w.error);
|
|
1144
|
+
const v = w.v;
|
|
1145
|
+
const actions = actionNames(r.el);
|
|
1146
|
+
let action = req.action;
|
|
1147
|
+
if (action === 'auto_press') {
|
|
1148
|
+
action = PRESS_ACTIONS.find(a => actions.indexOf(a) >= 0) || null;
|
|
1149
|
+
if (!action && settable(r.el, 'AXSelected')) action = 'select';
|
|
1150
|
+
if (!action) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `the element (${v.AXRole}) offers no semantic activation`, details: { actions } }));
|
|
1151
|
+
}
|
|
1152
|
+
if (action !== 'select' && action !== 'focus' && actions.indexOf(action) < 0) {
|
|
1153
|
+
return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `the element (${v.AXRole}) does not offer ${action}`, details: { actions } }));
|
|
1154
|
+
}
|
|
1155
|
+
const before = observeState(r.el, r.appEl);
|
|
1156
|
+
const err = action === 'select' ? setAttr(r.el, 'AXSelected', YES()) : action === 'focus' ? setAttr(r.el, 'AXFocused', YES()) : perform(r.el, action);
|
|
1157
|
+
if (err !== 0) return fail(axCallError(err, action));
|
|
1158
|
+
sleep(clamp(req.settle_ms, 0, 3000, 300));
|
|
1159
|
+
const after = observeState(r.el, r.appEl);
|
|
1160
|
+
return verdict(before, after, { mechanism: 'semantic', action, how: r.how, role: v.AXRole, title: nameOf(v).slice(0, 60) });
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
function onSomeDisplay(x, y) { return displays().some(d => x >= d.frame[0] && y >= d.frame[1] && x < d.frame[0] + d.frame[2] && y < d.frame[1] + d.frame[3]); }
|
|
1164
|
+
function appNameOfPid(pid) { const a = runningApps().find(x => x.pid === pid); return a ? a.name : ''; }
|
|
1165
|
+
// Does a pointer event at (x, y) reach the element? The element at that point must be the target or
|
|
1166
|
+
// inside it. An ancestor of the target is inconclusive (some controls are not hit-testable): the click
|
|
1167
|
+
// goes ahead, as agent-desktop's gate fails open. Anything else — another element, another app's
|
|
1168
|
+
// window — is an occluder, and nothing is sent.
|
|
1169
|
+
function hitTest(target, x, y) {
|
|
1170
|
+
const sys = $.AXUIElementCreateSystemWide();
|
|
1171
|
+
$.AXUIElementSetMessagingTimeout(sys, 2.0);
|
|
1172
|
+
const ref = Ref();
|
|
1173
|
+
const e = Number($.AXUIElementCopyElementAtPosition(sys, x, y, ref));
|
|
1174
|
+
if (e !== 0) return { verdict: 'unknown', reason: `hit test error ${e}` };
|
|
1175
|
+
const hit = cast(ref[0]);
|
|
1176
|
+
if (!hit) return { verdict: 'unknown', reason: 'no element at the point' };
|
|
1177
|
+
let cur = hit;
|
|
1178
|
+
for (let i = 0; i < 50 && cur; i++) { if (same(cur, target)) return { verdict: 'reaches' }; const p = attr(cur, 'AXParent'); cur = p && p.el ? p.el : null; }
|
|
1179
|
+
let up = target;
|
|
1180
|
+
for (let i = 0; i < 50 && up; i++) { if (same(up, hit)) return { verdict: 'unknown', reason: 'the point hits a container of the element' }; const p = attr(up, 'AXParent'); up = p && p.el ? p.el : null; }
|
|
1181
|
+
const hv = readNode(hit);
|
|
1182
|
+
const pr = Ref();
|
|
1183
|
+
let pid = 0;
|
|
1184
|
+
if (Number($.AXUIElementGetPid(hit, pr)) === 0) pid = Number(pr[0]);
|
|
1185
|
+
return { verdict: 'intercepted', occluder: { role: hv.AXRole || '?', title: nameOf(hv).slice(0, 60), app: appNameOfPid(pid) } };
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
// The frontmost app by pid (NSWorkspace — no System Events, no Automation permission), and whether a
|
|
1189
|
+
// given app (name, bundle id, .app path, or pid) is it. The server's focus guard asks this before it
|
|
1190
|
+
// sends keystrokes or a paste.
|
|
1191
|
+
function opFrontmost(req) {
|
|
1192
|
+
const f = frontApp();
|
|
1193
|
+
const out = { ok: true, front: f ? { pid: f.pid, name: f.name, bundle: f.bundle } : null };
|
|
1194
|
+
// at: [x, y] also reports whose window is on top at that point (raw-coordinate clicks check it first)
|
|
1195
|
+
if (Array.isArray(req.at) && req.at.length === 2 && req.at.every(v => typeof v === 'number' && isFinite(v))) out.top = cgTopAt(req.at[0], req.at[1]);
|
|
1196
|
+
if (req.pid !== undefined || req.app) {
|
|
1197
|
+
const t = req.pid !== undefined ? runningApps().find(a => a.pid === Number(req.pid)) || null : findApp(req.app);
|
|
1198
|
+
out.target = t ? { pid: t.pid, name: t.name, bundle: t.bundle } : null;
|
|
1199
|
+
out.match = Boolean(f && t && f.pid === t.pid);
|
|
1200
|
+
}
|
|
1201
|
+
return out;
|
|
1202
|
+
}
|
|
1203
|
+
// The topmost on-screen window at a point, front to back, as the window server stacks them. Skipped:
|
|
1204
|
+
// invisible windows (alpha 0), desktop-level ones (negative layer), and the Dock's full-display overlay,
|
|
1205
|
+
// which lets clicks through everywhere — only a Dock window as large as a whole display; the Dock itself
|
|
1206
|
+
// (its platter) and other Dock-owned strips do cover what is under them.
|
|
1207
|
+
function cgTopAt(x, y) {
|
|
1208
|
+
const list = cast($.CGWindowListCopyWindowInfo((1 << 0) | (1 << 4), 0)); // on screen only, no desktop elements
|
|
1209
|
+
if (!list) return null;
|
|
1210
|
+
let screens = null;
|
|
1211
|
+
for (let i = 0; i < Number(list.count); i++) {
|
|
1212
|
+
const d = list.objectAtIndex(i);
|
|
1213
|
+
const g = k => { const o = d.objectForKey(ks(k)); return o && !o.isNil() ? o.js : null; };
|
|
1214
|
+
const layer = Number(g('kCGWindowLayer')), alpha = Number(g('kCGWindowAlpha'));
|
|
1215
|
+
const owner = String(g('kCGWindowOwnerName') || '');
|
|
1216
|
+
if (!(alpha > 0) || layer < 0) continue;
|
|
1217
|
+
const b = d.objectForKey(ks('kCGWindowBounds'));
|
|
1218
|
+
if (!b || b.isNil()) continue;
|
|
1219
|
+
const [bx, by, bw, bh] = ['X', 'Y', 'Width', 'Height'].map(k => Number(b.objectForKey(ks(k)).js));
|
|
1220
|
+
if (bw * bh < 4 || x < bx || y < by || x >= bx + bw || y >= by + bh) continue;
|
|
1221
|
+
if (owner === 'Dock') {
|
|
1222
|
+
if (!screens) screens = displays().map(s => s.frame);
|
|
1223
|
+
if (screens.some(f => rectNear(f, [bx, by, bw, bh], 2))) continue;
|
|
1224
|
+
}
|
|
1225
|
+
return { pid: Number(g('kCGWindowOwnerPID')), owner, layer, wid: Number(g('kCGWindowNumber')) };
|
|
1226
|
+
}
|
|
1227
|
+
return null;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// Physical input on an element (count > 1, middle button, no semantic action, or asked for): resolve,
|
|
1231
|
+
// check it is enabled, on a display and not covered at its center, and hand the point plus the
|
|
1232
|
+
// before-state back to the server, which clicks with cliclick and then calls observe_after.
|
|
1233
|
+
function opPhysicalPrep(req) {
|
|
1234
|
+
const r = resolveTarget(req.target, 3000);
|
|
1235
|
+
if (r.error) return fail(notDelivered(r.error));
|
|
1236
|
+
const w = waitActionable(r.el, clamp(req.timeout_ms, 0, 30000, 3000));
|
|
1237
|
+
if (w.error) return fail(w.error);
|
|
1238
|
+
const fr = frameOf(w.v);
|
|
1239
|
+
if (!fr || fr[2] <= 0 || fr[3] <= 0) return fail(notDelivered({ code: 'NOT_ACTIONABLE', message: 'the element has no size on screen', details: { kind: 'no_frame' } }));
|
|
1240
|
+
const x = Math.round(fr[0] + fr[2] / 2), y = Math.round(fr[1] + fr[3] / 2);
|
|
1241
|
+
if (!onSomeDisplay(x, y)) return fail(notDelivered({ code: 'NOT_ACTIONABLE', message: `the element's center (${x},${y}) is off every display — scroll it into view (mac_scroll with element_index) or move the window`, details: { kind: 'offscreen' } }));
|
|
1242
|
+
if (attr(r.el, 'AXWindow') && attr(attr(r.el, 'AXWindow').el, 'AXMinimized') === true) return fail(notDelivered({ code: 'NOT_ACTIONABLE', message: 'the element\'s window is minimized', details: { kind: 'minimized' } }));
|
|
1243
|
+
const h = hitTest(r.el, x, y);
|
|
1244
|
+
if (h.verdict === 'intercepted') return fail(notDelivered({ code: 'OCCLUDED', message: `something else is on top of the element at ${x},${y} — bring its window to the front or close what covers it`, details: { occluder: h.occluder } }));
|
|
1245
|
+
if (h.verdict === 'unknown') {
|
|
1246
|
+
// the accessibility hit test was inconclusive (an error, nothing there, or only a container of the
|
|
1247
|
+
// element): the window server decides — the topmost window at the point must be the target app's
|
|
1248
|
+
const top = cgTopAt(x, y);
|
|
1249
|
+
if (!top) return fail(notDelivered({ code: 'NOT_ACTIONABLE', message: `no window is under ${x},${y} — the element is not visible there`, details: { kind: 'no_window_at_point' } }));
|
|
1250
|
+
if (top.pid !== r.app.pid) return fail(notDelivered({ code: 'OCCLUDED', message: `a window of "${top.owner}" is on top at ${x},${y} — bring the element's window to the front or close what covers it`, details: { occluder: { app: top.owner, layer: top.layer } } }));
|
|
1251
|
+
// the app's own window, but not the one the element is in (a floating panel, another document)
|
|
1252
|
+
// the element's own window id; else its AXWindow's; else (a window snapshot) the snapshot's window —
|
|
1253
|
+
// an unknown window id must not skip the check (R19)
|
|
1254
|
+
let ewid = axWindowId(r.el);
|
|
1255
|
+
if (!ewid) { const aw = attr(r.el, 'AXWindow'); ewid = aw && aw.el ? axWindowId(aw.el) : null; }
|
|
1256
|
+
if (!ewid) {
|
|
1257
|
+
// no AXWindow attribute: climb AXParent to the enclosing window (R20)
|
|
1258
|
+
let c = r.el;
|
|
1259
|
+
for (let k = 0; k < 64 && c && !ewid; k++) {
|
|
1260
|
+
const p = attr(c, 'AXParent');
|
|
1261
|
+
c = p && p.el ? p.el : null;
|
|
1262
|
+
if (c && attr(c, 'AXRole') === 'AXWindow') ewid = axWindowId(c);
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
if (!ewid && req.target && req.target.container && req.target.container.kind === 'window') ewid = (r.containerEl && axWindowId(r.containerEl)) || req.target.container.wid || null;
|
|
1266
|
+
if (ewid && top.wid && top.wid !== ewid) return fail(notDelivered({ code: 'OCCLUDED', message: `another window of "${top.owner}" is on top at ${x},${y} — bring the element's window to the front or close what covers it`, details: { occluder: { app: top.owner, layer: top.layer, other_window: true } } }));
|
|
1267
|
+
h.reason = (h.reason ? h.reason + '; ' : '') + 'the topmost window there is the app\'s own';
|
|
1268
|
+
}
|
|
1269
|
+
return { ok: true, point: [x, y], hit: h.verdict, reason: h.reason, pid: r.app.pid, before: observeState(r.el, r.appEl), role: w.v.AXRole, title: nameOf(w.v).slice(0, 60), how: r.how };
|
|
1270
|
+
}
|
|
1271
|
+
const ABSENT_CODES = new Set(['STALE_REF', 'WINDOW_NOT_FOUND', 'APP_NOT_FOUND']);
|
|
1272
|
+
function resolveOrError(target, budgetMs) {
|
|
1273
|
+
let r;
|
|
1274
|
+
try { r = resolveTarget(target, budgetMs); }
|
|
1275
|
+
catch (e) { return { error: { code: 'INTERNAL', message: String(e && e.message || e).slice(0, 200) } }; }
|
|
1276
|
+
try {
|
|
1277
|
+
if (!r.error) {
|
|
1278
|
+
if ((r.containerEl && readNode(r.containerEl).__err === -25204) || (r.appEl && readNode(r.appEl).__err === -25204) || (r.el && readNode(r.el).__err === -25204)) {
|
|
1279
|
+
return { error: { code: 'APP_UNRESPONSIVE', message: 'the app did not answer accessibility in time' } };
|
|
1280
|
+
}
|
|
1281
|
+
return r;
|
|
1282
|
+
}
|
|
1283
|
+
if (r.error.code === 'STALE_REF' && target && target.pid !== undefined) {
|
|
1284
|
+
const apps = runningApps().filter(a => a.pid === target.pid);
|
|
1285
|
+
if (apps.length) {
|
|
1286
|
+
const appEl = appElement(apps[0]);
|
|
1287
|
+
if (readNode(appEl).__err === -25204 || windowsOf(appEl).some(w => readNode(w).__err === -25204)) {
|
|
1288
|
+
return { error: { code: 'APP_UNRESPONSIVE', message: 'the app did not answer accessibility in time' } };
|
|
1289
|
+
}
|
|
1290
|
+
const c = containerEl(appEl, target.container);
|
|
1291
|
+
if (!c.error && c.el) {
|
|
1292
|
+
if (readNode(c.el).__err === -25204) return { error: { code: 'APP_UNRESPONSIVE', message: 'the app did not answer accessibility in time' } };
|
|
1293
|
+
const skipMenuBar = (target.container && target.container.kind || 'app') !== 'menubar';
|
|
1294
|
+
const pe = Array.isArray(target.path) ? pathEvidence(c.el, target.path, skipMenuBar) : { ok: false };
|
|
1295
|
+
if (pe.ok && readNode(pe.el).__err === -25204) return { error: { code: 'APP_UNRESPONSIVE', message: 'the app did not answer accessibility in time' } };
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
} catch (e) { return { error: { code: 'INTERNAL', message: String(e && e.message || e).slice(0, 200) } }; }
|
|
1300
|
+
return r;
|
|
1301
|
+
}
|
|
1302
|
+
function opObserveAfter(req) {
|
|
1303
|
+
const r = resolveOrError(req.target, 2000);
|
|
1304
|
+
let after;
|
|
1305
|
+
if (r.error) {
|
|
1306
|
+
if (!ABSENT_CODES.has(r.error.code)) {
|
|
1307
|
+
return { ok: true, delivery: 'delivered_unverified', retry: 'unsafe', changed: [], surfaces: [], note: `could not read the element after the action (${r.error.code})` };
|
|
1308
|
+
}
|
|
1309
|
+
// gone after the click: that is itself an observed change
|
|
1310
|
+
const apps = runningApps().filter(a => a.pid === req.target.pid);
|
|
1311
|
+
if (!apps.length) {
|
|
1312
|
+
const verified = !Array.isArray(req.keys) || req.keys.indexOf('gone') >= 0;
|
|
1313
|
+
return { ok: true, delivery: verified ? 'delivered_verified' : 'delivered_unverified', retry: 'unsafe', changed: ['gone', 'app_exited'], surfaces: [] };
|
|
1314
|
+
}
|
|
1315
|
+
try { after = observeState(null, appElement(apps[0])); }
|
|
1316
|
+
catch (e) { return { ok: true, delivery: 'delivered_unverified', retry: 'unsafe', changed: [], surfaces: [], note: 'could not read the element after the action (INTERNAL)' }; }
|
|
1317
|
+
} else {
|
|
1318
|
+
try { after = observeState(r.el, r.appEl); }
|
|
1319
|
+
catch (e) { return { ok: true, delivery: 'delivered_unverified', retry: 'unsafe', changed: [], surfaces: [], note: 'could not read the element after the action (INTERNAL)' }; }
|
|
1320
|
+
}
|
|
1321
|
+
return verdict(req.before || {}, after, {}, req.keys);
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
// Text into an element through accessibility: AXSelectedText inserts at the caret (replacing any
|
|
1325
|
+
// selection), AXValue replaces the whole value. No key events, so no input method can re-segment it
|
|
1326
|
+
// and the clipboard is not touched. Verified by reading the value back (secure fields cannot be read).
|
|
1327
|
+
function opInsertText(req) {
|
|
1328
|
+
let el, appEl, how = 'focused', label = 'the focused element';
|
|
1329
|
+
if (req.target) {
|
|
1330
|
+
const r = resolveTarget(req.target, 3000);
|
|
1331
|
+
if (r.error) return fail(notDelivered(r.error));
|
|
1332
|
+
el = r.el; appEl = r.appEl; how = r.how; label = 'the element';
|
|
1333
|
+
} else {
|
|
1334
|
+
const app = req.app ? findApp(req.app) : frontApp();
|
|
1335
|
+
if (!app) return fail(notDelivered({ code: 'APP_NOT_FOUND', message: req.app ? `no running app named "${req.app}"` : 'no frontmost app' }));
|
|
1336
|
+
appEl = appElement(app);
|
|
1337
|
+
const f = attr(appEl, 'AXFocusedUIElement');
|
|
1338
|
+
if (!f || !f.el) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `"${app.name}" reports no focused element`, details: { kind: 'no_focus' } }));
|
|
1339
|
+
el = f.el; label = `the focused element of "${app.name}"`;
|
|
1340
|
+
}
|
|
1341
|
+
const v = readNode(el);
|
|
1342
|
+
if (v.__err) return fail(notDelivered({ code: 'STALE_REF', message: 'the element disappeared', details: { kind: 'gone' } }));
|
|
1343
|
+
if (v.AXEnabled === false) return fail(notDelivered({ code: 'NOT_ACTIONABLE', message: `${label} is disabled`, details: { kind: 'disabled' } }));
|
|
1344
|
+
const canSel = settable(el, 'AXSelectedText'), canVal = settable(el, 'AXValue');
|
|
1345
|
+
if (req.replace ? !canVal : !(canSel || canVal)) {
|
|
1346
|
+
// text-like but read-only through accessibility (a terminal, a custom editor) vs. not text at all
|
|
1347
|
+
// (a button, a list, a sheet): the server only falls back to keystrokes for the first kind
|
|
1348
|
+
const textlike = TEXT_ROLES.has(roleKey(v)) || v.AXRole === 'AXWebArea' || attr(el, 'AXSelectedTextRange') !== null || attr(el, 'AXInsertionPointLineNumber') !== null;
|
|
1349
|
+
return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${label} (${v.AXRole}${v.AXSubrole ? '/' + v.AXSubrole : ''}) takes no text through accessibility${textlike ? '' : ' and is not a text input — focus a text field first'}`, details: { kind: 'not_text', role: v.AXRole, textlike } }));
|
|
1350
|
+
}
|
|
1351
|
+
const text = String(req.text);
|
|
1352
|
+
const secure = v.AXSubrole === 'AXSecureTextField';
|
|
1353
|
+
const before = typeof v.AXValue === 'string' ? v.AXValue : null;
|
|
1354
|
+
const beforeLen = attr(el, 'AXNumberOfCharacters');
|
|
1355
|
+
const beforeSel = JSON.stringify(attr(el, 'AXSelectedTextRange'));
|
|
1356
|
+
let err, via;
|
|
1357
|
+
if (req.replace) { err = setAttr(el, 'AXValue', $(text)); via = 'AXValue'; }
|
|
1358
|
+
else if (canSel) { err = setAttr(el, 'AXSelectedText', $(text)); via = 'AXSelectedText'; }
|
|
1359
|
+
else { err = setAttr(el, 'AXValue', $((before || '') + text)); via = 'AXValue (append)'; }
|
|
1360
|
+
if (err !== 0) return fail(axCallError(err, via));
|
|
1361
|
+
const deadline = now() + WRITE_POLL_MS;
|
|
1362
|
+
sleep(150);
|
|
1363
|
+
let after = attr(el, 'AXValue');
|
|
1364
|
+
const base = { ok: true, mechanism: 'semantic', via, how, role: v.AXRole };
|
|
1365
|
+
if (secure || typeof after !== 'string') return Object.assign(base, { delivery: 'delivered_unverified', retry: 'unsafe', reason: secure ? 'secure_field' : 'value_unreadable' });
|
|
1366
|
+
const isOk = (a) => typeof a === 'string' && (req.replace ? a === text : a !== before && a.indexOf(text) >= 0);
|
|
1367
|
+
let moved = attr(el, 'AXNumberOfCharacters') !== beforeLen || JSON.stringify(attr(el, 'AXSelectedTextRange')) !== beforeSel;
|
|
1368
|
+
if (!isOk(after) && after === before && !moved) {
|
|
1369
|
+
for (let i = 0; i < 6 && now() < deadline; i++) {
|
|
1370
|
+
sleep(100);
|
|
1371
|
+
after = attr(el, 'AXValue');
|
|
1372
|
+
if (typeof after !== 'string') return Object.assign(base, { delivery: 'delivered_unverified', retry: 'unsafe', reason: 'value_unreadable' });
|
|
1373
|
+
moved = attr(el, 'AXNumberOfCharacters') !== beforeLen || JSON.stringify(attr(el, 'AXSelectedTextRange')) !== beforeSel;
|
|
1374
|
+
if (after !== before) break;
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
if (isOk(after)) return Object.assign(base, { delivery: 'delivered_verified', retry: 'unsafe', length: after.length });
|
|
1378
|
+
if (after === before && !moved) {
|
|
1379
|
+
return fail({ code: 'NOT_CONFIRMED', message: `${label} did not change — the app ignored the accessibility write; mac_type with mechanism:"physical" or mac_paste sends real keystrokes instead`, delivery: 'delivered_unverified', retry: 'unsafe', details: { role: v.AXRole } });
|
|
1380
|
+
}
|
|
1381
|
+
if (after === before && moved) {
|
|
1382
|
+
// the caret or the length moved but the value reads the same: something happened, not shown to be the text
|
|
1383
|
+
return Object.assign(base, { delivery: 'delivered_unverified', retry: 'unsafe', reason: 'selection_moved' });
|
|
1384
|
+
}
|
|
1385
|
+
return fail({ code: 'NOT_CONFIRMED', message: `${label} changed but does not show the text`, delivery: 'unknown', retry: 'unsafe' });
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
// after an accessibility write the app accepted, how long to look for the value to show it: the answer
|
|
1389
|
+
// only decides verified vs unverified (an unchanged value is still reported delivered_unverified)
|
|
1390
|
+
const WRITE_POLL_MS = 400;
|
|
1391
|
+
function parseBool(s) {
|
|
1392
|
+
const t = String(s).trim().toLowerCase();
|
|
1393
|
+
if (['true', '1', 'on', 'yes', 'checked', 'selected', 'expanded', 'open'].indexOf(t) >= 0) return true;
|
|
1394
|
+
if (['false', '0', 'off', 'no', 'unchecked', 'deselected', 'collapsed', 'closed'].indexOf(t) >= 0) return false;
|
|
1395
|
+
return null;
|
|
1396
|
+
}
|
|
1397
|
+
function invalid(msg) { return fail(notDelivered({ code: 'INVALID_ARGS', message: msg })); }
|
|
1398
|
+
function isOn(v) { return v.AXValue === 1 || v.AXValue === true; }
|
|
1399
|
+
function toggleState(v) {
|
|
1400
|
+
if (v.AXValue === 2) return 'mixed';
|
|
1401
|
+
if (v.AXValue === 1 || v.AXValue === true) return true;
|
|
1402
|
+
if (v.AXValue === 0 || v.AXValue === false) return false;
|
|
1403
|
+
return null;
|
|
1404
|
+
}
|
|
1405
|
+
function toggleLabel(s) { return s === 'mixed' ? 'mixed' : s === true ? 'on' : s === false ? 'off' : 'unknown'; }
|
|
1406
|
+
function normOption(s) { return String(s).replace(/\s+/g, ' ').trim().replace(/(?:\s*(?:…|\.{3}))+$/, '').toLowerCase(); }
|
|
1407
|
+
|
|
1408
|
+
function findOpenMenu(el, appEl) {
|
|
1409
|
+
for (const k of children(el)) if (attr(k, 'AXRole') === 'AXMenu') return k;
|
|
1410
|
+
// some pop-ups attach the menu elsewhere: look at the app's focused element and its ancestors
|
|
1411
|
+
const f = attr(appEl, 'AXFocusedUIElement');
|
|
1412
|
+
let cur = f && f.el ? f.el : null;
|
|
1413
|
+
for (let i = 0; i < 6 && cur; i++) { if (attr(cur, 'AXRole') === 'AXMenu') return cur; const p = attr(cur, 'AXParent'); cur = p && p.el ? p.el : null; }
|
|
1414
|
+
return null;
|
|
1415
|
+
}
|
|
1416
|
+
function chooseOption(r, want, timeoutMs) {
|
|
1417
|
+
const acts = actionNames(r.el);
|
|
1418
|
+
const opener = acts.indexOf('AXPress') >= 0 ? 'AXPress' : acts.indexOf('AXShowMenu') >= 0 ? 'AXShowMenu' : null;
|
|
1419
|
+
if (!opener) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: 'the control does not open a menu', details: { actions: acts } }));
|
|
1420
|
+
const e = perform(r.el, opener);
|
|
1421
|
+
if (e !== 0 && e !== -25204) return fail(axCallError(e, opener));
|
|
1422
|
+
let menu = null;
|
|
1423
|
+
const end = now() + Math.min(timeoutMs, 3000);
|
|
1424
|
+
while (!menu && now() < end) { sleep(150); menu = findOpenMenu(r.el, r.appEl); }
|
|
1425
|
+
if (!menu) return fail({ code: 'ACTION_FAILED', message: 'the menu did not open', delivery: 'unknown', retry: 'unsafe' });
|
|
1426
|
+
const items = children(menu).map(k => ({ el: k, title: String(attr(k, 'AXTitle') || ''), enabled: attr(k, 'AXEnabled') !== false })).filter(i => i.title);
|
|
1427
|
+
const wantStr = String(want);
|
|
1428
|
+
const w = wantStr.toLowerCase();
|
|
1429
|
+
let hit = items.filter(i => i.title === wantStr);
|
|
1430
|
+
if (!hit.length) hit = items.filter(i => i.title.toLowerCase() === w);
|
|
1431
|
+
if (!hit.length) { const nw = normOption(wantStr); hit = items.filter(i => normOption(i.title) === nw); }
|
|
1432
|
+
if (hit.length !== 1 || !hit[0].enabled) {
|
|
1433
|
+
perform(menu, 'AXCancel');
|
|
1434
|
+
const why = hit.length > 1 ? `${hit.length} options match "${want}"` : hit.length ? `option "${hit[0].title}" is disabled` : `no option matches "${want}"`;
|
|
1435
|
+
return fail({ code: hit.length > 1 ? 'AMBIGUOUS_TARGET' : 'ACTION_FAILED', message: `${why} (the menu was opened and closed again)`, details: { options: items.slice(0, 40).map(i => i.title) }, delivery: 'not_delivered', retry: 'safe' });
|
|
1436
|
+
}
|
|
1437
|
+
const pe = perform(hit[0].el, 'AXPress');
|
|
1438
|
+
if (pe !== 0 && pe !== -25204) { perform(menu, 'AXCancel'); return fail(axCallError(pe, 'AXPress on the option')); }
|
|
1439
|
+
sleep(300);
|
|
1440
|
+
const after = readNode(r.el);
|
|
1441
|
+
const shown = [after.AXValue, after.AXTitle, nameOf(after)].map(x => String(x === undefined || x === null ? '' : x));
|
|
1442
|
+
const okv = shown.some(s => s === hit[0].title);
|
|
1443
|
+
// a changed value that does not show the chosen option is not proof it was chosen
|
|
1444
|
+
return { ok: true, mechanism: 'semantic', via: 'menu option', option: hit[0].title, delivery: okv ? 'delivered_verified' : 'delivered_unverified', retry: 'unsafe', value: after.AXValue === undefined ? null : after.AXValue };
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
// Role-aware value setting: text, toggles (idempotent), disclosure, selection, menu options, numbers.
|
|
1448
|
+
// Like every action it reports what opened as a result (a sheet, a dialog, a menu left open).
|
|
1449
|
+
function opSetValue(req) {
|
|
1450
|
+
const r = resolveTarget(req.target, 3000);
|
|
1451
|
+
if (r.error) return fail(notDelivered(r.error));
|
|
1452
|
+
const before = observeState(r.el, r.appEl);
|
|
1453
|
+
const res = setValueCore(req, r);
|
|
1454
|
+
if (res.ok && res.delivery !== 'not_delivered') {
|
|
1455
|
+
const d = diffState(before, observeState(r.el, r.appEl));
|
|
1456
|
+
if (d.surfaces.length) res.surfaces = d.surfaces;
|
|
1457
|
+
}
|
|
1458
|
+
return res;
|
|
1459
|
+
}
|
|
1460
|
+
function setValueCore(req, r) {
|
|
1461
|
+
const timeoutMs = clamp(req.timeout_ms, 0, 30000, 3000);
|
|
1462
|
+
const w = waitActionable(r.el, timeoutMs);
|
|
1463
|
+
if (w.error) return fail(w.error);
|
|
1464
|
+
const v = w.v;
|
|
1465
|
+
const role = roleKey(v);
|
|
1466
|
+
const val = String(req.value === undefined || req.value === null ? '' : req.value);
|
|
1467
|
+
const acts = actionNames(r.el);
|
|
1468
|
+
const done = (delivery, extra) => Object.assign({ ok: true, mechanism: 'semantic', role: v.AXRole, how: r.how, delivery, retry: delivery === 'not_delivered' ? 'safe' : 'unsafe' }, extra || {});
|
|
1469
|
+
|
|
1470
|
+
if (TOGGLE_ROLES.has(role) || TOGGLE_ROLES.has(v.AXRole) || v.AXSubrole === 'AXToggle') {
|
|
1471
|
+
const want = val.trim().toLowerCase() === 'mixed' ? 'mixed' : parseBool(val);
|
|
1472
|
+
if (want === null) return invalid('a checkbox, radio button or switch takes true or false');
|
|
1473
|
+
const cur = toggleState(v);
|
|
1474
|
+
if (cur === want) return done('not_delivered', { note: `already ${toggleLabel(want)} — nothing sent`, value: want });
|
|
1475
|
+
if (v.AXRole === 'AXRadioButton' && want !== true) return invalid('a radio button is turned off by choosing another one in its group');
|
|
1476
|
+
if (acts.indexOf('AXPress') < 0) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: 'the control cannot be pressed', details: { actions: acts } }));
|
|
1477
|
+
const e = perform(r.el, 'AXPress');
|
|
1478
|
+
if (e !== 0) return fail(axCallError(e, 'AXPress'));
|
|
1479
|
+
sleep(200);
|
|
1480
|
+
let afterState = toggleState(readNode(r.el));
|
|
1481
|
+
if (afterState !== want) {
|
|
1482
|
+
const e2 = perform(r.el, 'AXPress');
|
|
1483
|
+
if (e2 !== 0) return fail({ code: 'NOT_CONFIRMED', message: `pressed once, then second AXPress failed (${axCallError(e2, 'AXPress').message})`, delivery: 'unknown', retry: 'unsafe' });
|
|
1484
|
+
sleep(200);
|
|
1485
|
+
afterState = toggleState(readNode(r.el));
|
|
1486
|
+
}
|
|
1487
|
+
if (afterState === want) return done('delivered_verified', { value: want, via: 'AXPress' });
|
|
1488
|
+
return fail({ code: 'NOT_CONFIRMED', message: `pressed, but the control still reads ${toggleLabel(afterState)}`, delivery: 'unknown', retry: 'unsafe' });
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
const b = parseBool(val);
|
|
1492
|
+
if (b !== null && (role === 'AXDisclosureTriangle' || settable(r.el, 'AXExpanded') || settable(r.el, 'AXDisclosing') || (v.AXExpanded !== undefined && acts.indexOf('AXPress') >= 0 && (v.AXRole === 'AXRow' || v.AXRole === 'AXDisclosureTriangle')))) {
|
|
1493
|
+
const attrName = settable(r.el, 'AXExpanded') ? 'AXExpanded' : settable(r.el, 'AXDisclosing') ? 'AXDisclosing' : null;
|
|
1494
|
+
const cur = attr(r.el, attrName || 'AXExpanded') === true || (role === 'AXDisclosureTriangle' && isOn(v));
|
|
1495
|
+
if (cur === b) return done('not_delivered', { note: `already ${b ? 'expanded' : 'collapsed'} — nothing sent`, value: b });
|
|
1496
|
+
const e = attrName ? setAttr(r.el, attrName, b ? YES() : NO()) : perform(r.el, 'AXPress');
|
|
1497
|
+
if (e !== 0) return fail(axCallError(e, attrName || 'AXPress'));
|
|
1498
|
+
sleep(250);
|
|
1499
|
+
const now2 = attr(r.el, attrName || 'AXExpanded') === true || (role === 'AXDisclosureTriangle' && isOn(readNode(r.el)));
|
|
1500
|
+
return now2 === b ? done('delivered_verified', { value: b, via: attrName || 'AXPress' }) : fail({ code: 'NOT_CONFIRMED', message: `the element still reads ${now2 ? 'expanded' : 'collapsed'}`, delivery: 'unknown', retry: 'unsafe' });
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
if (b === true && (v.AXRole === 'AXRow' || v.AXRole === 'AXCell' || role === 'AXTab' || v.AXRole === 'AXMenuItem') && (settable(r.el, 'AXSelected') || acts.indexOf('AXPress') >= 0)) {
|
|
1504
|
+
if (v.AXSelected === true) return done('not_delivered', { note: 'already selected — nothing sent', value: true });
|
|
1505
|
+
const e = settable(r.el, 'AXSelected') ? setAttr(r.el, 'AXSelected', YES()) : perform(r.el, 'AXPress');
|
|
1506
|
+
if (e !== 0) return fail(axCallError(e, 'select'));
|
|
1507
|
+
sleep(200);
|
|
1508
|
+
return attr(r.el, 'AXSelected') === true ? done('delivered_verified', { value: true, via: 'AXSelected' }) : done('delivered_unverified', { value: true, via: 'AXSelected' });
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
if (v.AXRole === 'AXPopUpButton' || v.AXRole === 'AXMenuButton' || (v.AXRole === 'AXComboBox' && !settable(r.el, 'AXValue'))) {
|
|
1512
|
+
const res = chooseOption(r, val, timeoutMs);
|
|
1513
|
+
if (res.ok) { res.role = v.AXRole; res.how = r.how; }
|
|
1514
|
+
return res;
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
if (['AXSlider', 'AXIncrementor', 'AXLevelIndicator', 'AXStepper', 'AXScrollBar', 'AXValueIndicator'].indexOf(v.AXRole) >= 0) {
|
|
1518
|
+
const n = Number(val);
|
|
1519
|
+
if (!Number.isFinite(n)) return invalid(`a ${v.AXRole} takes a number`);
|
|
1520
|
+
const minV = attr(r.el, 'AXMinValue'), maxV = attr(r.el, 'AXMaxValue');
|
|
1521
|
+
if (typeof minV === 'number' && n < minV) return invalid(`${n} is below the minimum ${minV}`);
|
|
1522
|
+
if (typeof maxV === 'number' && n > maxV) return invalid(`${n} is above the maximum ${maxV}`);
|
|
1523
|
+
const tol = typeof minV === 'number' && typeof maxV === 'number' ? Math.max(Math.abs(maxV - minV) * 0.01, 1e-9) : 1e-6;
|
|
1524
|
+
if (typeof v.AXValue === 'number' && Math.abs(v.AXValue - n) <= tol) return done('not_delivered', { note: 'already at that value — nothing sent', value: v.AXValue });
|
|
1525
|
+
if (settable(r.el, 'AXValue')) {
|
|
1526
|
+
const e = setAttr(r.el, 'AXValue', $.NSNumber.numberWithDouble(n));
|
|
1527
|
+
if (e !== 0) return fail(axCallError(e, 'AXValue'));
|
|
1528
|
+
} else if (acts.indexOf('AXIncrement') >= 0 && acts.indexOf('AXDecrement') >= 0 && typeof v.AXValue === 'number') {
|
|
1529
|
+
let steps = 0;
|
|
1530
|
+
for (let i = 0; i < 200; i++) {
|
|
1531
|
+
const cur = attr(r.el, 'AXValue');
|
|
1532
|
+
if (typeof cur !== 'number' || Math.abs(cur - n) <= tol) break;
|
|
1533
|
+
const dir = cur < n ? 'AXIncrement' : 'AXDecrement';
|
|
1534
|
+
const e = perform(r.el, dir);
|
|
1535
|
+
if (e !== 0) {
|
|
1536
|
+
if (steps > 0) {
|
|
1537
|
+
const curNow = attr(r.el, 'AXValue');
|
|
1538
|
+
return done('delivered_unverified', { value: typeof curNow === 'number' ? curNow : cur, via: dir, note: `stopped after ${steps} steps: ${axCallError(e, 'step').message}` });
|
|
1539
|
+
}
|
|
1540
|
+
return fail(axCallError(e, 'step'));
|
|
1541
|
+
}
|
|
1542
|
+
steps++;
|
|
1543
|
+
const nxt = attr(r.el, 'AXValue');
|
|
1544
|
+
if (nxt === cur || (cur < n && nxt > n) || (cur > n && nxt < n)) break;
|
|
1545
|
+
}
|
|
1546
|
+
} else return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: 'the value cannot be set', details: { actions: acts } }));
|
|
1547
|
+
sleep(150);
|
|
1548
|
+
const after = attr(r.el, 'AXValue');
|
|
1549
|
+
return typeof after === 'number' && Math.abs(after - n) <= tol ? done('delivered_verified', { value: after, via: 'AXValue' }) : done('delivered_unverified', { value: after, via: 'AXValue', note: 'the control settled on a different value (it may step)' });
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
if (settable(r.el, 'AXValue')) {
|
|
1553
|
+
const secure = v.AXSubrole === 'AXSecureTextField';
|
|
1554
|
+
const numeric = !secure && typeof v.AXValue === 'number';
|
|
1555
|
+
const beforeLen = attr(r.el, 'AXNumberOfCharacters');
|
|
1556
|
+
const beforeSel = JSON.stringify(attr(r.el, 'AXSelectedTextRange'));
|
|
1557
|
+
const e = setAttr(r.el, 'AXValue', numeric && Number.isFinite(Number(val)) ? $.NSNumber.numberWithDouble(Number(val)) : $(val));
|
|
1558
|
+
if (e !== 0) return fail(axCallError(e, 'AXValue'));
|
|
1559
|
+
const deadline = now() + WRITE_POLL_MS;
|
|
1560
|
+
sleep(150);
|
|
1561
|
+
if (secure) return done('delivered_unverified', { secure: true, reason: 'secure_field', via: 'AXValue' });
|
|
1562
|
+
let after = attr(r.el, 'AXValue');
|
|
1563
|
+
if (after === null || after === undefined) return done('delivered_unverified', { reason: 'value_unreadable', via: 'AXValue' });
|
|
1564
|
+
const matchesVal = (a) => a !== null && a !== undefined && (String(a) === val || (numeric && Number(a) === Number(val)));
|
|
1565
|
+
let moved = attr(r.el, 'AXNumberOfCharacters') !== beforeLen || JSON.stringify(attr(r.el, 'AXSelectedTextRange')) !== beforeSel;
|
|
1566
|
+
if (!matchesVal(after) && JSON.stringify(after) === JSON.stringify(v.AXValue) && !moved) {
|
|
1567
|
+
for (let i = 0; i < 6 && now() < deadline; i++) {
|
|
1568
|
+
sleep(100);
|
|
1569
|
+
after = attr(r.el, 'AXValue');
|
|
1570
|
+
if (after === null || after === undefined) return done('delivered_unverified', { reason: 'value_unreadable', via: 'AXValue' });
|
|
1571
|
+
moved = attr(r.el, 'AXNumberOfCharacters') !== beforeLen || JSON.stringify(attr(r.el, 'AXSelectedTextRange')) !== beforeSel;
|
|
1572
|
+
if (JSON.stringify(after) !== JSON.stringify(v.AXValue)) break;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
if (matchesVal(after)) return done('delivered_verified', { value: typeof after === 'string' ? after.slice(0, 200) : after, via: 'AXValue' });
|
|
1576
|
+
if (JSON.stringify(after) === JSON.stringify(v.AXValue) && !moved) {
|
|
1577
|
+
return fail({ code: 'NOT_CONFIRMED', message: 'the value did not change — the app ignored the write', delivery: 'delivered_unverified', retry: 'unsafe', details: { role: v.AXRole } });
|
|
1578
|
+
}
|
|
1579
|
+
if (JSON.stringify(after) === JSON.stringify(v.AXValue) && moved) {
|
|
1580
|
+
return done('delivered_unverified', { via: 'AXValue', reason: 'selection_moved' });
|
|
1581
|
+
}
|
|
1582
|
+
return fail({ code: 'NOT_CONFIRMED', message: 'the value changed but differs from what was set', delivery: 'unknown', retry: 'unsafe', details: { value: typeof after === 'string' ? after.slice(0, 200) : after } });
|
|
1583
|
+
}
|
|
1584
|
+
return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${v.AXRole} has no settable value here`, details: { actions: acts } }));
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
// Scroll an element into view (AXScrollToVisible), or find where to send wheel events for a scroll area.
|
|
1588
|
+
function opScrollPrep(req) {
|
|
1589
|
+
const r = resolveTarget(req.target, 3000);
|
|
1590
|
+
if (r.error) return fail(notDelivered(r.error));
|
|
1591
|
+
const v = readNode(r.el);
|
|
1592
|
+
const scrollable = ['AXScrollArea', 'AXWebArea', 'AXList', 'AXTable', 'AXOutline', 'AXBrowser', 'AXTextArea'].indexOf(v.AXRole) >= 0 || attr(r.el, 'AXVerticalScrollBar') !== null;
|
|
1593
|
+
if (!scrollable) {
|
|
1594
|
+
const acts = actionNames(r.el);
|
|
1595
|
+
if (acts.indexOf('AXScrollToVisible') < 0) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${v.AXRole} is neither a scroll area nor able to scroll itself into view`, details: { actions: acts } }));
|
|
1596
|
+
const before = observeState(r.el, r.appEl);
|
|
1597
|
+
const e = perform(r.el, 'AXScrollToVisible');
|
|
1598
|
+
if (e !== 0) return fail(axCallError(e, 'AXScrollToVisible'));
|
|
1599
|
+
sleep(250);
|
|
1600
|
+
return Object.assign(verdict(before, observeState(r.el, r.appEl), { mechanism: 'semantic', action: 'AXScrollToVisible', role: v.AXRole }), { scrolled_into_view: true });
|
|
1601
|
+
}
|
|
1602
|
+
const p = opPhysicalPrep(req);
|
|
1603
|
+
if (p.ok) p.role = v.AXRole;
|
|
1604
|
+
return p;
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
// ── wait ─────────────────────────────────────────────────────────────────────────────────────────
|
|
1608
|
+
// Polls inside this one process (no respawn per poll). Conditions:
|
|
1609
|
+
// window / window_gone a window of `app` whose title contains `title` (any window when title is empty)
|
|
1610
|
+
// text / text_gone `text` anywhere in the app's window tree (title or value)
|
|
1611
|
+
// element the target element exists | is gone | enabled | focused | has value (equals / contains)
|
|
1612
|
+
// menu / menu_closed an open menu in `app`
|
|
1613
|
+
// sheet / sheet_gone a sheet, alert or dialog in `app`
|
|
1614
|
+
// app_running / app_gone `app` is running / not running
|
|
1615
|
+
// notification a new notification (from `app`, containing `text`) appeared after the wait began
|
|
1616
|
+
const ABSENCE_APP_CONDS = new Set(['window_gone', 'text_gone', 'menu_closed', 'sheet_gone']);
|
|
1617
|
+
function opWait(req) {
|
|
1618
|
+
const timeoutMs = clamp(req.timeout_ms, 0, 60000, 10000);
|
|
1619
|
+
const end = now() + timeoutMs;
|
|
1620
|
+
const cond = String(req.condition || '');
|
|
1621
|
+
let last = null;
|
|
1622
|
+
let sawApp = false;
|
|
1623
|
+
const needAX = cond !== 'app_running' && cond !== 'app_gone';
|
|
1624
|
+
if (needAX && !$.AXIsProcessTrusted()) return fail(permError());
|
|
1625
|
+
const baseline = cond === 'notification' ? new Set(listNotifications().map(n => n.id)) : null;
|
|
1626
|
+
const check = () => {
|
|
1627
|
+
if (cond === 'app_running' || cond === 'app_gone') {
|
|
1628
|
+
const a = findApp(req.app);
|
|
1629
|
+
last = { running: Boolean(a) };
|
|
1630
|
+
return cond === 'app_running' ? Boolean(a) : !a;
|
|
1631
|
+
}
|
|
1632
|
+
if (cond === 'notification') {
|
|
1633
|
+
const fresh = listNotifications().filter(n => !baseline.has(n.id) && (!req.app || textMatch(n.app, req.app, false)) && (!req.text || textMatch([n.title, n.subtitle, n.body].join('\n'), req.text, false)));
|
|
1634
|
+
last = { new_notifications: fresh.length };
|
|
1635
|
+
if (fresh.length) { last.notification = fresh[0]; return true; }
|
|
1636
|
+
return false;
|
|
1637
|
+
}
|
|
1638
|
+
if (cond === 'element') {
|
|
1639
|
+
const r = resolveOrError(req.target, 1500);
|
|
1640
|
+
const p = req.predicate || 'exists';
|
|
1641
|
+
if (r.error) {
|
|
1642
|
+
const absent = ABSENT_CODES.has(r.error.code);
|
|
1643
|
+
last = { exists: absent ? false : null, code: r.error.code };
|
|
1644
|
+
return p === 'gone' && absent;
|
|
1645
|
+
}
|
|
1646
|
+
const v = r.v;
|
|
1647
|
+
last = { exists: true, enabled: v.AXEnabled !== false, focused: v.AXFocused === true, value: valueOf(v, 200) === undefined ? null : valueOf(v, 200) };
|
|
1648
|
+
if (p === 'exists') return true;
|
|
1649
|
+
if (p === 'gone') return false;
|
|
1650
|
+
if (p === 'enabled') return v.AXEnabled !== false;
|
|
1651
|
+
if (p === 'focused') return v.AXFocused === true;
|
|
1652
|
+
if (p === 'value_equals') return String(v.AXValue) === String(req.value);
|
|
1653
|
+
if (p === 'value_contains') return String(v.AXValue === undefined ? '' : v.AXValue).toLowerCase().indexOf(String(req.value).toLowerCase()) >= 0;
|
|
1654
|
+
return false;
|
|
1655
|
+
}
|
|
1656
|
+
const app = findApp(req.app);
|
|
1657
|
+
if (!app) {
|
|
1658
|
+
if (ABSENCE_APP_CONDS.has(cond) && !sawApp) return 'app_not_found';
|
|
1659
|
+
last = { app_running: false };
|
|
1660
|
+
return ABSENCE_APP_CONDS.has(cond) && sawApp;
|
|
1661
|
+
}
|
|
1662
|
+
sawApp = true;
|
|
1663
|
+
const appEl = appElement(app);
|
|
1664
|
+
if (cond === 'window' || cond === 'window_gone') {
|
|
1665
|
+
const titles = windowsOf(appEl).map(w => String(attr(w, 'AXTitle') || ''));
|
|
1666
|
+
last = { windows: titles.slice(0, 8) };
|
|
1667
|
+
const hit = titles.some(t => !req.title || textMatch(t, req.title, req.exact));
|
|
1668
|
+
return cond === 'window' ? hit : !hit;
|
|
1669
|
+
}
|
|
1670
|
+
if (cond === 'menu' || cond === 'menu_closed') { const m = menuOpen(appEl); last = { menu: m }; return cond === 'menu' ? m : !m; }
|
|
1671
|
+
if (cond === 'sheet' || cond === 'sheet_gone') {
|
|
1672
|
+
let n = 0;
|
|
1673
|
+
for (const w of windowsOf(appEl)) {
|
|
1674
|
+
const sr = attr(w, 'AXSubrole');
|
|
1675
|
+
if (sr === 'AXDialog' || sr === 'AXSystemDialog') n++;
|
|
1676
|
+
for (const k of children(w)) if (attr(k, 'AXRole') === 'AXSheet') n++;
|
|
1677
|
+
}
|
|
1678
|
+
last = { sheets: n };
|
|
1679
|
+
return cond === 'sheet' ? n > 0 : n === 0;
|
|
1680
|
+
}
|
|
1681
|
+
if (cond === 'text' || cond === 'text_gone') {
|
|
1682
|
+
const w = pickWindow(appEl, req);
|
|
1683
|
+
if (w.error) { last = { window: w.error.code }; return cond === 'text_gone' && w.error.code === 'WINDOW_NOT_FOUND'; }
|
|
1684
|
+
const f = walk(w.el, [], { depth: 60, maxNodes: 1, budgetMs: 3000, maxVisit: 20000, find: { text: req.text, exact: Boolean(req.exact), limit: 1 } });
|
|
1685
|
+
last = { found: f.nodes.length > 0, complete: f.complete };
|
|
1686
|
+
return cond === 'text' ? f.nodes.length > 0 : f.nodes.length === 0 && f.complete;
|
|
1687
|
+
}
|
|
1688
|
+
throw new Error(`unknown condition ${cond}`);
|
|
1689
|
+
};
|
|
1690
|
+
const t0 = now();
|
|
1691
|
+
for (;;) {
|
|
1692
|
+
let ok;
|
|
1693
|
+
try { ok = check(); } catch (e) { return fail({ code: 'INVALID_ARGS', message: String(e.message || e) }); }
|
|
1694
|
+
if (ok === 'app_not_found') return fail(appNotFound(req));
|
|
1695
|
+
if (ok) return { ok: true, met: true, condition: cond, elapsed_ms: now() - t0, observed: last };
|
|
1696
|
+
if (now() >= end) return fail({ code: 'TIMEOUT', message: `${cond} not met within ${timeoutMs} ms`, details: { kind: 'wait_timeout', last_observed: last } });
|
|
1697
|
+
sleep(250);
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
// ── apps: activate / hide / quit, and waiting for a launch ───────────────────────────────────────
|
|
1702
|
+
// Session-critical processes are never quit, whatever is asked (matched exactly by bundle id).
|
|
1703
|
+
const PROTECTED_BUNDLES = new Set(['com.apple.loginwindow', 'com.apple.dock', 'com.apple.systemuiserver', 'com.apple.controlcenter',
|
|
1704
|
+
'com.apple.notificationcenterui', 'com.apple.finder', 'com.apple.WindowManager', 'com.apple.Spotlight', 'com.apple.SecurityAgent',
|
|
1705
|
+
'com.apple.coreservices.uiagent', 'com.apple.TextInputMenuAgent', 'com.apple.universalcontrol', 'com.apple.WindowServer']);
|
|
1706
|
+
function appInfo(spec) {
|
|
1707
|
+
const a = findApp(spec);
|
|
1708
|
+
const out = { running: Boolean(a) };
|
|
1709
|
+
if (a) Object.assign(out, { name: a.name, pid: a.pid, bundle_id: a.bundle, presentation: POLICY[a.policy] || 'helper', hidden: a.hidden });
|
|
1710
|
+
// where the app lives, also when it is not running (for launch checks)
|
|
1711
|
+
let path = null;
|
|
1712
|
+
try {
|
|
1713
|
+
if (a && a.ns.bundleURL && !a.ns.bundleURL.isNil()) path = a.ns.bundleURL.path.js;
|
|
1714
|
+
else if (/^\/.+\.app\/?$/.test(String(spec)) && $.NSFileManager.defaultManager.fileExistsAtPath(String(spec))) path = String(spec).replace(/\/$/, '');
|
|
1715
|
+
else if (/^[\w-]+(\.[\w-]+)+$/.test(String(spec))) { const u = $.NSWorkspace.sharedWorkspace.URLForApplicationWithBundleIdentifier(String(spec)); if (u && !u.isNil()) path = u.path.js; }
|
|
1716
|
+
else { const p = $.NSWorkspace.sharedWorkspace.fullPathForApplication(String(spec)); if (p && !p.isNil()) path = p.js; }
|
|
1717
|
+
} catch (e) { /* unknown */ }
|
|
1718
|
+
out.path = path;
|
|
1719
|
+
if (path) {
|
|
1720
|
+
try {
|
|
1721
|
+
const list = $.NSFileManager.defaultManager.contentsOfDirectoryAtPathError(path + '/Contents/Frameworks', null);
|
|
1722
|
+
const names = [];
|
|
1723
|
+
if (list && !list.isNil()) for (let i = 0; i < Number(list.count); i++) names.push(list.objectAtIndex(i).js);
|
|
1724
|
+
out.chromium = names.some(x => CHROMIUM_MARKERS.indexOf(x) >= 0 || /(Chrome|Chromium|Edge|Brave|Vivaldi|Opera|Arc).* Framework\.framework$/.test(x));
|
|
1725
|
+
out.electron = names.indexOf('Electron Framework.framework') >= 0;
|
|
1726
|
+
} catch (e) { out.chromium = false; }
|
|
1727
|
+
}
|
|
1728
|
+
return out;
|
|
1729
|
+
}
|
|
1730
|
+
function opAppInfo(req) { return Object.assign({ ok: true }, appInfo(req.app)); }
|
|
1731
|
+
function opAppCtl(req) {
|
|
1732
|
+
const a = findApp(req.app);
|
|
1733
|
+
const action = String(req.action);
|
|
1734
|
+
if (!a) return fail(notDelivered({ code: 'APP_NOT_FOUND', message: `no running app named "${req.app}"` }));
|
|
1735
|
+
if (action === 'quit') {
|
|
1736
|
+
if (PROTECTED_BUNDLES.has(a.bundle)) return fail(notDelivered({ code: 'POLICY_DENIED', message: `${a.name} (${a.bundle}) is part of the macOS session and is never quit` }));
|
|
1737
|
+
if ((req.protect_pids || []).indexOf(a.pid) >= 0) return fail(notDelivered({ code: 'POLICY_DENIED', message: `${a.name} runs noracu itself (the MCP host) — quitting it would end this session` }));
|
|
1738
|
+
// NSRunningApplication's `terminated` flag is cached in this process (no run loop), so whether the
|
|
1739
|
+
// process actually ended is checked by the server, by pid
|
|
1740
|
+
const ok = req.force ? a.ns.forceTerminate : a.ns.terminate;
|
|
1741
|
+
if (!ok) return fail(notDelivered({ code: 'ACTION_FAILED', message: `${a.name} refused to ${req.force ? 'force-quit' : 'quit'}` }));
|
|
1742
|
+
sleep(800); // the request is delivered asynchronously; exiting at once can drop it
|
|
1743
|
+
return { ok: true, sent: true, name: a.name, pid: a.pid, method: req.force ? 'force' : 'graceful' };
|
|
1744
|
+
}
|
|
1745
|
+
if (action === 'hide' || action === 'unhide') {
|
|
1746
|
+
// NSRunningApplication's own `hidden` is a cached KVO value that never refreshes here (no run loop);
|
|
1747
|
+
// the app's AXHidden attribute is live
|
|
1748
|
+
const appEl = appElement(a);
|
|
1749
|
+
if (action === 'hide') a.ns.hide; else a.ns.unhide;
|
|
1750
|
+
sleep(400);
|
|
1751
|
+
const hidden = attr(appEl, 'AXHidden') === true;
|
|
1752
|
+
return { ok: true, delivery: hidden === (action === 'hide') ? 'delivered_verified' : 'delivered_unverified', retry: 'safe', name: a.name, pid: a.pid, hidden };
|
|
1753
|
+
}
|
|
1754
|
+
return fail(notDelivered({ code: 'INVALID_ARGS', message: `unknown app action "${action}"` }));
|
|
1755
|
+
}
|
|
1756
|
+
function opAppWait(req) {
|
|
1757
|
+
const end = now() + clamp(req.timeout_ms, 0, 60000, 15000);
|
|
1758
|
+
let a = null, win = null;
|
|
1759
|
+
while (now() < end) {
|
|
1760
|
+
a = findApp(req.app);
|
|
1761
|
+
if (a && (!req.not_pid || a.pid !== req.not_pid)) {
|
|
1762
|
+
if (!req.want_window) break;
|
|
1763
|
+
if ($.AXIsProcessTrusted()) {
|
|
1764
|
+
const ws = windowsOf(appElement(a));
|
|
1765
|
+
if (ws.length) { win = windowInfo(ws[0], 0); break; }
|
|
1766
|
+
} else break;
|
|
1767
|
+
}
|
|
1768
|
+
sleep(250);
|
|
1769
|
+
}
|
|
1770
|
+
const front = frontApp();
|
|
1771
|
+
if (!a) return fail({ code: 'TIMEOUT', message: `"${req.app}" did not start in time`, delivery: 'unknown', retry: 'unsafe', details: { kind: 'launch_timeout' } });
|
|
1772
|
+
const out = { ok: true, name: a.name, pid: a.pid, bundle_id: a.bundle, frontmost: Boolean(front && front.pid === a.pid) };
|
|
1773
|
+
if (win) out.window = { title: win.title, frame: win.frame };
|
|
1774
|
+
else if (req.want_window) out.note = 'running, but no window yet (a document app may show one only when brought forward)';
|
|
1775
|
+
return out;
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
// ── windows: focus / minimize / restore / move / resize / maximize ───────────────────────────────
|
|
1779
|
+
function cgWindow(id) {
|
|
1780
|
+
const info = cast($.CGWindowListCopyWindowInfo(8, id));
|
|
1781
|
+
if (!info || Number(info.count) < 1) return null;
|
|
1782
|
+
const d = info.objectAtIndex(0);
|
|
1783
|
+
const g = k => { const o = d.objectForKey(ks(k)); return o && !o.isNil() ? o : null; };
|
|
1784
|
+
const b = g('kCGWindowBounds');
|
|
1785
|
+
return { id, pid: Number(g('kCGWindowOwnerPID').js), app: g('kCGWindowOwnerName') ? g('kCGWindowOwnerName').js : '', title: g('kCGWindowName') ? g('kCGWindowName').js : null,
|
|
1786
|
+
bounds: b ? [Number(b.objectForKey(ks('X')).js), Number(b.objectForKey(ks('Y')).js), Number(b.objectForKey(ks('Width')).js), Number(b.objectForKey(ks('Height')).js)].map(Math.round) : null };
|
|
1787
|
+
}
|
|
1788
|
+
// the AX window behind a CGWindowID (same process, same bounds, then same title), or by app + index/title
|
|
1789
|
+
function axWindowFor(req) {
|
|
1790
|
+
if (req.window_id !== undefined && req.window_id !== null) {
|
|
1791
|
+
const cg = cgWindow(Number(req.window_id));
|
|
1792
|
+
if (!cg) return { error: notDelivered({ code: 'WINDOW_NOT_FOUND', message: `no window with id ${req.window_id}` }) };
|
|
1793
|
+
const app = runningApps().find(x => x.pid === cg.pid);
|
|
1794
|
+
if (!app) return { error: notDelivered({ code: 'WINDOW_NOT_FOUND', message: 'the window\'s app is gone' }) };
|
|
1795
|
+
const appEl = appElement(app);
|
|
1796
|
+
const ws = windowsOf(appEl);
|
|
1797
|
+
const infos = ws.map((w, i) => windowInfo(w, i));
|
|
1798
|
+
// the CGWindowID itself when accessibility exposes it; bounds and title only as a fallback
|
|
1799
|
+
let hits = infos.filter(x => x.wid === Number(req.window_id));
|
|
1800
|
+
if (!hits.length) hits = infos.filter(x => x.wid === null && rectNear(x.frame, cg.bounds, 2));
|
|
1801
|
+
if (hits.length > 1 && cg.title) hits = hits.filter(x => x.title === cg.title);
|
|
1802
|
+
if (hits.length !== 1) return { error: notDelivered({ code: hits.length ? 'AMBIGUOUS_WINDOW' : 'WINDOW_NOT_FOUND', message: hits.length ? 'several accessibility windows match that id' : 'accessibility cannot see that window (minimized windows are listed with include_offscreen)' }) };
|
|
1803
|
+
return { el: ws[hits[0].n], info: hits[0], app, appEl };
|
|
1804
|
+
}
|
|
1805
|
+
const app = findApp(req.app);
|
|
1806
|
+
if (!app) return { error: notDelivered({ code: 'APP_NOT_FOUND', message: req.app ? `no running app named "${req.app}"` : 'no frontmost app' }) };
|
|
1807
|
+
const appEl = appElement(app);
|
|
1808
|
+
const w = pickWindow(appEl, req);
|
|
1809
|
+
if (w.error) return { error: notDelivered(w.error) };
|
|
1810
|
+
return { el: w.el, info: w.info, app, appEl };
|
|
1811
|
+
}
|
|
1812
|
+
// AXValueCreate needs a typed pointer holding a real struct. On macOS 27 the bridge's first struct
|
|
1813
|
+
// conversion in a process can come out as zeros (a plain JS object always does), so the value is read
|
|
1814
|
+
// back and rebuilt until it holds what was asked; a value that never does is an error, not a zero move.
|
|
1815
|
+
function axStruct(kind, a, b) {
|
|
1816
|
+
for (let i = 0; i < 4; i++) {
|
|
1817
|
+
const r = kind === 1 ? Ref('{CGPoint="x"d"y"d}') : Ref('{CGSize="width"d"height"d}');
|
|
1818
|
+
r[0] = kind === 1 ? $.CGPointMake(a, b) : $.CGSizeMake(a, b);
|
|
1819
|
+
const v = cast($.AXValueCreate(kind, r));
|
|
1820
|
+
const back = v ? axValue(v) : null;
|
|
1821
|
+
if (back && (kind === 1 ? back.x === a && back.y === b : back.w === a && back.h === b)) return v;
|
|
1822
|
+
}
|
|
1823
|
+
throw new Error('could not build an accessibility point/size value');
|
|
1824
|
+
}
|
|
1825
|
+
function axPoint(x, y) { return axStruct(1, Math.round(x), Math.round(y)); }
|
|
1826
|
+
function axSize(w, h) { return axStruct(2, Math.round(w), Math.round(h)); }
|
|
1827
|
+
function visibleFrameOf(x, y) {
|
|
1828
|
+
const s = $.NSScreen.screens;
|
|
1829
|
+
const mainH = Number(s.objectAtIndex(0).frame.size.height);
|
|
1830
|
+
for (let i = 0; i < Number(s.count); i++) {
|
|
1831
|
+
const sc = s.objectAtIndex(i);
|
|
1832
|
+
const f = sc.frame, v = sc.visibleFrame;
|
|
1833
|
+
const fx = Number(f.origin.x), fy = mainH - Number(f.origin.y) - Number(f.size.height), fw = Number(f.size.width), fh = Number(f.size.height);
|
|
1834
|
+
if (x >= fx && x < fx + fw && y >= fy && y < fy + fh) return [Number(v.origin.x), mainH - Number(v.origin.y) - Number(v.size.height), Number(v.size.width), Number(v.size.height)];
|
|
1835
|
+
}
|
|
1836
|
+
return null;
|
|
1837
|
+
}
|
|
1838
|
+
function opWindowOp(req) {
|
|
1839
|
+
if (!$.AXIsProcessTrusted()) return fail(permError());
|
|
1840
|
+
const w = axWindowFor(req);
|
|
1841
|
+
if (w.error) return fail(w.error);
|
|
1842
|
+
const action = String(req.action);
|
|
1843
|
+
const before = windowInfo(w.el, w.info.n);
|
|
1844
|
+
let err = 0, raiseErr = 0;
|
|
1845
|
+
if (action === 'focus' || action === 'raise') {
|
|
1846
|
+
// several steps change the window before AXRaise answers, so an AXRaise error is not "nothing
|
|
1847
|
+
// sent": the result is decided by the state asked for (R19)
|
|
1848
|
+
if (before.minimized) { setAttr(w.el, 'AXMinimized', NO()); sleep(150); }
|
|
1849
|
+
raiseErr = perform(w.el, 'AXRaise');
|
|
1850
|
+
setAttr(w.el, 'AXMain', YES());
|
|
1851
|
+
if (action === 'focus') { try { w.app.ns.activateWithOptions(1 << 1); } catch (e) { /* activation may be refused */ } }
|
|
1852
|
+
} else if (action === 'minimize') err = setAttr(w.el, 'AXMinimized', YES());
|
|
1853
|
+
else if (action === 'restore') { err = setAttr(w.el, 'AXMinimized', NO()); perform(w.el, 'AXRaise'); }
|
|
1854
|
+
else if (action === 'move') {
|
|
1855
|
+
if (!Number.isFinite(Number(req.x)) || !Number.isFinite(Number(req.y))) return invalid('move needs x and y');
|
|
1856
|
+
err = setAttr(w.el, 'AXPosition', axPoint(Number(req.x), Number(req.y)));
|
|
1857
|
+
} else if (action === 'resize') {
|
|
1858
|
+
if (!(Number(req.width) > 0) || !(Number(req.height) > 0)) return invalid('resize needs width and height');
|
|
1859
|
+
err = setAttr(w.el, 'AXSize', axSize(Number(req.width), Number(req.height)));
|
|
1860
|
+
} else if (action === 'maximize') {
|
|
1861
|
+
const fr = before.frame;
|
|
1862
|
+
const vf = fr ? visibleFrameOf(fr[0] + fr[2] / 2, fr[1] + fr[3] / 2) : null;
|
|
1863
|
+
if (!vf) return fail(notDelivered({ code: 'ACTION_FAILED', message: 'could not tell which display the window is on' }));
|
|
1864
|
+
err = setAttr(w.el, 'AXPosition', axPoint(vf[0], vf[1]));
|
|
1865
|
+
if (err === 0) {
|
|
1866
|
+
const se = setAttr(w.el, 'AXSize', axSize(vf[2], vf[3]));
|
|
1867
|
+
if (se !== 0) return fail({ code: 'ACTION_FAILED', message: `moved the window but could not resize it: ${axCallError(se, 'AXSize').message}`, delivery: 'delivered_unverified', retry: 'safe' });
|
|
1868
|
+
}
|
|
1869
|
+
} else if (action === 'fullscreen' || action === 'exit_fullscreen') {
|
|
1870
|
+
err = setAttr(w.el, 'AXFullScreen', action === 'fullscreen' ? YES() : NO());
|
|
1871
|
+
} else return invalid(`unknown window action "${action}"`);
|
|
1872
|
+
if (err !== 0) return fail(axCallError(err, `window ${action}`));
|
|
1873
|
+
sleep(action === 'fullscreen' || action === 'exit_fullscreen' ? 900 : 300);
|
|
1874
|
+
const after = windowInfo(w.el, w.info.n);
|
|
1875
|
+
const front = frontApp();
|
|
1876
|
+
const changed = JSON.stringify([before.frame, before.minimized, before.focused, before.main]) !== JSON.stringify([after.frame, after.minimized, after.focused, after.main]);
|
|
1877
|
+
// verified only by the state that was asked for, not by any change
|
|
1878
|
+
const fr = after.frame, near = (a, b) => Math.abs(a - b) <= 4;
|
|
1879
|
+
const want = {
|
|
1880
|
+
focus: () => Boolean(front && front.pid === w.app.pid && (after.focused || after.main)),
|
|
1881
|
+
raise: () => after.main === true || changed,
|
|
1882
|
+
minimize: () => after.minimized === true,
|
|
1883
|
+
restore: () => after.minimized === false,
|
|
1884
|
+
move: () => Boolean(fr) && near(fr[0], Number(req.x)) && near(fr[1], Number(req.y)),
|
|
1885
|
+
resize: () => Boolean(fr) && near(fr[2], Number(req.width)) && near(fr[3], Number(req.height)),
|
|
1886
|
+
maximize: () => { const vf = before.frame ? visibleFrameOf(before.frame[0] + before.frame[2] / 2, before.frame[1] + before.frame[3] / 2) : null; return Boolean(fr && vf) && rectNear(fr, vf, 8); },
|
|
1887
|
+
fullscreen: () => attr(w.el, 'AXFullScreen') === true,
|
|
1888
|
+
exit_fullscreen: () => attr(w.el, 'AXFullScreen') === false,
|
|
1889
|
+
};
|
|
1890
|
+
const verified = want[action] ? want[action]() : changed;
|
|
1891
|
+
if (raiseErr !== 0 && !verified) {
|
|
1892
|
+
const e = axCallError(raiseErr, `window ${action}`);
|
|
1893
|
+
// the window may already have been unminimized / made main / activated
|
|
1894
|
+
return fail(e.delivery === 'not_delivered' ? Object.assign({}, e, { delivery: 'delivered_unverified', retry: 'safe' }) : e);
|
|
1895
|
+
}
|
|
1896
|
+
return { ok: true, action, app: w.app.name, window: { title: after.title, frame: after.frame, minimized: after.minimized, focused: after.focused }, frontmost: front ? front.name : null,
|
|
1897
|
+
delivery: verified ? 'delivered_verified' : 'delivered_unverified', retry: 'safe' };
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
// ── paste (mac_paste) ────────────────────────────────────────────────────────────────────────────
|
|
1901
|
+
// One engine call does the whole paste, so the user's clipboard never leaves this process and nothing
|
|
1902
|
+
// can slip in between the steps: focus guard → copy every item and type aside → write the text (marked
|
|
1903
|
+
// transient, so clipboard managers skip it) → ⌘V through cliclick, only if the clipboard and the
|
|
1904
|
+
// frontmost app are still as they were → wait for the paste to show in the focused element (else at
|
|
1905
|
+
// least 1 s, and only while the app answers) → put the user's items back, only if nobody else wrote
|
|
1906
|
+
// to the clipboard meanwhile. A password manager's concealed item is never copied or put back: the
|
|
1907
|
+
// clipboard is cleared instead.
|
|
1908
|
+
const PB_CONCEALED = 'org.nspasteboard.ConcealedType', PB_TRANSIENT = 'org.nspasteboard.TransientType';
|
|
1909
|
+
const PB_REMOTE = 'com.apple.is-remote-clipboard';
|
|
1910
|
+
const CLIP_SAVE_LIMIT = 64 * 1024 * 1024;
|
|
1911
|
+
function pbGeneral() { return $.NSPasteboard.generalPasteboard; }
|
|
1912
|
+
function pbTypes() {
|
|
1913
|
+
const out = [], tl = pbGeneral().types;
|
|
1914
|
+
if (tl && !tl.isNil()) for (let i = 0; i < Number(tl.count); i++) out.push(tl.objectAtIndex(i).js);
|
|
1915
|
+
return out;
|
|
1916
|
+
}
|
|
1917
|
+
function pbChangeCount() { return Number(pbGeneral().changeCount); }
|
|
1918
|
+
// the types of every item (NSPasteboard.types lists only the first item's), read without any data
|
|
1919
|
+
function pbItemTypes() {
|
|
1920
|
+
const out = [], items = pbGeneral().pasteboardItems;
|
|
1921
|
+
if (items && !items.isNil()) for (let i = 0; i < Number(items.count); i++) {
|
|
1922
|
+
const tl = items.objectAtIndex(i).types;
|
|
1923
|
+
if (tl && !tl.isNil()) for (let j = 0; j < Number(tl.count); j++) out.push(tl.objectAtIndex(j).js);
|
|
1924
|
+
}
|
|
1925
|
+
return out;
|
|
1926
|
+
}
|
|
1927
|
+
// every item with every type's data, kept as NSData in this process
|
|
1928
|
+
function pbSave(limit) {
|
|
1929
|
+
const items = pbGeneral().pasteboardItems, out = [];
|
|
1930
|
+
let bytes = 0;
|
|
1931
|
+
if (items && !items.isNil()) for (let i = 0; i < Number(items.count); i++) {
|
|
1932
|
+
const it = items.objectAtIndex(i), tl = it.types, rec = [];
|
|
1933
|
+
if (tl && !tl.isNil()) for (let j = 0; j < Number(tl.count); j++) {
|
|
1934
|
+
const t = tl.objectAtIndex(j).js, d = it.dataForType(ks(t));
|
|
1935
|
+
if (!d || d.isNil()) continue;
|
|
1936
|
+
bytes += Number(d.length);
|
|
1937
|
+
if (bytes > limit) return { too_large: true, bytes };
|
|
1938
|
+
rec.push([t, d]);
|
|
1939
|
+
}
|
|
1940
|
+
if (rec.length) out.push(rec);
|
|
1941
|
+
}
|
|
1942
|
+
if (!out.length) {
|
|
1943
|
+
const d = pbGeneral().dataForType(ks('public.utf8-plain-text'));
|
|
1944
|
+
if (d && !d.isNil()) { bytes = Number(d.length); out.push([['public.utf8-plain-text', d]]); }
|
|
1945
|
+
}
|
|
1946
|
+
return { items: out, bytes };
|
|
1947
|
+
}
|
|
1948
|
+
function pbWriteObjects(objs) {
|
|
1949
|
+
const p = pbGeneral();
|
|
1950
|
+
p.clearContents;
|
|
1951
|
+
if (!objs.length) return true;
|
|
1952
|
+
const a = $.NSMutableArray.alloc.init;
|
|
1953
|
+
for (const o of objs) a.addObject(o);
|
|
1954
|
+
return Boolean(p.writeObjects(a));
|
|
1955
|
+
}
|
|
1956
|
+
// our text as UTF-8 plain text, marked transient; the change count afterwards identifies our write
|
|
1957
|
+
function pbWriteText(text) {
|
|
1958
|
+
const it = $.NSPasteboardItem.alloc.init;
|
|
1959
|
+
it.setStringForType($(text), ks('public.utf8-plain-text'));
|
|
1960
|
+
it.setDataForType($.NSData.data, ks(PB_TRANSIENT));
|
|
1961
|
+
return pbWriteObjects([it]) ? pbChangeCount() : null;
|
|
1962
|
+
}
|
|
1963
|
+
function pbRestore(saved) {
|
|
1964
|
+
return pbWriteObjects(saved.items.map(rec => { const it = $.NSPasteboardItem.alloc.init; for (const [t, d] of rec) it.setDataForType(d, ks(t)); return it; }));
|
|
1965
|
+
}
|
|
1966
|
+
function pbClear() { pbGeneral().clearContents; }
|
|
1967
|
+
// a program by absolute path with an argv array (no shell), output discarded, under a time limit
|
|
1968
|
+
function runTool(path, args, timeoutMs) {
|
|
1969
|
+
if (!$.NSFileManager.defaultManager.isExecutableFileAtPath(String(path))) return { started: false, error: `${path} is not an executable file` };
|
|
1970
|
+
const t = $.NSTask.alloc.init;
|
|
1971
|
+
t.launchPath = String(path);
|
|
1972
|
+
t.arguments = $(args.map(String));
|
|
1973
|
+
t.standardOutput = $.NSFileHandle.fileHandleWithNullDevice;
|
|
1974
|
+
t.standardError = $.NSFileHandle.fileHandleWithNullDevice;
|
|
1975
|
+
try { t.launch; } catch (e) { return { started: false, error: String(e.message || e).slice(0, 160) }; }
|
|
1976
|
+
const end = now() + timeoutMs;
|
|
1977
|
+
while (t.running && now() < end) sleep(20);
|
|
1978
|
+
if (t.running) {
|
|
1979
|
+
// never leave it running: it could still send its events after we have moved on
|
|
1980
|
+
t.terminate;
|
|
1981
|
+
const grace = now() + 300;
|
|
1982
|
+
while (t.running && now() < grace) sleep(20);
|
|
1983
|
+
if (t.running) { const k = $.NSTask.alloc.init; k.launchPath = '/bin/kill'; k.arguments = $(['-9', String(Number(t.processIdentifier))]); try { k.launch; k.waitUntilExit; } catch (e) { /* gone */ } }
|
|
1984
|
+
return { started: true, timedOut: true };
|
|
1985
|
+
}
|
|
1986
|
+
return { started: true, status: Number(t.terminationStatus) };
|
|
1987
|
+
}
|
|
1988
|
+
// what a paste changes in the focused element (null when nothing there can be read)
|
|
1989
|
+
// { el, key } — the focused element and a digest of its value, length and selection; null when
|
|
1990
|
+
// nothing there can be read. Each read gives up after half a second (an app that hangs right after
|
|
1991
|
+
// ⌘V must not eat the whole call's time).
|
|
1992
|
+
function focusEvidence(appEl) {
|
|
1993
|
+
const f = attr(appEl, 'AXFocusedUIElement');
|
|
1994
|
+
if (!f || !f.el) return null;
|
|
1995
|
+
try { $.AXUIElementSetMessagingTimeout(f.el, 0.5); } catch (e) { /* default */ }
|
|
1996
|
+
const v = readNode(f.el);
|
|
1997
|
+
if (v.__err) return null;
|
|
1998
|
+
const n = attr(f.el, 'AXNumberOfCharacters'), sel = attr(f.el, 'AXSelectedTextRange');
|
|
1999
|
+
const val = typeof v.AXValue === 'string' ? vhash(v.AXValue) : null;
|
|
2000
|
+
if (val === null && typeof n !== 'number' && !sel) return null;
|
|
2001
|
+
return { el: f.el, key: JSON.stringify([val, typeof n === 'number' ? n : null, sel || null]) };
|
|
2002
|
+
}
|
|
2003
|
+
const PASTE_MIN_HOLD_MS = 300;
|
|
2004
|
+
function opPaste(req) {
|
|
2005
|
+
const text = String(req.text === undefined || req.text === null ? '' : req.text);
|
|
2006
|
+
if (!text) return invalid('text required');
|
|
2007
|
+
const front = frontApp();
|
|
2008
|
+
if (!front) return fail(notDelivered({ code: 'FOCUS_UNKNOWN', message: 'could not read the frontmost app — nothing was pasted' }));
|
|
2009
|
+
let target = front;
|
|
2010
|
+
if (req.app) {
|
|
2011
|
+
const t = findApp(req.app);
|
|
2012
|
+
if (!t) return fail(notDelivered({ code: 'FOCUS_LOST', message: `"${req.app}" is not running (frontmost is "${front.name}") — nothing was pasted` }));
|
|
2013
|
+
if (t.pid !== front.pid) return fail(notDelivered({ code: 'FOCUS_LOST', message: `expected "${t.name}", frontmost is "${front.name}" — nothing was pasted` }));
|
|
2014
|
+
target = t;
|
|
2015
|
+
}
|
|
2016
|
+
const force = req.force === true;
|
|
2017
|
+
const appEl = appElement(target);
|
|
2018
|
+
const ev0 = focusEvidence(appEl);
|
|
2019
|
+
// the change count before anything is read: a copy that lands while we save is not overwritten
|
|
2020
|
+
const cc0 = pbChangeCount();
|
|
2021
|
+
// the first item's types tell a remote (Universal Clipboard) clipboard before any item is touched;
|
|
2022
|
+
// the other items' types are read without their data
|
|
2023
|
+
const first = pbTypes();
|
|
2024
|
+
const remote = first.indexOf(PB_REMOTE) >= 0;
|
|
2025
|
+
const types = remote ? first : first.concat(pbItemTypes());
|
|
2026
|
+
// keep: why the clipboard will not be put back exactly as it was
|
|
2027
|
+
let saved = null, keep = null;
|
|
2028
|
+
if (!remote && types.indexOf(PB_CONCEALED) >= 0) keep = 'previous_concealed';
|
|
2029
|
+
else if (!remote && types.indexOf(PB_TRANSIENT) >= 0) keep = 'previous_transient';
|
|
2030
|
+
else if (remote || (types.some(t => /^com\.apple\.pasteboard\.promised-file/.test(t)) && types.indexOf('public.file-url') < 0)) {
|
|
2031
|
+
// reading it would start a transfer from the other device (or make the promised file)
|
|
2032
|
+
if (!force) return fail(notDelivered({ code: 'CLIPBOARD_REMOTE', message: 'the clipboard holds content from another device (Universal Clipboard) or a file not made yet, which cannot be copied aside without fetching it — nothing was pasted. mac_type types without the clipboard; force:true pastes and leaves the pasted text on the clipboard' }));
|
|
2033
|
+
keep = 'remote';
|
|
2034
|
+
} else if (!types.length) keep = 'was_empty';
|
|
2035
|
+
else {
|
|
2036
|
+
const sv = pbSave(CLIP_SAVE_LIMIT);
|
|
2037
|
+
if (sv.too_large) {
|
|
2038
|
+
if (!force) return fail(notDelivered({ code: 'CLIPBOARD_TOO_LARGE', message: `the clipboard holds more than ${CLIP_SAVE_LIMIT / 1048576} MB, which is not copied aside — nothing was pasted. mac_type types without the clipboard; force:true pastes and leaves the pasted text on the clipboard` }));
|
|
2039
|
+
keep = 'too_large';
|
|
2040
|
+
} else saved = sv;
|
|
2041
|
+
}
|
|
2042
|
+
const putBack = (ours) => {
|
|
2043
|
+
if (pbChangeCount() !== ours) return 'false (changed_externally)';
|
|
2044
|
+
if (keep === 'previous_concealed' || keep === 'previous_transient') { pbClear(); return `cleared (${keep})`; }
|
|
2045
|
+
if (keep === 'was_empty') { pbClear(); return 'true (was_empty)'; }
|
|
2046
|
+
if (keep) return `false (${keep})`;
|
|
2047
|
+
return pbRestore(saved) ? 'true' : 'false (write_failed)';
|
|
2048
|
+
};
|
|
2049
|
+
if (pbChangeCount() !== cc0) return fail(notDelivered({ code: 'NOT_CONFIRMED', message: 'another app wrote to the clipboard while it was being copied aside — nothing was written or pasted' }));
|
|
2050
|
+
const ours = pbWriteText(text);
|
|
2051
|
+
if (ours === null) {
|
|
2052
|
+
const restored = saved || keep ? putBack(pbChangeCount()) : 'false';
|
|
2053
|
+
return fail(notDelivered({ code: 'ACTION_FAILED', message: `could not write the text to the clipboard — nothing was pasted (clipboard restored: ${restored})` }));
|
|
2054
|
+
}
|
|
2055
|
+
if (ours !== cc0 + 1) {
|
|
2056
|
+
// someone else wrote between the last check and our write: that write is gone; do not paste
|
|
2057
|
+
const restored = putBack(ours);
|
|
2058
|
+
return fail(notDelivered({ code: 'NOT_CONFIRMED', message: `another app wrote to the clipboard at the same moment as noracu — nothing was pasted (clipboard restored: ${restored})` }));
|
|
2059
|
+
}
|
|
2060
|
+
// last check before the keystroke: still our text on the clipboard, still the same app in front
|
|
2061
|
+
const f2 = frontApp();
|
|
2062
|
+
if (pbChangeCount() !== ours) return fail(notDelivered({ code: 'NOT_CONFIRMED', message: 'another app wrote to the clipboard just before the paste — nothing was pasted (the clipboard keeps what that app wrote)' }));
|
|
2063
|
+
if (!f2 || f2.pid !== target.pid) {
|
|
2064
|
+
const restored = putBack(ours);
|
|
2065
|
+
return fail(notDelivered({ code: 'FOCUS_LOST', message: `the frontmost app changed to "${f2 ? f2.name : 'unknown'}" just before the paste — nothing was pasted (clipboard restored: ${restored})` }));
|
|
2066
|
+
}
|
|
2067
|
+
const tool = req.cliclick || '/opt/homebrew/bin/cliclick';
|
|
2068
|
+
const k = runTool(tool, ['kd:cmd', 't:v', 'ku:cmd'], 10000);
|
|
2069
|
+
if (!k.started) {
|
|
2070
|
+
const restored = putBack(ours);
|
|
2071
|
+
return fail(notDelivered({ code: 'INTERNAL', message: `cliclick could not start: ${k.error} — nothing was pasted (clipboard restored: ${restored})` }));
|
|
2072
|
+
}
|
|
2073
|
+
if (k.timedOut || k.status !== 0) {
|
|
2074
|
+
// ⌘V may or may not have gone out (and ⌘ may still be down): release ⌘, keep our text on the
|
|
2075
|
+
// clipboard — a late paste must at worst repeat the text, never the user's clipboard
|
|
2076
|
+
runTool(tool, ['ku:cmd'], 2000);
|
|
2077
|
+
return fail({ code: 'ACTION_FAILED', message: `cliclick ${k.timedOut ? 'timed out' : `exited ${k.status}`} while sending ⌘V — the paste may or may not have happened (clipboard restored: false (paste_uncertain))`, delivery: 'unknown', retry: 'unsafe' });
|
|
2078
|
+
}
|
|
2079
|
+
// the paste is done when the focused element shows it; without that evidence the clipboard stays
|
|
2080
|
+
// ours for at least hold_ms, so an app that reads it late does not get the user's clipboard instead
|
|
2081
|
+
// evidence counts only from the element that was focused before (a focus move is not a paste), and
|
|
2082
|
+
// the clipboard stays ours for at least PASTE_MIN_HOLD_MS even then
|
|
2083
|
+
const holdMs = clamp(req.hold_ms, PASTE_MIN_HOLD_MS, 5000, 1000);
|
|
2084
|
+
const t0 = now();
|
|
2085
|
+
let evidence = false;
|
|
2086
|
+
const end = t0 + holdMs;
|
|
2087
|
+
while (now() < end) {
|
|
2088
|
+
sleep(100);
|
|
2089
|
+
const e = focusEvidence(appEl);
|
|
2090
|
+
if (ev0 && e && same(e.el, ev0.el) && e.key !== ev0.key) { evidence = true; break; }
|
|
2091
|
+
}
|
|
2092
|
+
if (evidence && now() - t0 < PASTE_MIN_HOLD_MS) sleep(PASTE_MIN_HOLD_MS - (now() - t0));
|
|
2093
|
+
// an app that does not answer may not have read the clipboard yet: leave our text there
|
|
2094
|
+
const hung = !evidence && readNode(appEl).__err === -25204;
|
|
2095
|
+
const restored = hung ? 'false (app_unresponsive)' : putBack(ours);
|
|
2096
|
+
return { ok: true, delivery: evidence ? 'delivered_verified' : 'delivered_unverified', retry: 'unsafe', restored, front: target.name, chars: text.length };
|
|
2097
|
+
}
|
|
2098
|
+
|
|
2099
|
+
// ── clipboard (read) ─────────────────────────────────────────────────────────────────────────────
|
|
2100
|
+
// Password managers mark secrets with org.nspasteboard.ConcealedType (nspasteboard.org); such an item is
|
|
2101
|
+
// never returned. Text is capped; an image comes back as PNG for the server to attach.
|
|
2102
|
+
function opClipboard(req) {
|
|
2103
|
+
const pb = $.NSPasteboard.generalPasteboard;
|
|
2104
|
+
const types = [];
|
|
2105
|
+
const tl = pb.types;
|
|
2106
|
+
if (tl && !tl.isNil()) for (let i = 0; i < Number(tl.count); i++) types.push(tl.objectAtIndex(i).js);
|
|
2107
|
+
const out = { ok: true, types: types.slice(0, 20), change_count: Number(pb.changeCount) };
|
|
2108
|
+
// a concealed mark on any item (types lists only the first item's) withholds the whole clipboard
|
|
2109
|
+
if (types.indexOf('org.nspasteboard.ConcealedType') >= 0 || pbItemTypes().indexOf('org.nspasteboard.ConcealedType') >= 0) { out.concealed = true; out.note = 'the clipboard holds an item marked concealed (e.g. a password manager copy); its content is not returned'; return out; }
|
|
2110
|
+
const fmt = req.format || 'auto';
|
|
2111
|
+
if (fmt === 'auto' || fmt === 'files') {
|
|
2112
|
+
const items = pb.pasteboardItems;
|
|
2113
|
+
const files = [];
|
|
2114
|
+
if (items && !items.isNil()) for (let i = 0; i < Number(items.count); i++) {
|
|
2115
|
+
const s = items.objectAtIndex(i).stringForType(ks('public.file-url'));
|
|
2116
|
+
if (s && !s.isNil()) { const u = $.NSURL.URLWithString(s); if (u && !u.isNil() && u.path && !u.path.isNil()) files.push(u.path.js); }
|
|
2117
|
+
}
|
|
2118
|
+
if (files.length) { out.type = 'files'; out.files = files.slice(0, 200); return out; }
|
|
2119
|
+
if (fmt === 'files') { out.type = 'none'; return out; }
|
|
2120
|
+
}
|
|
2121
|
+
if (fmt === 'auto' || fmt === 'image') {
|
|
2122
|
+
const t = types.indexOf('public.png') >= 0 ? 'public.png' : types.indexOf('public.tiff') >= 0 ? 'public.tiff' : null;
|
|
2123
|
+
if (t) {
|
|
2124
|
+
const data = pb.dataForType(ks(t));
|
|
2125
|
+
const rep = $.NSBitmapImageRep.imageRepWithData(data);
|
|
2126
|
+
if (rep && !rep.isNil()) {
|
|
2127
|
+
const png = rep.representationUsingTypeProperties(4, $({}));
|
|
2128
|
+
out.type = 'image'; out.width = Number(rep.pixelsWide); out.height = Number(rep.pixelsHigh);
|
|
2129
|
+
out.png_base64 = png.base64EncodedStringWithOptions(0).js;
|
|
2130
|
+
return out;
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
if (fmt === 'image') { out.type = 'none'; return out; }
|
|
2134
|
+
}
|
|
2135
|
+
const s = pb.stringForType(ks('public.utf8-plain-text'));
|
|
2136
|
+
if (s && !s.isNil()) {
|
|
2137
|
+
const text = s.js;
|
|
2138
|
+
const max = clamp(req.max_chars, 1, 200000, 20000);
|
|
2139
|
+
out.type = 'text'; out.length = text.length; out.text = text.length > max ? text.slice(0, max) : text; out.truncated = text.length > max;
|
|
2140
|
+
return out;
|
|
2141
|
+
}
|
|
2142
|
+
out.type = 'none';
|
|
2143
|
+
return out;
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
// ── notifications ────────────────────────────────────────────────────────────────────────────────
|
|
2147
|
+
// Banners, alerts and (when it is open) Notification Center's list live in the Notification Center
|
|
2148
|
+
// process as groups with an AXNotificationCenter* subrole. Each carries a stable AXIdentifier (a UUID),
|
|
2149
|
+
// a description "App, title, subtitle, body", text children identified as title / subtitle / body, and
|
|
2150
|
+
// its buttons as named actions ("Name:Close\nTarget:…").
|
|
2151
|
+
function ncApp() { return runningApps().find(a => a.bundle === 'com.apple.notificationcenterui') || null; }
|
|
2152
|
+
function actionLabel(a) { const m = String(a).match(/^Name:(.*?)(\n|$)/); return m ? m[1] : a === 'AXPress' ? 'press' : null; }
|
|
2153
|
+
function collectNotifications(appEl) {
|
|
2154
|
+
const found = [];
|
|
2155
|
+
const visit = (el, d) => {
|
|
2156
|
+
if (d > 14) return;
|
|
2157
|
+
const v = readNode(el);
|
|
2158
|
+
if (v.__err) return;
|
|
2159
|
+
if (String(v.AXSubrole || '').indexOf('AXNotificationCenter') === 0) {
|
|
2160
|
+
const texts = {};
|
|
2161
|
+
for (const k of v.AXChildren || []) { const kv = readNode(k); if (kv.AXRole === 'AXStaticText' && kv.AXIdentifier) texts[kv.AXIdentifier] = typeof kv.AXValue === 'string' ? kv.AXValue : ''; }
|
|
2162
|
+
const desc = typeof v.AXDescription === 'string' ? v.AXDescription : '';
|
|
2163
|
+
const acts = actionNames(el);
|
|
2164
|
+
found.push({ el, id: String(v.AXIdentifier || ''), kind: String(v.AXSubrole).replace('AXNotificationCenter', '').toLowerCase(),
|
|
2165
|
+
app: desc.split(', ')[0] || '', title: texts.title || '', subtitle: texts.subtitle || '', body: texts.body || '',
|
|
2166
|
+
actions: acts.map(actionLabel).filter(Boolean), rawActions: acts });
|
|
2167
|
+
return;
|
|
2168
|
+
}
|
|
2169
|
+
for (const k of v.AXChildren || []) visit(k, d + 1);
|
|
2170
|
+
};
|
|
2171
|
+
for (const w of windowsOf(appEl)) visit(w, 0);
|
|
2172
|
+
return found;
|
|
2173
|
+
}
|
|
2174
|
+
function listNotifications() {
|
|
2175
|
+
const a = ncApp();
|
|
2176
|
+
if (!a) return [];
|
|
2177
|
+
return collectNotifications(appElement(a)).map(n => ({ id: n.id, kind: n.kind, app: n.app, title: n.title, subtitle: n.subtitle, body: n.body, actions: n.actions }));
|
|
2178
|
+
}
|
|
2179
|
+
// Notification Center's history opens from the clock in the menu bar, when accessibility exposes it.
|
|
2180
|
+
function clockExtra() {
|
|
2181
|
+
for (const b of ['com.apple.controlcenter', 'com.apple.systemuiserver', 'com.apple.notificationcenterui']) {
|
|
2182
|
+
const a = runningApps().find(x => x.bundle === b);
|
|
2183
|
+
if (!a) continue;
|
|
2184
|
+
const mb = attr(appElement(a), 'AXExtrasMenuBar');
|
|
2185
|
+
if (!mb || !mb.el) continue;
|
|
2186
|
+
for (const it of children(mb.el)) {
|
|
2187
|
+
const v = readNode(it);
|
|
2188
|
+
const tag = [v.AXIdentifier, v.AXTitle, v.AXDescription].map(x => String(x || '')).join(' ').toLowerCase();
|
|
2189
|
+
if (/clock|notification center/.test(tag)) return it;
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
return null;
|
|
2193
|
+
}
|
|
2194
|
+
// True only on positive evidence that Notification Center's panel is already open: the menu-bar clock reads
|
|
2195
|
+
// selected / expanded, or a window holds a Notification Center element that is not a banner or alert.
|
|
2196
|
+
// Desktop widgets are windows of the same process (macOS 27.2: 180 × 180 AXUnknown windows, verified on a
|
|
2197
|
+
// real Mac), so "it has a window" is no evidence (t10 review).
|
|
2198
|
+
function ncCenterOpen(appEl, clock) {
|
|
2199
|
+
if (clock && (attr(clock, 'AXSelected') === true || attr(clock, 'AXExpanded') === true)) return true;
|
|
2200
|
+
for (const w of windowsOf(appEl)) {
|
|
2201
|
+
let panel = false;
|
|
2202
|
+
const scan = (el, d) => {
|
|
2203
|
+
if (d > 8 || panel) return;
|
|
2204
|
+
const v = readNode(el);
|
|
2205
|
+
if (v.__err) return;
|
|
2206
|
+
const sr = String(v.AXSubrole || '');
|
|
2207
|
+
if (sr.indexOf('AXNotificationCenter') === 0 && sr !== 'AXNotificationCenterBanner' && sr !== 'AXNotificationCenterAlert') { panel = true; return; }
|
|
2208
|
+
for (const k of v.AXChildren || []) scan(k, d + 1);
|
|
2209
|
+
};
|
|
2210
|
+
scan(w, 0);
|
|
2211
|
+
if (panel) return true;
|
|
2212
|
+
}
|
|
2213
|
+
return false;
|
|
2214
|
+
}
|
|
2215
|
+
function opNotifications(req) {
|
|
2216
|
+
if (!$.AXIsProcessTrusted()) return fail(permError());
|
|
2217
|
+
if (req.id === '' || req.expected_app === '' || req.expected_title === '') {
|
|
2218
|
+
return invalid('id, expected_app and expected_title must be non-empty strings');
|
|
2219
|
+
}
|
|
2220
|
+
const a = ncApp();
|
|
2221
|
+
if (!a) return fail(notDelivered({ code: 'APP_NOT_FOUND', message: 'Notification Center is not running' }));
|
|
2222
|
+
const appEl = appElement(a);
|
|
2223
|
+
const action = req.action || 'list';
|
|
2224
|
+
let opened = false, alreadyOpen = false;
|
|
2225
|
+
if (req.open_center) {
|
|
2226
|
+
const clock = clockExtra();
|
|
2227
|
+
if (ncCenterOpen(appEl, clock)) {
|
|
2228
|
+
alreadyOpen = true;
|
|
2229
|
+
} else {
|
|
2230
|
+
if (!clock) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: 'accessibility does not expose the menu-bar clock here, so Notification Center cannot be opened from noracu — open it yourself (click the clock) and list again; banners on screen are listed without it', details: { kind: 'open_center_unavailable' } }));
|
|
2231
|
+
if (perform(clock, 'AXPress') === 0) { opened = true; sleep(900); }
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
const all = collectNotifications(appEl);
|
|
2235
|
+
const close = () => { if (opened) { const c = clockExtra(); if (c) perform(c, 'AXPress'); } };
|
|
2236
|
+
if (action === 'list') {
|
|
2237
|
+
let list = all.map((n, i) => ({ index: i + 1, id: n.id, kind: n.kind, app: n.app, title: n.title, subtitle: n.subtitle, body: n.body, actions: n.actions }));
|
|
2238
|
+
if (req.app) list = list.filter(n => textMatch(n.app, req.app, false));
|
|
2239
|
+
if (req.text) list = list.filter(n => textMatch([n.title, n.subtitle, n.body].join('\n'), req.text, false));
|
|
2240
|
+
close();
|
|
2241
|
+
// center_opened: this call opened it (and closed it again); center_was_open: it was already open, so the clock was not clicked
|
|
2242
|
+
return { ok: true, count: list.length, notifications: list.slice(0, clamp(req.limit, 1, 100, 20)), center_opened: opened, center_was_open: alreadyOpen,
|
|
2243
|
+
note: list.length || opened || alreadyOpen ? undefined : 'only notifications on screen (banners, alerts, an open Notification Center) are visible to accessibility' };
|
|
2244
|
+
}
|
|
2245
|
+
// dismiss / act: by id (preferred) or 1-based index, and the listing must still match the fingerprint
|
|
2246
|
+
const hasId = typeof req.id === 'string' && req.id.length > 0;
|
|
2247
|
+
let n = hasId ? all.find(x => x.id === req.id) : (Number.isInteger(req.index) ? all[req.index - 1] : null);
|
|
2248
|
+
if (!n) {
|
|
2249
|
+
close();
|
|
2250
|
+
const missingMsg = hasId
|
|
2251
|
+
? `no notification with id ${req.id} is on screen (it may have been dismissed or moved into Notification Center)`
|
|
2252
|
+
: Number.isInteger(req.index)
|
|
2253
|
+
? `no notification at index ${req.index} (${all.length} visible on screen)`
|
|
2254
|
+
: 'give id (from mac_notifications list) or index';
|
|
2255
|
+
return fail(notDelivered({ code: 'NOTIFICATION_NOT_FOUND', message: missingMsg }));
|
|
2256
|
+
}
|
|
2257
|
+
if ((req.expected_app && !textMatch(n.app, req.expected_app, false)) || (req.expected_title && !textMatch(n.title, req.expected_title, false))) {
|
|
2258
|
+
close();
|
|
2259
|
+
return fail(notDelivered({ code: 'NOTIFICATION_NOT_FOUND', message: `the notification there now is from "${n.app}" titled "${n.title}", not the expected one — list again`, details: { kind: 'fingerprint_mismatch' } }));
|
|
2260
|
+
}
|
|
2261
|
+
const want = action === 'dismiss' ? 'close' : String(req.name || 'press').toLowerCase();
|
|
2262
|
+
const idx = n.rawActions.findIndex(x => String(actionLabel(x) || '').toLowerCase() === want);
|
|
2263
|
+
if (idx < 0) { close(); return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `the notification offers ${n.actions.join(', ') || 'no actions'}, not "${want}"`, details: { actions: n.actions } })); }
|
|
2264
|
+
const e = perform(n.el, n.rawActions[idx]);
|
|
2265
|
+
if (e !== 0) {
|
|
2266
|
+
// only "invalid element" proves it was gone before the action ran; after any other error a missing
|
|
2267
|
+
// notification may be this action's own effect, so delivery stays what the error says (t10 review)
|
|
2268
|
+
const goneNow = e !== -25202 && !collectNotifications(appEl).some(x => x.id === n.id);
|
|
2269
|
+
close();
|
|
2270
|
+
if (e === -25202) return fail(notDelivered({ code: 'NOTIFICATION_NOT_FOUND', message: `no notification with id ${n.id} is on screen (it was dismissed before the action ran)` }));
|
|
2271
|
+
const err = axCallError(e, `notification ${want}`);
|
|
2272
|
+
if (goneNow) err.message += ' — the notification is no longer on screen (this action may have closed it); list again before retrying';
|
|
2273
|
+
return fail(err);
|
|
2274
|
+
}
|
|
2275
|
+
sleep(500);
|
|
2276
|
+
const still = collectNotifications(appEl).some(x => x.id === n.id);
|
|
2277
|
+
close();
|
|
2278
|
+
return { ok: true, action: want, id: n.id, app: n.app, title: n.title, delivery: want === 'close' ? (still ? 'delivered_unverified' : 'delivered_verified') : 'delivered_unverified', retry: 'unsafe' };
|
|
2279
|
+
}
|
|
2280
|
+
|
|
2281
|
+
// ── menu bar commands ────────────────────────────────────────────────────────────────────────────
|
|
2282
|
+
// Menu items are reachable through the menu bar hierarchy without opening any menu; AXPress on an item
|
|
2283
|
+
// runs it without moving the pointer. `command` is an item title (must be unique in the menu bar) or a
|
|
2284
|
+
// path "File > Export > PDF…". Matching is by the titles the app shows, so it follows the app's language.
|
|
2285
|
+
function menuItems(menuBar, topMenu) {
|
|
2286
|
+
const out = [];
|
|
2287
|
+
const barKids = children(menuBar);
|
|
2288
|
+
let bars = [];
|
|
2289
|
+
for (let i = 0; i < barKids.length; i++) {
|
|
2290
|
+
const v = readNode(barKids[i]);
|
|
2291
|
+
if (v.__err || v.AXRole !== 'AXMenuBarItem') continue;
|
|
2292
|
+
bars.push({ el: barKids[i], bar: i, title: nameOf(v) });
|
|
2293
|
+
}
|
|
2294
|
+
// a path whose first segment names a top-level menu walks only that menu; a path that starts below
|
|
2295
|
+
// the top level ("Export > PDF…") still matches as a suffix anywhere
|
|
2296
|
+
if (topMenu) {
|
|
2297
|
+
const exact = bars.filter(b => b.title === topMenu);
|
|
2298
|
+
const scoped = exact.length ? exact : bars.filter(b => normMenu(b.title) === normMenu(topMenu));
|
|
2299
|
+
if (scoped.length) bars = scoped;
|
|
2300
|
+
}
|
|
2301
|
+
const visit = (el, path, bar, d) => {
|
|
2302
|
+
if (d > 8) return;
|
|
2303
|
+
for (const k of children(el)) {
|
|
2304
|
+
const v = readNode(k);
|
|
2305
|
+
if (v.__err) continue;
|
|
2306
|
+
if (v.AXRole === 'AXMenuItem') {
|
|
2307
|
+
const t = nameOf(v);
|
|
2308
|
+
const p = t ? path.concat(t) : path;
|
|
2309
|
+
if (t) out.push({ el: k, path: p, enabled: v.AXEnabled !== false, bar, id: v.AXIdentifier || '' });
|
|
2310
|
+
visit(k, p, bar, d + 1);
|
|
2311
|
+
} else if (v.AXRole === 'AXMenu') visit(k, path, bar, d + 1);
|
|
2312
|
+
}
|
|
2313
|
+
};
|
|
2314
|
+
for (const b of bars) visit(b.el, b.title ? [b.title] : [], b.bar, 1);
|
|
2315
|
+
return out;
|
|
2316
|
+
}
|
|
2317
|
+
function normMenu(x) { return String(x).replace(/[.…]+$/, '').trim().toLowerCase(); }
|
|
2318
|
+
// Menu shortcut attributes → chord id in the server's format ("alt+cmd+shift+q"), or null when none.
|
|
2319
|
+
// AXMenuItemCmdModifiers bits: 1 = Shift, 2 = Option, 4 = Control, 8 = NoCommand (Command is present unless bit 8 is set).
|
|
2320
|
+
function menuChord(cmdChar, mods, vk) {
|
|
2321
|
+
const ch = typeof cmdChar === 'string' ? cmdChar : '';
|
|
2322
|
+
const v = typeof vk === 'number' && Number.isInteger(vk) ? vk : null;
|
|
2323
|
+
let key = null;
|
|
2324
|
+
if (v === 117) key = 'fwd-delete';
|
|
2325
|
+
else if (ch === '\u0008' || v === 51) key = 'delete';
|
|
2326
|
+
else if (ch === '\u238b' || v === 53) key = 'esc';
|
|
2327
|
+
else if (ch.length === 1 && !/[\x00-\x1f\x7f-\x9f\ue000-\uf8ff]/.test(ch)) key = ch.toLowerCase();
|
|
2328
|
+
if (!key) return null;
|
|
2329
|
+
const m = typeof mods === 'number' ? mods : 0;
|
|
2330
|
+
const ms = [];
|
|
2331
|
+
if (m & 2) ms.push('alt');
|
|
2332
|
+
if (!(m & 8)) ms.push('cmd');
|
|
2333
|
+
if (m & 4) ms.push('ctrl');
|
|
2334
|
+
if (m & 1) ms.push('shift');
|
|
2335
|
+
return ms.concat(key).join('+');
|
|
2336
|
+
}
|
|
2337
|
+
function opMenu(req) {
|
|
2338
|
+
if (!$.AXIsProcessTrusted()) return fail(permError());
|
|
2339
|
+
const app = findApp(req.app);
|
|
2340
|
+
if (!app) return fail(notDelivered({ code: 'APP_NOT_FOUND', message: `no running app named "${req.app}"` }));
|
|
2341
|
+
const appEl = appElement(app);
|
|
2342
|
+
const mb = attr(appEl, 'AXMenuBar');
|
|
2343
|
+
if (!mb || !mb.el) return fail(notDelivered({ code: 'SURFACE_ABSENT', message: `"${app.name}" exposes no menu bar` }));
|
|
2344
|
+
const want = String(req.command || '').split(/\s*>\s*/).filter(Boolean);
|
|
2345
|
+
if (!want.length) return fail(notDelivered({ code: 'INVALID_ARGS', message: 'menu command required' }));
|
|
2346
|
+
const items = menuItems(mb.el, want.length > 1 ? want[0] : null);
|
|
2347
|
+
let hits = items.filter(i => i.path.length >= want.length && want.every((w, k) => i.path[i.path.length - want.length + k] === w));
|
|
2348
|
+
if (!hits.length) hits = items.filter(i => i.path.length >= want.length && want.every((w, k) => normMenu(i.path[i.path.length - want.length + k]) === normMenu(w)));
|
|
2349
|
+
if (!hits.length) return fail(notDelivered({ code: 'ACTION_FAILED', message: `no menu item "${req.command}" in ${app.name}`, details: { kind: 'menu_item_absent' } }));
|
|
2350
|
+
if (hits.length > 1) return fail(notDelivered({ code: 'AMBIGUOUS_TARGET', message: `${hits.length} menu items match "${req.command}" — give the path, e.g. "${hits[0].path.join(' > ')}"`, details: { kind: 'menu_item_ambiguous', paths: hits.slice(0, 8).map(h => h.path.join(' > ')) } }));
|
|
2351
|
+
const h = hits[0];
|
|
2352
|
+
const itemPath = h.path.join(' > ');
|
|
2353
|
+
// the shortcut is read for the chosen item only (not for every item walked)
|
|
2354
|
+
const chord = menuChord(attr(h.el, 'AXMenuItemCmdChar'), attr(h.el, 'AXMenuItemCmdModifiers'), attr(h.el, 'AXMenuItemCmdVirtualKey'));
|
|
2355
|
+
const isQuit = chord === 'cmd+q' || chord === 'alt+cmd+q' || h.id === 'terminate:' || h.id === 'NSAlternateQuitMenuItem';
|
|
2356
|
+
if (isQuit && PROTECTED_BUNDLES.has(app.bundle)) {
|
|
2357
|
+
return fail(notDelivered({ code: 'POLICY_DENIED', message: `"${itemPath}" in ${app.name}: ${app.name} (${app.bundle}) is part of the macOS session and is never quit` }));
|
|
2358
|
+
}
|
|
2359
|
+
if (isQuit && (req.protect_pids || []).indexOf(app.pid) >= 0) {
|
|
2360
|
+
return fail(notDelivered({ code: 'POLICY_DENIED', message: `"${itemPath}" in ${app.name}: ${app.name} runs noracu itself (the MCP host) — quitting it would end this session` }));
|
|
2361
|
+
}
|
|
2362
|
+
if (h.bar === 0 && req.force !== true) {
|
|
2363
|
+
return fail(notDelivered({ code: 'POLICY_DENIED', message: `"${itemPath}" is under the Apple menu (sleep, lock, log out, restart, shut down, Force Quit) — nothing was sent; pass force:true if that is intended` }));
|
|
2364
|
+
}
|
|
2365
|
+
if (chord && (req.deny_chords || []).indexOf(chord) >= 0 && req.force !== true) {
|
|
2366
|
+
return fail(notDelivered({ code: 'POLICY_DENIED', message: `"${itemPath}" in ${app.name} has shortcut ${chord}, which is a refused chord — nothing was sent; pass force:true if that is intended` }));
|
|
2367
|
+
}
|
|
2368
|
+
if (req.require_enabled === true && !h.enabled) {
|
|
2369
|
+
return fail(notDelivered({ code: 'ACTION_FAILED', message: `menu item "${itemPath}" in ${app.name} is disabled`, details: { kind: 'menu_item_disabled' } }));
|
|
2370
|
+
}
|
|
2371
|
+
// AppKit re-validates a menu only when it opens, so AXEnabled on an item of a closed menu can be stale
|
|
2372
|
+
// (Select All reads disabled while the text view would accept it). Pressing a truly disabled item does
|
|
2373
|
+
// nothing, so it is pressed anyway and the before/after reading decides what is reported.
|
|
2374
|
+
const before = observeState(null, appEl);
|
|
2375
|
+
const focusEl = attr(appEl, 'AXFocusedUIElement');
|
|
2376
|
+
const fBefore = focusEl && focusEl.el ? observeState(focusEl.el, appEl) : null;
|
|
2377
|
+
const e = perform(h.el, 'AXPress');
|
|
2378
|
+
if (e !== 0 && e !== -25204) return fail(axCallError(e, 'AXPress'));
|
|
2379
|
+
sleep(clamp(req.settle_ms, 0, 3000, 300));
|
|
2380
|
+
const v = verdict(before, observeState(null, appEl), { mechanism: 'semantic', action: 'AXPress', path: itemPath, app: app.name });
|
|
2381
|
+
// the focused element is where most menu commands land (Select All, Bold, Paste…)
|
|
2382
|
+
if (fBefore && v.delivery === 'delivered_unverified') {
|
|
2383
|
+
const fAfter = observeState(focusEl.el, appEl);
|
|
2384
|
+
const d = diffState(fBefore, fAfter);
|
|
2385
|
+
if (d.verified) { v.delivery = 'delivered_verified'; v.changed = d.changed; }
|
|
2386
|
+
}
|
|
2387
|
+
if (!h.enabled && v.delivery !== 'delivered_verified') v.note = 'the item reported disabled (menus refresh that state lazily) and nothing observable changed';
|
|
2388
|
+
if (e === -25204) { v.delivery = 'unknown'; v.note = 'the app did not answer in time (a modal menu or dialog may be open)'; }
|
|
2389
|
+
return v;
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
// A named key (return, esc, tab, arrows, F-keys…) with optional modifiers, posted to the frontmost app at
|
|
2393
|
+
// the HID level from a HID-state event source, the way a hardware keyboard sends it: each modifier pressed
|
|
2394
|
+
// (a flags-changed event), the key down and up 20 ms apart, the modifiers released last-first. Chrome's
|
|
2395
|
+
// address bar ignored cliclick 5.1's Return (0 of 2) and took these events (2 of 2) — iTerm2 Claude Code run
|
|
2396
|
+
// 2026-11-06. Flags are always set explicitly: a key event that carries a modifier flag without the
|
|
2397
|
+
// modifier's own press and release leaves the system believing it is still held (seen on the device run:
|
|
2398
|
+
// Cmd after cmd-arrow-up, Shift after shift-tab). Navigation and F-keys carry the Fn flag, arrows the
|
|
2399
|
+
// keypad flag, as hardware sends them. The server's focus guard runs before this op.
|
|
2400
|
+
const KEY_FLAGS = { cmd: 0x100000, shift: 0x20000, alt: 0x80000, ctrl: 0x40000, fn: 0x800000 };
|
|
2401
|
+
const MOD_KEYCODES = { cmd: 55, shift: 56, alt: 58, ctrl: 59 }; // left-hand keys; fn is a flag only (pressing Fn alone can switch input source)
|
|
2402
|
+
const FLAG_NUMPAD = 0x200000;
|
|
2403
|
+
const HELD_MASK = KEY_FLAGS.cmd | KEY_FLAGS.shift | KEY_FLAGS.alt | KEY_FLAGS.ctrl;
|
|
2404
|
+
const EV_FLAGS_CHANGED = 12;
|
|
2405
|
+
function postKey(code, modKeys, extra) {
|
|
2406
|
+
const src = $.CGEventSourceCreate($.kCGEventSourceStateHIDSystemState);
|
|
2407
|
+
const ev = (k, down, flags, flagsChanged) => {
|
|
2408
|
+
const e = $.CGEventCreateKeyboardEvent(src, k, down);
|
|
2409
|
+
if (!e) return null;
|
|
2410
|
+
if (flagsChanged) $.CGEventSetType(e, EV_FLAGS_CHANGED);
|
|
2411
|
+
$.CGEventSetFlags(e, flags);
|
|
2412
|
+
return e;
|
|
2413
|
+
};
|
|
2414
|
+
let flags = 0, ok = true;
|
|
2415
|
+
const held = [];
|
|
2416
|
+
for (const [k, f] of modKeys) {
|
|
2417
|
+
const e = ev(k, true, flags | f, true);
|
|
2418
|
+
if (!e) { ok = false; break; }
|
|
2419
|
+
flags |= f; $.CGEventPost($.kCGHIDEventTap, e); held.push([k, f]); sleep(5);
|
|
2420
|
+
}
|
|
2421
|
+
if (ok) {
|
|
2422
|
+
const down = ev(code, true, flags | extra, false), up = ev(code, false, flags | extra, false);
|
|
2423
|
+
if (down && up) { $.CGEventPost($.kCGHIDEventTap, down); sleep(20); $.CGEventPost($.kCGHIDEventTap, up); }
|
|
2424
|
+
else ok = false;
|
|
2425
|
+
}
|
|
2426
|
+
for (const [k, f] of held.reverse()) {
|
|
2427
|
+
flags &= ~f;
|
|
2428
|
+
const e = ev(k, false, flags, true);
|
|
2429
|
+
if (e) $.CGEventPost($.kCGHIDEventTap, e);
|
|
2430
|
+
sleep(5);
|
|
2431
|
+
}
|
|
2432
|
+
return ok;
|
|
2433
|
+
}
|
|
2434
|
+
// The modifiers this call pressed that the system still believes held (CGEventSourceFlagsState, HID
|
|
2435
|
+
// state) get one more release each; modifiers the user is holding on the keyboard are left alone.
|
|
2436
|
+
// Returns the names still held after that (normally none).
|
|
2437
|
+
function releaseStuckModifiers(names) {
|
|
2438
|
+
const mask = names.reduce((a, m) => a | KEY_FLAGS[m], 0) & HELD_MASK;
|
|
2439
|
+
const now = () => Number($.CGEventSourceFlagsState($.kCGEventSourceStateHIDSystemState)) & mask;
|
|
2440
|
+
if (!mask || !now()) return [];
|
|
2441
|
+
const src = $.CGEventSourceCreate($.kCGEventSourceStateHIDSystemState);
|
|
2442
|
+
for (const m of names) {
|
|
2443
|
+
if (!MOD_KEYCODES[m]) continue;
|
|
2444
|
+
const e = $.CGEventCreateKeyboardEvent(src, MOD_KEYCODES[m], false);
|
|
2445
|
+
if (!e) continue;
|
|
2446
|
+
$.CGEventSetType(e, EV_FLAGS_CHANGED); $.CGEventSetFlags(e, 0); $.CGEventPost($.kCGHIDEventTap, e);
|
|
2447
|
+
}
|
|
2448
|
+
sleep(30);
|
|
2449
|
+
const left = now();
|
|
2450
|
+
return names.filter(m => MOD_KEYCODES[m] && (left & KEY_FLAGS[m]));
|
|
2451
|
+
}
|
|
2452
|
+
function opKey(req) {
|
|
2453
|
+
const code = req.code;
|
|
2454
|
+
if (!Number.isInteger(code) || code < 0 || code > 127) return fail(notDelivered({ code: 'INVALID_ARGS', message: 'key: code must be an integer 0-127' }));
|
|
2455
|
+
const mods = Array.isArray(req.mods) ? req.mods : [];
|
|
2456
|
+
const modKeys = [];
|
|
2457
|
+
let extra = 0;
|
|
2458
|
+
for (const m of mods) {
|
|
2459
|
+
if (!Object.prototype.hasOwnProperty.call(KEY_FLAGS, m)) return fail(notDelivered({ code: 'INVALID_ARGS', message: `key: unknown modifier "${String(m).slice(0, 20)}"` }));
|
|
2460
|
+
if (m === 'fn') extra |= KEY_FLAGS.fn;
|
|
2461
|
+
else modKeys.push([MOD_KEYCODES[m], KEY_FLAGS[m]]);
|
|
2462
|
+
}
|
|
2463
|
+
if (req.fn_key === true) extra |= KEY_FLAGS.fn;
|
|
2464
|
+
if (req.numpad === true) extra |= FLAG_NUMPAD;
|
|
2465
|
+
const sent = postKey(code, modKeys, extra);
|
|
2466
|
+
const stuck = releaseStuckModifiers(mods.filter(m => m !== 'fn'));
|
|
2467
|
+
if (!sent) return fail(notDelivered({ code: 'ACTION_FAILED', message: 'key: could not create the keyboard events', details: stuck.length ? { modifiers_still_held: stuck } : undefined }));
|
|
2468
|
+
const out = { ok: true, delivery: 'delivered_unverified', retry: 'unsafe', flags: modKeys.reduce((a, [, f]) => a | f, 0) | extra };
|
|
2469
|
+
if (stuck.length) out.note = `the system still reports ${stuck.join('+')} held — press and release it on the keyboard`;
|
|
2470
|
+
return out;
|
|
2471
|
+
}
|
|
2472
|
+
|
|
2473
|
+
const OPS = {
|
|
2474
|
+
key: opKey,
|
|
2475
|
+
snapshot: opSnapshot, find: opFind, get: opGet, apps: opApps, windows: opWindows, status: opStatus,
|
|
2476
|
+
act: opAct, physical_prep: opPhysicalPrep, observe_after: opObserveAfter, insert_text: opInsertText, set_value: opSetValue, scroll_prep: opScrollPrep,
|
|
2477
|
+
menu: opMenu, wait: opWait, frontmost: opFrontmost, app_info: opAppInfo, app_ctl: opAppCtl, app_wait: opAppWait, window_op: opWindowOp, clipboard: opClipboard, paste: opPaste, notifications: opNotifications,
|
|
2478
|
+
};
|
|
2479
|
+
|
|
2480
|
+
function readStdin() {
|
|
2481
|
+
const d = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile;
|
|
2482
|
+
return $.NSString.alloc.initWithDataEncoding(d, $.NSUTF8StringEncoding).js;
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
function run(argv) {
|
|
2486
|
+
let req;
|
|
2487
|
+
try { req = JSON.parse(readStdin()); } catch (e) { return JSON.stringify({ ok: false, code: 'INVALID_ARGS', message: 'request is not JSON' }); }
|
|
2488
|
+
const fn = OPS[req && req.op];
|
|
2489
|
+
if (!fn) return JSON.stringify({ ok: false, code: 'INVALID_ARGS', message: `unknown op "${req && req.op}"` });
|
|
2490
|
+
// the system-wide element's messaging timeout is this process's default for every element whose own
|
|
2491
|
+
// timeout is unset (children, parents, hit-test results): a hung app costs at most this per call
|
|
2492
|
+
try { $.AXUIElementSetMessagingTimeout($.AXUIElementCreateSystemWide(), AX_MSG_TIMEOUT_S); } catch (e) { /* keep the default */ }
|
|
2493
|
+
try { return JSON.stringify(fn(req)); } catch (e) { return JSON.stringify({ ok: false, code: 'INTERNAL', message: String(e).slice(0, 300) }); }
|
|
2494
|
+
}
|