noracu 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mac-ax.js CHANGED
@@ -26,6 +26,7 @@ ObjC.import('ApplicationServices');
26
26
  ObjC.import('AppKit');
27
27
  ObjC.import('CoreGraphics');
28
28
  ObjC.import('Foundation');
29
+ ObjC.import('signal');
29
30
 
30
31
  // ── CF type ids and small bridges ──────────────────────────────────────────────────────────────
31
32
  const TID = {
@@ -93,8 +94,10 @@ function children(el) {
93
94
  for (let i = 0; i < n; i++) out.push(arr.objectAtIndex(i));
94
95
  return out;
95
96
  }
96
- function elemsOf(el, name) {
97
+ // errOut (optional) gets the AX error of the read: an empty list is "none" only when err is 0
98
+ function elemsOf(el, name, errOut) {
97
99
  const a = attrErr(el, name);
100
+ if (errOut) errOut.err = a.err;
98
101
  if (a.err !== 0) return [];
99
102
  const o = cast(a.raw);
100
103
  if (!o) return [];
@@ -228,21 +231,41 @@ function frontApp() {
228
231
  try { bundle = x.bundleIdentifier.js || ''; } catch (e) { /* none */ }
229
232
  return { ns: x, name: x.localizedName.js, bundle, pid: Number(x.processIdentifier) };
230
233
  }
231
- function findApp(spec) {
232
- if (!spec) return frontApp();
234
+ // The running apps a spec stands for. "pid:<number>" is that process. A .app path: every process started from
235
+ // it. A name or a bundle id: exact matches before case-insensitive ones, and among those only the most app-like
236
+ // kind (a Dock app before a menu-bar app before a helper).
237
+ function appCandidates(spec) {
233
238
  const apps = runningApps();
234
239
  const want = String(spec);
240
+ const byPid = /^pid:(\d{1,7})$/.exec(want);
241
+ if (byPid) return apps.filter(a => a.pid === Number(byPid[1]));
242
+ let hit;
235
243
  if (/^\/.+\.app\/?$/.test(want)) {
244
+ // every process started from that bundle — its helpers included, which the policy rule below leaves out
236
245
  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;
246
+ hit = apps.filter(a => { try { return a.ns.bundleURL && !a.ns.bundleURL.isNil() && a.ns.bundleURL.path.js === p; } catch (e) { return false; } });
247
+ } else {
248
+ const lower = want.toLowerCase();
249
+ hit = apps.filter(a => a.name === want || a.bundle === want);
250
+ if (!hit.length) hit = apps.filter(a => a.name.toLowerCase() === lower || a.bundle.toLowerCase() === lower);
239
251
  }
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];
252
+ if (!hit.length) return hit;
253
+ const best = Math.min.apply(null, hit.map(a => a.policy));
254
+ return hit.filter(a => a.policy === best);
255
+ }
256
+ // Several running apps under one name — two copies of an app, two apps with the same display name. None of them
257
+ // is picked for the caller: the answer lists them, and "pid:<number>" names one.
258
+ function ambiguousApp(spec, hit) {
259
+ const front = frontApp();
260
+ const apps = hit.map(a => ({ pid: a.pid, name: a.name, bundle_id: a.bundle, frontmost: Boolean(front && front.pid === a.pid) }));
261
+ return notDelivered({ code: 'AMBIGUOUS_APP', message: `"${String(spec).slice(0, 80)}" names ${apps.length} running apps (${apps.map(x => `pid ${x.pid}${x.frontmost ? ', frontmost' : ''}`).join('; ')}) — nothing was done; name the one you mean as "pid:<number>" (mac_apps lists them)`, details: { apps } });
262
+ }
263
+ // One app, none (null), or — thrown, and answered by dispatch — the refusal for a name several apps share.
264
+ function findApp(spec) {
265
+ if (!spec) return frontApp();
266
+ const hit = appCandidates(spec);
267
+ if (hit.length > 1) throw { noracu: ambiguousApp(spec, hit) };
268
+ return hit[0] || null;
246
269
  }
247
270
  const POLICY = ['foreground', 'background', 'helper'];
248
271
 
@@ -282,11 +305,12 @@ function enableWebAccessibility(appEl) {
282
305
  function webAxStatus(setter, rootEl, rootPath, isWindow) {
283
306
  if (setter !== 'unsupported' || !isWindow) return setter;
284
307
  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';
308
+ // "unsupported" says the window holds no web content: only a search that looked through all of it can say so
309
+ return w.nodes.length ? 'exposed' : w.complete ? 'unsupported' : 'unknown';
286
310
  }
287
311
 
288
312
  // ── containers (where a path starts) ─────────────────────────────────────────────────────────────
289
- function windowsOf(appEl) { return elemsOf(appEl, 'AXWindows'); }
313
+ function windowsOf(appEl, errOut) { return elemsOf(appEl, 'AXWindows', errOut); }
290
314
  // The CGWindowID behind an AX window (HIServices' _AXUIElementGetWindow, bound at run time). It is the
291
315
  // window's identity for its whole life, so an element is only ever re-found inside the very window it was
292
316
  // seen in. null when the function is unavailable or the element is not a real window.
@@ -311,9 +335,12 @@ function windowIdOf(el) {
311
335
  }
312
336
  return null;
313
337
  }
338
+ // A window whose attributes could not be read is marked unreadable: its empty title, missing frame and "not
339
+ // minimized" are not what it is, so it is never picked as the window a snapshot is about by default
314
340
  function windowInfo(w, n) {
315
341
  const v = readNode(w);
316
- 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 };
342
+ const bad = v.__err !== undefined ? { unreadable: true } : {};
343
+ return { ...bad, 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 };
317
344
  }
318
345
  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; }
319
346
  // Finder's desktop: the one window without a CGWindowID seen on the test Mac (wid probe 2026-11-06; its
@@ -329,12 +356,44 @@ function isFinderDesktop(app, c) {
329
356
  return rectNear([x0, y0, x1 - x0, y1 - y0], c.frame, 2) || ds.some(f => rectNear(f, c.frame, 2));
330
357
  }
331
358
 
359
+ // The windows of one process that the window server lists but does not show now: on another Space, minimized,
360
+ // or of a hidden app. Accessibility lists none of an app's windows on another Space, so this count is the only
361
+ // sign that such an app has windows at all. -1 when the process or the list could not be read.
362
+ function offscreenWindowCount(appEl) {
363
+ try {
364
+ const pr = Ref();
365
+ if (Number($.AXUIElementGetPid(appEl, pr)) !== 0) return -1;
366
+ const pid = Number(pr[0]);
367
+ const info = cast($.CGWindowListCopyWindowInfo($.kCGWindowListOptionAll, 0));
368
+ if (!pid || !info) return -1;
369
+ let n = 0;
370
+ for (let i = 0, c = Number(info.count); i < c; i++) {
371
+ const d = info.objectAtIndex(i);
372
+ const num = k => { const o = d.objectForKey(ks(k)); return o && !o.isNil() ? o.js : undefined; };
373
+ if (Number(num('kCGWindowOwnerPID')) !== pid || Number(num('kCGWindowLayer') || 0) !== 0 || num('kCGWindowIsOnscreen')) continue;
374
+ n++;
375
+ }
376
+ return n;
377
+ } catch (e) { return -1; }
378
+ }
379
+ // No window of the app can be read. The answer says which case it is, because the next step differs: an app
380
+ // with windows on another Space is brought forward only by moving the person's desktop there.
381
+ function noWindowError(appEl) {
382
+ const n = offscreenWindowCount(appEl);
383
+ if (n > 0) return { code: 'WINDOW_NOT_FOUND', message: `the app has no window that accessibility can read from the desktop in view: the window server lists ${n} of its windows off screen (on another Space, minimized to the Dock, or the app is hidden) — mac_windows with include_offscreen:true lists them; mac_app activate brings the app forward, and macOS may then switch the person's desktop to it`, details: { offscreen_windows: n } };
384
+ if (n === 0) return { code: 'WINDOW_NOT_FOUND', message: 'the app has no window open (the window server lists none of its windows, on screen or off)', details: { offscreen_windows: 0 } };
385
+ return { code: 'WINDOW_NOT_FOUND', message: 'the app has no window that accessibility can read (not open, minimized to the Dock, or on another Space)' };
386
+ }
387
+
332
388
  // Pick the window a snapshot is about: an explicit index/title, else the focused or main window,
333
389
  // else the only window. Several candidates and no way to choose → AMBIGUOUS_WINDOW with the list.
334
390
  function pickWindow(appEl, req) {
335
- const ws = windowsOf(appEl);
391
+ const read = {};
392
+ const ws = windowsOf(appEl, read);
336
393
  const infos = ws.map((w, i) => windowInfo(w, i));
337
- 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)' } };
394
+ // the window list did not answer (a busy or hung app): that is not "no window, minimized or on another Space"
395
+ if (!ws.length && read.err === -25204) return { error: { code: 'APP_UNRESPONSIVE', message: 'the app did not answer when its windows were asked for (busy or hung) — try again in a moment' } };
396
+ if (!ws.length) return { error: noWindowError(appEl) };
338
397
  if (req.window_id !== undefined && req.window_id !== null) {
339
398
  const hit = infos.filter(x => x.wid === Number(req.window_id));
340
399
  if (hit.length === 1) return { el: ws[hit[0].n], info: hit[0] };
@@ -348,19 +407,26 @@ function pickWindow(appEl, req) {
348
407
  }
349
408
  const hits = infos.filter(x => x.title === want);
350
409
  const loose = hits.length ? hits : infos.filter(x => x.title.toLowerCase().indexOf(String(want).toLowerCase()) >= 0);
351
- if (loose.length === 1) return { el: ws[loose[0].n], info: loose[0] };
410
+ // no title is the one asked for, and one contains it (any case): that one, and the answer says so
411
+ if (loose.length === 1) return { el: ws[loose[0].n], info: loose[0], partial: !hits.length };
352
412
  return { error: { code: loose.length ? 'AMBIGUOUS_WINDOW' : 'WINDOW_NOT_FOUND', message: `${loose.length || 'no'} window(s) match "${want}"`, details: { windows: infos.map(summaryOfWindow) } } };
353
413
  }
354
414
  const f = infos.filter(x => x.focused);
355
415
  if (f.length === 1) return { el: ws[f[0].n], info: f[0] };
356
416
  const m = infos.filter(x => x.main);
357
417
  if (m.length === 1) return { el: ws[m[0].n], info: m[0] };
358
- const vis = infos.filter(x => !x.minimized);
418
+ const vis = infos.filter(x => !x.minimized && !x.unreadable);
359
419
  if (vis.length === 1) return { el: ws[vis[0].n], info: vis[0] };
360
420
  if (ws.length === 1) return { el: ws[0], info: infos[0] };
361
421
  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) } } };
362
422
  }
363
- function summaryOfWindow(x) { return { n: x.n, window_id: x.wid, title: x.title.slice(0, 80), frame: x.frame, minimized: x.minimized }; }
423
+ // the app's windows that are dialogs of their own (subrole AXDialog / AXSystemDialog), as { el, info }
424
+ function dialogWindows(appEl) {
425
+ const ws = windowsOf(appEl), out = [];
426
+ for (let i = 0; i < ws.length; i++) { const sr = attr(ws[i], 'AXSubrole'); if (sr === 'AXDialog' || sr === 'AXSystemDialog') out.push({ el: ws[i], info: windowInfo(ws[i], i) }); }
427
+ return out;
428
+ }
429
+ function summaryOfWindow(x) { return { n: x.n, window_id: x.wid, title: x.title.slice(0, 80), frame: x.frame, minimized: x.minimized, ...(x.unreadable ? { unreadable: true } : {}) }; }
364
430
 
365
431
  function surfaceRoot(appEl, win, surface) {
366
432
  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' } }; }
@@ -441,34 +507,41 @@ function makeNode(v, ldepth, path, actions, interactive) {
441
507
  return node;
442
508
  }
443
509
 
510
+ const NO_WINDOW_ID = -1;
444
511
  // Returns flat nodes in document order. Each node carries what the server needs to show it and to
445
512
  // find it again (path from the container root). Logical depth skips transparent wrappers.
446
513
  function walk(rootEl, rootPath, opt) {
447
514
  const nodes = [];
448
515
  const deadline = now() + opt.budgetMs;
449
516
  let visited = 0;
450
- let complete = true;
517
+ let complete = true, rootErr = 0;
518
+ let outline = false; // a skeleton snapshot left children out at its depth limit (it still reports complete)
451
519
  const skeleton = Boolean(opt.skeleton);
452
520
  const maxDepth = skeleton ? Math.min(opt.depth, 3) : opt.depth;
453
521
  // anc: evidence about the path from the container down to this node (see pathEvidence, which re-derives
454
522
  // it while resolving) — the child count at every level (shape), the labels of the ancestors (chain),
455
- // and the text collectors of the nearest ITEM_LEVELS ancestors (item keys, see itemKeyOf)
523
+ // the text collectors of the nearest ITEM_LEVELS ancestors (accs: one of them becomes the node's item,
524
+ // see itemKeyOf), and every collector still taking texts (open: an ancestor collects at any depth)
456
525
  function visit(el, path, ldepth, inMenuBar, anc) {
457
526
  if (nodes.length >= opt.maxNodes || now() > deadline || visited >= opt.maxVisit) { complete = false; return 'stop'; }
458
527
  visited++;
459
- collect(anc.accs, null, true);
528
+ collect(anc.open, null, true);
460
529
  const v = readNode(el);
461
- if (v.__err) { if (v.__err !== -25202) complete = false; return; } // vanished: skip; unanswered: incomplete
530
+ // a descendant that vanished is skipped; one that did not answer, or a root that is gone, leaves the walk incomplete
531
+ if (v.__err) { if (el === rootEl) rootErr = v.__err; if (v.__err !== -25202 || el === rootEl) complete = false; return; }
462
532
  const role = v.AXRole || '?';
463
533
  const isRoot = el === rootEl;
464
534
  // a text field's value counts for an ancestor's item only through a cell or row (table content)
465
535
  const t = itemText(v, true);
466
- if (t) collect(anc.accs, t, false, TEXT_ROLES.has(role) ? anc.cells : null);
536
+ if (t) collect(anc.open, t, false, TEXT_ROLES.has(role));
467
537
  if (opt.pruneMenuBar && (role === 'AXMenuBar') && !inMenuBar) return;
468
538
  // every visited element counts towards "is this fingerprint unique" — also the ones a filtered
469
539
  // (find) or interactive-only snapshot does not show
470
540
  const fid = fpKey(role, v.AXSubrole || '', v.AXIdentifier || '', stableName(v));
471
541
  seen[fid] = (seen[fid] || 0) + 1;
542
+ // where it sits, to count the look-alikes of an item among all visited elements (see the end of walk)
543
+ const rec = { fid, accs: anc.accs, own: null };
544
+ recs.push(rec);
472
545
  const actions = actionNames(el);
473
546
  const wrapper = isWrapper(v, actions);
474
547
  const interactive = isInteractive(v, actions);
@@ -477,10 +550,13 @@ function walk(rootEl, rootPath, opt) {
477
550
  const show = !(opt.compact && wrapper) && (!opt.interactive || interactive || (skeleton && atLimit && kids.length));
478
551
  // app-level snapshots (no window container): an element under a window records that window's
479
552
  // CGWindowID, so a window closed and reopened with the same content is not taken for the old one
480
- const wwid = opt.trackWindow ? (role === 'AXWindow' ? axWindowId(el) : anc.wwid) : null;
553
+ // a window without an id (NO_WINDOW_ID) cannot be told from one closed and reopened with the same content:
554
+ // what is seen inside it is marked, and the resolver refuses it as it refuses a window-level snapshot of
555
+ // such a window (Finder's desktop is the exception there and here)
556
+ const wwid = opt.trackWindow ? (role === 'AXWindow' ? (axWindowId(el) || (opt.noIdOk && opt.noIdOk(el) ? null : NO_WINDOW_ID)) : anc.wwid) : null;
481
557
  if (opt.find ? matches(v, opt.find) : show) {
482
558
  const node = makeNode(v, ldepth, path, actions, interactive);
483
- if (wwid) node.fp.wwid = wwid;
559
+ if (wwid === NO_WINDOW_ID) node.fp.wnoid = true; else if (wwid) node.fp.wwid = wwid;
484
560
  if (anc.chain.length) node.fp.chain = chainKey(anc.chain);
485
561
  node._shape = anc.shape.slice();
486
562
  node._accs = anc.accs;
@@ -489,15 +565,16 @@ function walk(rootEl, rootPath, opt) {
489
565
  nodes.push(node);
490
566
  if (opt.find && nodes.length >= opt.find.limit) { complete = false; return 'stop'; }
491
567
  }
492
- 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; }
568
+ if (atLimit && !opt.find) { if (kids.length && !skeleton) complete = false; if (kids.length && skeleton) outline = true; if (kids.length) for (const x of anc.open) if (!x.a.full) x.a.cut = true; return; }
493
569
  const nextDepth = wrapper ? ldepth : ldepth + 1;
494
570
  const name = isRoot && opt.rootIsContainer ? '' : chainName(v);
495
571
  // the container itself is never an item (its texts are the whole window's: toolbars, status lines),
496
572
  // nor are page-, toolbar- or pane-level groups
497
573
  const own = { texts: [], seen: 0, full: false, cut: false, closed: false, noItem: (isRoot && Boolean(opt.rootIsContainer)) || ITEM_SKIP_ROLES.has(role) };
498
574
  if (nodes.length && nodes[nodes.length - 1]._el === el) nodes[nodes.length - 1]._own = own;
575
+ rec.own = own;
499
576
  const cell = CELL_ROLES.has(role);
500
- 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), wwid };
577
+ 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), open: [{ a: own, cell }].concat(anc.open.filter(x => !x.a.full).map(x => ({ a: x.a, cell: x.cell || cell }))), wwid };
501
578
  if (atLimit) own.cut = true;
502
579
  for (let i = 0; i < kids.length; i++) {
503
580
  if (visit(kids[i], path.concat(i), nextDepth, inMenuBar || role === 'AXMenuBar', childAnc) === 'stop') return 'stop';
@@ -506,7 +583,8 @@ function walk(rootEl, rootPath, opt) {
506
583
  }
507
584
  const pre = opt.evidence || { shape: [], chain: [] };
508
585
  const seen = {};
509
- visit(rootEl, rootPath.slice(), 0, false, { shape: pre.shape.slice(), chain: pre.chain.slice(), accs: [], cells: [], wwid: opt.trackWindow ? windowIdOf(rootEl) : null });
586
+ const recs = [];
587
+ visit(rootEl, rootPath.slice(), 0, false, { shape: pre.shape.slice(), chain: pre.chain.slice(), accs: [], open: [], wwid: opt.trackWindow ? windowIdOf(rootEl) : null });
510
588
  // Elements that share their fingerprint with another one in the container (several "Delete" buttons,
511
589
  // one per list item) are told apart by their surroundings: the path shape, and the item key. Uniqueness
512
590
  // is known only when the whole container was walked: a snapshot that stopped early, or one drilled into
@@ -514,10 +592,12 @@ function walk(rootEl, rootPath, opt) {
514
592
  // Every labelled element also records its item key — the first texts under itself or its nearest
515
593
  // ancestor (within ITEM_LEVELS, never the container) that has any — because a look-alike can appear
516
594
  // after the snapshot (a second message arriving above the only one there was). Every element records
517
- // its path shape. An item key that two look-alikes share (both rows climbed to the same section
518
- // heading) tells nothing apart and is dropped.
519
- const whole = complete && opt.rootIsContainer !== false;
520
- const picked = new Map();
595
+ // its path shape. An item key that two look-alikes share (two rows that both climbed to the same section
596
+ // heading, or two unlabelled buttons of one row) does not tell them apart: it is marked shared, and a
597
+ // search never picks one of them by it. It is kept all the same, because it still says where they are —
598
+ // found by its path, such an element must still sit in that item (a recycled row is another item).
599
+ // a skeleton that left children out has not seen the whole container either
600
+ const whole = complete && !outline && opt.rootIsContainer !== false;
521
601
  for (const n of nodes) {
522
602
  const fid = fpKey(n.fp.role, n.fp.subrole, n.fp.id, n.fp.name);
523
603
  const dup = !whole || seen[fid] > 1;
@@ -529,20 +609,35 @@ function walk(rootEl, rootPath, opt) {
529
609
  const accs = [n._own].concat(n._accs);
530
610
  for (let k = 0; k < accs.length; k++) {
531
611
  const a = accs[k];
612
+ // the row or group around it (not its own subtree) was not read in full: its texts — what tells this
613
+ // element from the same control of another row — are unknown, and the element is refused for actions
614
+ if (k > 0 && a && a.cut && !a.noItem) { n.fp.rowcut = true; break; }
532
615
  if (a && a.closed && !a.cut && !a.noItem && a.texts.length) {
533
616
  n.fp.item = `${k}:${a.texts.join('\u0001')}`;
534
617
  n._acc = a;
535
- if (dup) { if (!picked.has(fid)) picked.set(fid, new Map()); const m = picked.get(fid); m.set(a, (m.get(a) || 0) + 1); }
536
618
  break;
537
619
  }
538
620
  }
539
621
  }
540
622
  }
623
+ // look-alikes that share an item are counted over every visited element — also the ones a filtered snapshot
624
+ // (mac_find, interactive) left out: a left-out look-alike in the same row makes the row's texts tell nothing
625
+ // apart. A left-out one whose nearer group was not read in full is counted at the first item that was.
626
+ const want = new Set();
627
+ for (const n of nodes) if (n.fp.dup && n._acc) want.add(fpKey(n.fp.role, n.fp.subrole, n.fp.id, n.fp.name));
628
+ const byItem = new Map();
629
+ for (const r of recs) {
630
+ if (!want.has(r.fid)) continue;
631
+ const a = [r.own].concat(r.accs).find((x) => x && x.closed && !x.cut && !x.noItem && x.texts.length);
632
+ if (!a) continue;
633
+ if (!byItem.has(r.fid)) byItem.set(r.fid, new Map());
634
+ const m = byItem.get(r.fid); m.set(a, (m.get(a) || 0) + 1);
635
+ }
541
636
  for (const n of nodes) {
542
- 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; }
637
+ if (n.fp.dup && n._acc) { const m = byItem.get(fpKey(n.fp.role, n.fp.subrole, n.fp.id, n.fp.name)); if (m && m.get(n._acc) > 1) n.fp.shared = true; }
543
638
  delete n._shape; delete n._accs; delete n._el; delete n._own; delete n._acc;
544
639
  }
545
- return { nodes, complete, visited };
640
+ return { nodes, complete, visited, rootErr };
546
641
  }
547
642
 
548
643
  function textMatch(have, want, exact) {
@@ -615,13 +710,16 @@ function itemText(v, cellOk) {
615
710
  }
616
711
  function fpKey(role, subrole, id, name) { return [role, subrole, id, name].join('\u0001'); }
617
712
  // walk-side collection: every visited descendant counts against ITEM_VISIT (whether or not it answers),
618
- // texts are kept in document order until ITEM_TEXTS — itemKeyOf counts the same way
619
- function collect(accs, text, counting, mask) {
620
- for (let j = 0; j < accs.length; j++) {
621
- const a = accs[j];
713
+ // texts are kept in document order until ITEM_TEXTS — itemKeyOf counts the same way. `open` holds every
714
+ // ancestor whose collector is not full yet, however far up, as { a, cell } (cell: a cell or row lies
715
+ // between that ancestor and the node — itemKeyOf's cellOk): an item's texts are often many levels below
716
+ // it (web content), and itemKeyOf reads them at any depth. `field`: the text is a text field's value.
717
+ function collect(open, text, counting, field) {
718
+ for (let j = 0; j < open.length; j++) {
719
+ const a = open[j].a;
622
720
  if (a.full) continue;
623
721
  if (counting) { if (++a.seen > ITEM_VISIT) a.full = true; continue; }
624
- if (text && (!mask || mask[j])) { a.texts.push(text); if (a.texts.length >= ITEM_TEXTS) a.full = true; }
722
+ if (text && (!field || open[j].cell)) { a.texts.push(text); if (a.texts.length >= ITEM_TEXTS) a.full = true; }
625
723
  }
626
724
  }
627
725
  function chainName(v) { return VOLATILE_NAME_ROLES.has(v.AXRole) ? '' : stableName(v).replace(/\d+/g, '#'); }
@@ -711,16 +809,46 @@ function climbEvidence(e, root) {
711
809
  }
712
810
  return null;
713
811
  }
812
+ // A number in a unique element's item may change in place only when its form says it is a reading and not a name:
813
+ // a clock time or a duration (12:30, 1:02:03), a percentage (45%), a time span with its unit (5 min, 3h, 2 days
814
+ // ago, 3 分钟前), an explicit count (3 unread, Unread 3, 12 items, 2 new messages) or — as a text of its own — a
815
+ // count against a fixed total above 31 that is not a year (12/280: the total has to stay). Any other number is
816
+ // part of the item's name: "Invoice 12" replaced in place by "Invoice 13" is another item, and so are "Room 5",
817
+ // "$1,200", "Report (2)" and a date.
818
+ // a one-letter unit ends the token: "104s-2" and "2hx" are no spans
819
+ const READING_UNIT = '(?:(?:[Ss]ecs?|[Ss]econds?|[Mm]ins?|[Mm]inutes?|[Hh]rs?|[Hh]ours?|[Dd]ays?|[Ww]ks?|[Ww]eeks?|[Mm]onths?|[Yy]rs?|[Yy]ears?)(?![A-Za-z])|[smh](?![\\w-]))';
820
+ // a reading's number has nothing glued to its front: no letter or digit ("A12%", "x5 min"), no currency sign
821
+ // ("$12m"), no 第 ("第3天" is Day 3). The character before it is kept by the match and left as it is.
822
+ const READING_FRONT = '(?:^|[^\\w$€£¥₹₩第.,])';
823
+ const COUNT_WORD = '(?:[Uu]nread|[Nn]ew|[Ii]tems?|[Mm]essages?|[Nn]otifications?|[Cc]omments?|[Rr]epl(?:y|ies)|[Rr]esults?|[Ss]elected|[Rr]emaining|[Ll]eft|[Mm]ore|[Uu]pdates?|未读|未讀)';
824
+ const COUNT_NAMED = '(?:[Uu]nread|[Ii]tems|[Mm]essages|[Nn]otifications|[Cc]omments|[Rr]eplies|[Rr]esults|[Uu]pdates|未读|未讀)';
825
+ const TEXT_END = '(?=\\s*(?:$|\\u0001|[)\\])】,.;:!?·|]))';
826
+ const READING = new RegExp([
827
+ '(?:^|[^\\d:])\\d{1,2}:\\d{2}(?::\\d{2})?(?![\\d:])', // a whole clock: not the middle of "912:30", not the start of "12:300"
828
+ READING_FRONT + '\\d+(?:[.,]\\d+)?\\s?%',
829
+ READING_FRONT + '\\d+(?:[.,]\\d+)?\\s?' + READING_UNIT,
830
+ READING_FRONT + '\\d+\\s?(?:秒|分钟|分鐘|小时|小時|天)(?:[前后後内內]|(?![\\u4e00-\\u9fff]))', // 3 分钟前, 5 分钟 — not 3天行程, 24小时制
831
+ READING_FRONT + '\\d+\\+?\\s?(?:条|條|封|则|則|个|個)?\\s?' + COUNT_WORD + '(?:\\s' + COUNT_WORD + ')?' + TEXT_END,
832
+ COUNT_NAMED + ':?\\s?\\d+\\+?' + TEXT_END,
833
+ ].join('|'), 'g');
834
+ function steadyItem(key) {
835
+ const i = key.indexOf(':');
836
+ return key.slice(0, i + 1) + key.slice(i + 1).split('\u0001').map((t) => {
837
+ const m = /^(\d+)\s?\/\s?(\d+)$/.exec(t);
838
+ if (m) { const total = Number(m[2]); return total > 31 && !(total >= 1900 && total < 2100) ? `#/${m[2]}` : t; }
839
+ return t.replace(READING, (s) => s.replace(/\d+/g, '#'));
840
+ }).join('\u0001');
841
+ }
714
842
  // item key check: level 0 is the element itself, then its ancestors nearest first (the container last)
715
- // A look-alike's item must match exactly ("Invoice 12" is not "Invoice 13"); a unique element's item
716
- // ignores digits like the ancestor chain does (a counter or a relative time in the same group changes)
843
+ // A look-alike's item must match exactly; a unique element's item may differ in the numbers steadyItem lets
844
+ // change (a counter or a relative time in the same group changes while the element stays the same)
717
845
  function itemSame(el, ancs, fp, skipMenuBar, exact) {
718
846
  if (!fp.item) return true;
719
847
  const k = itemLevel(fp);
720
848
  const a = k === 0 ? el : ancs[k - 1];
721
849
  if (!a) return false;
722
850
  const live = itemKeyOf(a, k, skipMenuBar);
723
- return fp.dup || exact ? live === fp.item : live.replace(/\d+/g, '#') === fp.item.replace(/\d+/g, '#');
851
+ return fp.dup || exact ? live === fp.item : steadyItem(live) === steadyItem(fp.item);
724
852
  }
725
853
  function itemLevel(fp) { return fp.item ? Number(fp.item.slice(0, fp.item.indexOf(':'))) : -1; }
726
854
  // open menus (a pop-up, a context menu, a menu bar menu while it is open)
@@ -763,10 +891,21 @@ function containerEl(appEl, c, app) {
763
891
  return { error: 'container_unknown' };
764
892
  }
765
893
  const SEARCH_MAX_DEPTH = 150, SEARCH_MAX_VISIT = 20000;
894
+ function unverifiableWindow() {
895
+ return { code: 'POLICY_DENIED', message: 'the element\'s window had no window ID when it was read, so a window closed and reopened with the same title and frame could not be told apart from it — element_index actions in this window are refused (use the app\'s menu with mac_menu_command, or mac_click x,y, which checks the window on top)', details: { kind: 'window_unverifiable' } };
896
+ }
766
897
  // An element seen in an app-level snapshot recorded the CGWindowID of the window it was in (fp.wwid):
767
898
  // found again, it must still be in that very window — a window closed and reopened with the same content
768
899
  // has a new id and is a stale reference (Reddit r/mcp review 2026-11-06).
769
- function resolveTarget(t, budgetMs) {
900
+ // An element of a row that the snapshot did not read in full (fp.rowcut) is found for a read (mac_get, a wait, a
901
+ // drill with root) but refused for an action: without the row's texts nothing tells it from the same control of
902
+ // another row that took the row's place with the same shape.
903
+ function rowUnread() {
904
+ return { code: 'STALE_REF', message: 'the row or group this element is in was not read in full (the snapshot stopped above its texts: skeleton, depth or max_nodes), so it cannot be told from the same control of another row — drill into the row with root, or take a snapshot without skeleton or with a higher depth, and act on an index from that', details: { kind: 'row_unread' } };
905
+ }
906
+ function resolveTarget(t, budgetMs, read) {
907
+ if (t && t.fp && t.fp.wnoid) return { error: unverifiableWindow() };
908
+ if (t && t.fp && t.fp.rowcut && !read) return { error: rowUnread() };
770
909
  const r = resolveTargetCore(t, budgetMs);
771
910
  if (r.error || !t || !t.fp || !t.fp.wwid) return r;
772
911
  const live = windowIdOf(r.el);
@@ -782,7 +921,7 @@ function resolveTargetCore(t, budgetMs) {
782
921
  const kind = t.container && t.container.kind || 'app';
783
922
  const c = containerEl(appEl, t.container, app);
784
923
  if (c.error === 'window_unverifiable') {
785
- return { error: { code: 'POLICY_DENIED', message: 'the element\'s window had no window ID when it was read, so a window closed and reopened with the same title and frame could not be told apart from it — element_index actions in this window are refused (use the app\'s menu with mac_menu_command, or mac_click x,y, which checks the window on top)', details: { kind: 'window_unverifiable' } } };
924
+ return { error: unverifiableWindow() };
786
925
  }
787
926
  if (c.error) {
788
927
  const amb = /ambiguous/.test(c.error);
@@ -805,7 +944,7 @@ function resolveTargetCore(t, budgetMs) {
805
944
  // the shape of the path must hold unless the element's own item (itself or its parent) vouches for
806
945
  // it word for word — an unlabelled element always needs it; a different shape sends a labelled one
807
946
  // to the search (a row prepended above "Invoice 12" that reads "Invoice 13" is not a match)
808
- const ownItem = !anon && itemLevel(t.fp) >= 0 && itemLevel(t.fp) <= 1;
947
+ const ownItem = !anon && !t.fp.shared && itemLevel(t.fp) >= 0 && itemLevel(t.fp) <= 1;
809
948
  const shaped = shapeOk(pe.shape);
810
949
  if (!v.__err && fpOk(v, t.fp) && frameNear(v, t.fp, c.shift, anon ? POS_TOL : PATH_NAMED_TOL) && chainOk(pe.chain)
811
950
  && (shaped ? (!t.fp.item || itemSame(pe.el, ancs, t.fp, skipMenuBar)) : ownItem && itemSame(pe.el, ancs, t.fp, skipMenuBar, true))) {
@@ -833,10 +972,12 @@ function resolveTargetCore(t, budgetMs) {
833
972
  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)); };
834
973
  if (t.fp.dup) {
835
974
  // one of several look-alikes (a Delete per list item): only its item's texts tell which one it was
836
- 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' } } };
975
+ if (!t.fp.item || t.fp.shared) 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' } } };
837
976
  const agree = hits.filter(h => evOk(h, true));
838
977
  const pick = agree.length > 1 ? agree.filter(h => frameNear(h.v, t.fp, c.shift, POS_TOL)) : agree;
839
- if (pick.length === 1 && (complete || agree.length === 1)) return found(pick[0], 'search+item');
978
+ // a search that could not read everything may have missed the real one: the only match it did read counts
979
+ // only where the element was (as for a unique element below)
980
+ if (pick.length === 1 && (complete || (agree.length === 1 && frameNear(pick[0].v, t.fp, c.shift, POS_TOL)))) return found(pick[0], 'search+item');
840
981
  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' } } };
841
982
  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' } } };
842
983
  }
@@ -872,9 +1013,9 @@ function opSnapshot(req) {
872
1013
  pruneMenuBar: true,
873
1014
  };
874
1015
  // contEl: the element the container record stands for (where paths start); the root is walked
875
- let root, container, basePath = [], winInfo = null, surface = req.surface || 'window', contEl = null;
1016
+ let root, container, basePath = [], winInfo = null, winPartial = false, surface = req.surface || 'window', contEl = null;
876
1017
  if (req.root) {
877
- const r = resolveTarget(req.root, 3000);
1018
+ const r = resolveTarget(req.root, 3000, true);
878
1019
  if (r.error) return fail(r.error);
879
1020
  // children are numbered from where the root is now, not from where it was (it may have been found
880
1021
  // by search after siblings moved)
@@ -887,12 +1028,21 @@ function opSnapshot(req) {
887
1028
  else {
888
1029
  const w = pickWindow(appEl, req);
889
1030
  if (w.error) return fail(w.error);
890
- root = w.el; container = w.info; winInfo = w.info;
1031
+ root = w.el; container = w.info; winInfo = w.info; winPartial = Boolean(w.partial);
891
1032
  }
892
1033
  contEl = root;
893
1034
  } else {
894
1035
  let win = null;
895
- 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; }
1036
+ if (surface === 'sheet' || surface === 'alert' || surface === 'popover' || surface === 'dialog') {
1037
+ const w = pickWindow(appEl, req);
1038
+ if (w.error) {
1039
+ // several windows and none focused: a dialog or alert that is a window of its own is the answer when it is
1040
+ // the only one (the windows were not looked at before AMBIGUOUS_WINDOW); a window asked for stays asked for
1041
+ const own = (surface === 'alert' || surface === 'dialog') && w.error.code === 'AMBIGUOUS_WINDOW' && req.window == null && req.window_id == null ? dialogWindows(appEl) : [];
1042
+ if (own.length !== 1) return fail(w.error);
1043
+ win = own[0]; winInfo = own[0].info;
1044
+ } else { win = w; winInfo = w.info; winPartial = Boolean(w.partial); }
1045
+ }
896
1046
  const s = surfaceRoot(appEl, win, surface);
897
1047
  if (!s) return fail({ code: 'INVALID_ARGS', message: `unknown surface "${surface}"` });
898
1048
  if (s.error) return fail(s.error);
@@ -923,17 +1073,25 @@ function opSnapshot(req) {
923
1073
  }
924
1074
  const t0 = now();
925
1075
  const rv = readNode(root);
926
- if (rv.__err === -25204) return fail({ code: 'APP_UNRESPONSIVE', message: `"${app.name}" did not answer accessibility in time (it may be busy or hung)` });
1076
+ // A root that cannot be read is an error, never an empty tree — whichever of the two reads of it fails (this
1077
+ // one, or the walk's a moment later). Gone between being picked and being read is a window that just closed.
1078
+ const rootError = (err) => err === -25204 ? fail({ code: 'APP_UNRESPONSIVE', message: `"${app.name}" did not answer accessibility in time (it may be busy or hung)` })
1079
+ : err === -25202 ? fail({ code: 'STALE_REF', message: 'what was being snapshotted went away as the snapshot started — take a new snapshot', details: { kind: 'gone' } })
1080
+ : err === -25211 ? fail(permError())
1081
+ : fail({ code: 'INTERNAL', message: `the root of the snapshot could not be read (accessibility error ${err})` });
1082
+ if (rv.__err) return rootError(rv.__err);
927
1083
  opt.trackWindow = !container || container.kind === 'app';
1084
+ opt.noIdOk = (winEl) => isFinderDesktop(app, windowInfo(winEl, 0));
928
1085
  const w = walk(root, basePath, opt);
1086
+ if (w.rootErr) return rootError(w.rootErr);
929
1087
  const out = {
930
1088
  ok: true, app: app.name, bundle_id: app.bundle, pid: app.pid, surface, complete: w.complete,
931
1089
  container: containerOut(container), nodes: w.nodes, visited: w.visited, ms: now() - t0,
932
1090
  };
933
1091
  if (req.root) out.root_path = basePath;
934
- if (winInfo) out.window = { title: winInfo.title, frame: winInfo.frame, n: winInfo.n, window_id: winInfo.wid };
1092
+ if (winInfo) out.window = { title: winInfo.title, frame: winInfo.frame, n: winInfo.n, window_id: winInfo.wid, ...(winPartial ? { title_match: 'partial' } : {}) };
935
1093
  if (webAx) out.web_accessibility = webAxStatus(webAx, root, basePath, surface === 'window');
936
- if (container && container.kind === 'window' && !container.wid && !isFinderDesktop(app, container)) out.window_identity = 'unverifiable';
1094
+ if ((container && container.kind === 'window' && !container.wid && !isFinderDesktop(app, container)) || w.nodes.some(n => n.fp.wnoid)) out.window_identity = 'unverifiable';
937
1095
  return out;
938
1096
  }
939
1097
  function containerOut(c) {
@@ -970,15 +1128,15 @@ function opFind(req) {
970
1128
  else { const w = pickWindow(appEl, req); if (w.error) return fail(w.error); root = w.el; container = w.info; }
971
1129
  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) };
972
1130
  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' });
973
- 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, trackWindow: surface === 'app' });
1131
+ 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, trackWindow: surface === 'app', noIdOk: (winEl) => isFinderDesktop(app, windowInfo(winEl, 0)) });
974
1132
  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 };
975
1133
  if (webAx) out.web_accessibility = webAxStatus(webAx, root, basePath, surface === 'window');
976
- if (container && container.kind === 'window' && !container.wid && !isFinderDesktop(app, container)) out.window_identity = 'unverifiable';
1134
+ if ((container && container.kind === 'window' && !container.wid && !isFinderDesktop(app, container)) || w.nodes.some(n => n.fp.wnoid)) out.window_identity = 'unverifiable';
977
1135
  return out;
978
1136
  }
979
1137
 
980
1138
  function opGet(req) {
981
- const r = resolveTarget(req.target, 3000);
1139
+ const r = resolveTarget(req.target, 3000, true);
982
1140
  if (r.error) return fail(r.error);
983
1141
  const v = r.v;
984
1142
  const out = { ok: true, how: r.how, role: v.AXRole, title: nameOf(v) };
@@ -1023,11 +1181,21 @@ function displays() {
1023
1181
  }
1024
1182
 
1025
1183
  function opWindows(req) {
1184
+ // app: a name, a bundle id, a .app path or "pid:<number>" names one process, as for every other tool — several
1185
+ // apps under one name are refused (ambiguous_app). A word that names no app exactly still filters the window
1186
+ // owners' names by substring, as before ("Chrome" lists Google Chrome's windows).
1187
+ let wantPid = null;
1188
+ if (req.app) {
1189
+ const hit = appCandidates(req.app);
1190
+ if (hit.length > 1) throw { noracu: ambiguousApp(req.app, hit) };
1191
+ if (hit.length === 1) wantPid = hit[0].pid;
1192
+ }
1026
1193
  const opts = req.include_offscreen ? $.kCGWindowListOptionAll : ($.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements);
1027
1194
  const info = cast($.CGWindowListCopyWindowInfo(opts, 0));
1028
1195
  const front = frontApp();
1029
1196
  const out = [];
1030
- let named = 0;
1197
+ let named = 0, me = -1;
1198
+ try { me = Number($.NSProcessInfo.processInfo.processIdentifier); } catch (e) { /* not known */ }
1031
1199
  const n = info ? Number(info.count) : 0;
1032
1200
  const wantApp = req.app ? String(req.app).toLowerCase() : '';
1033
1201
  for (let i = 0; i < n; i++) {
@@ -1036,12 +1204,14 @@ function opWindows(req) {
1036
1204
  const layer = Number(get('kCGWindowLayer') ? get('kCGWindowLayer').js : 0);
1037
1205
  if (layer !== 0 && !req.all_layers) continue;
1038
1206
  const owner = get('kCGWindowOwnerName') ? get('kCGWindowOwnerName').js : '';
1039
- if (wantApp && owner.toLowerCase().indexOf(wantApp) < 0) continue;
1207
+ if (wantPid !== null ? Number(get('kCGWindowOwnerPID') ? get('kCGWindowOwnerPID').js : 0) !== wantPid : (wantApp && owner.toLowerCase().indexOf(wantApp) < 0)) continue;
1040
1208
  const b = get('kCGWindowBounds');
1041
1209
  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;
1042
1210
  const title = get('kCGWindowName') ? get('kCGWindowName').js : null;
1043
- if (title !== null) named++;
1044
1211
  const pid = Number(get('kCGWindowOwnerPID') ? get('kCGWindowOwnerPID').js : 0);
1212
+ // a title the window server gave: another process's, and not empty — this process's own windows are named
1213
+ // without Screen Recording permission, and an empty title is no title
1214
+ if (title && pid !== me) named++;
1045
1215
  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) });
1046
1216
  }
1047
1217
  // Without Screen Recording permission window titles are withheld; fill them from accessibility.
@@ -1051,11 +1221,19 @@ function opWindows(req) {
1051
1221
  for (const pid of Object.keys(byPid)) {
1052
1222
  const appEl = $.AXUIElementCreateApplication(Number(pid));
1053
1223
  $.AXUIElementSetMessagingTimeout(appEl, 1.0);
1054
- const ws = windowsOf(appEl);
1055
- for (let i = 0; i < ws.length; i++) {
1056
- const wi = windowInfo(ws[i], i);
1057
- const hit = byPid[pid].find(x => rectNear(x.bounds, wi.frame, 2));
1058
- if (hit) { hit.title = wi.title; hit.ax_index = i; }
1224
+ const infos = windowsOf(appEl).map((w, i) => windowInfo(w, i));
1225
+ // the row with the window's id
1226
+ infos.forEach((wi, i) => {
1227
+ const hit = wi.wid ? byPid[pid].find(x => x.ax_index === undefined && x.id === wi.wid) : null;
1228
+ if (hit) { if (!wi.unreadable) hit.title = wi.title; hit.ax_index = i; }
1229
+ });
1230
+ // a window whose id cannot be read: by its frame, and only when that names one such window and one row no
1231
+ // window has taken — a frame that two of either share does not say which is which (one may be minimized or
1232
+ // on another Space and have no row at all), and a guess would put one window's title on another
1233
+ const noId = infos.map((wi, i) => ({ wi, i })).filter(o => !o.wi.wid);
1234
+ for (const o of noId) {
1235
+ const rows = byPid[pid].filter(x => x.ax_index === undefined && rectNear(x.bounds, o.wi.frame, 2));
1236
+ if (rows.length === 1 && noId.filter(p => rectNear(p.wi.frame, o.wi.frame, 2)).length === 1) { rows[0].title = o.wi.title; rows[0].ax_index = o.i; }
1059
1237
  }
1060
1238
  }
1061
1239
  }
@@ -1111,18 +1289,52 @@ function axCallError(code, what) {
1111
1289
  return { code: 'ACTION_FAILED', message: `${what}: accessibility error ${code}`, delivery: 'unknown', retry: 'unsafe' };
1112
1290
  }
1113
1291
 
1292
+ // -25204 is also what a call to an app that has just exited returns: then the element is gone, not slow.
1293
+ // Unknown (no pid) counts as still running. A view hosted by a helper process (an open or save panel) has
1294
+ // the helper's pid, which is not among the apps: the process itself is asked for (kill with signal 0).
1295
+ function appOfElementExited(el) {
1296
+ try {
1297
+ const pr = Ref();
1298
+ if (Number($.AXUIElementGetPid(el, pr)) !== 0) return false;
1299
+ const pid = Number(pr[0]);
1300
+ return Number.isInteger(pid) && pid > 0 && !runningApps().some(a => a.pid === pid) && Number($.kill(pid, 0)) !== 0;
1301
+ } catch (e) { return false; }
1302
+ }
1114
1303
  // Transient checks are polled until the budget runs out: the element must still exist and be enabled.
1304
+ // waited: the element was not actionable at the first look, so time went by before it was
1115
1305
  function waitActionable(el, timeoutMs) {
1116
1306
  const end = now() + timeoutMs;
1117
- for (;;) {
1307
+ for (let waited = false; ; waited = true) {
1118
1308
  const v = readNode(el);
1119
- if (v.__err) return { error: notDelivered({ code: 'STALE_REF', message: 'the element disappeared', details: { kind: 'gone' } }) };
1120
- if (v.AXEnabled !== false) return { v };
1309
+ // only -25202 means the element is gone; an app that did not answer, or a lost permission, is said as such
1310
+ if (v.__err === -25202 || (v.__err === -25204 && appOfElementExited(el))) return { error: notDelivered({ code: 'STALE_REF', message: 'the element disappeared', details: { kind: 'gone' } }) };
1311
+ if (v.__err === -25204) return { error: notDelivered({ code: 'APP_UNRESPONSIVE', message: 'the app did not answer in time while the element was being checked — nothing was sent' }) };
1312
+ if (v.__err === -25211) return { error: notDelivered(permError()) };
1313
+ if (v.__err) return { error: notDelivered({ code: 'ACTION_FAILED', message: `the element could not be read (accessibility error ${v.__err}) — nothing was sent` }) };
1314
+ if (v.AXEnabled !== false) return { v, waited };
1121
1315
  if (now() >= end) return { error: notDelivered({ code: 'NOT_ACTIONABLE', message: 'the element is disabled', details: { kind: 'disabled' } }) };
1122
1316
  sleep(100);
1123
1317
  }
1124
1318
  }
1125
1319
 
1320
+ // An element that was waited for (it was disabled, for up to 30 s) is looked up once more before anything is done
1321
+ // to it: a list re-uses one accessibility element for another row, and what became enabled may not be the row
1322
+ // that was asked for. Returns the refusal, or null when it is still the same element.
1323
+ function changedWhileWaited(target, r, w) {
1324
+ if (!w.waited) return null;
1325
+ let again;
1326
+ try { again = resolveTarget(target, 1000); } catch (e) { again = { error: true }; }
1327
+ if (!again.error && same(again.el, r.el)) return null;
1328
+ // A control with an identifier of its own — no other element of the snapshot had it, and it is not part of a
1329
+ // list item — that only changed its label while it was waited for ("Loading…" → "Submit") is still that control.
1330
+ const fp = target && target.fp;
1331
+ if (fp && fp.id && !fp.dup && !fp.item) {
1332
+ const v = readNode(r.el);
1333
+ if (!v.__err && (v.AXIdentifier || '') === fp.id && (v.AXRole || '') === fp.role && (v.AXSubrole || '') === (fp.subrole || '')) return null;
1334
+ }
1335
+ return notDelivered({ code: 'STALE_REF', message: 'the element changed while it was waited for (it was disabled) — take a new snapshot', details: { kind: 'changed_while_waited' } });
1336
+ }
1337
+
1126
1338
  function menuOpen(appEl) {
1127
1339
  const mb = attr(appEl, 'AXMenuBar');
1128
1340
  if (mb && mb.el) for (const item of children(mb.el)) if (attr(item, 'AXSelected') === true) return true;
@@ -1136,7 +1348,7 @@ function observeState(el, appEl) {
1136
1348
  if (el) {
1137
1349
  const v = readNode(el);
1138
1350
  // only an invalid element (-25202) is gone; any other read error (-25204: the app did not answer in time)
1139
- // says nothing about the element, so it is unknown, never evidence of a change (audit S5A-s10-G-3 / -D-2)
1351
+ // says nothing about the element, so it is unknown, never evidence of a change
1140
1352
  if (v.__err && v.__err !== -25202) o.gone = null;
1141
1353
  if (!v.__err) {
1142
1354
  o.gone = false;
@@ -1154,6 +1366,20 @@ function observeState(el, appEl) {
1154
1366
  }
1155
1367
  const ws = windowsOf(appEl);
1156
1368
  o.windows = ws.map(w => `${attr(w, 'AXSubrole') || ''}:${attr(w, 'AXTitle') || ''}`);
1369
+ // for an action on an element: which kinds of windows there are, and the title of the element's own window
1370
+ // (see diffState — another window's title is not evidence)
1371
+ if (el) {
1372
+ o.windowKinds = ws.map(w => String(attr(w, 'AXSubrole') || '')).sort();
1373
+ // the element's window: its AXWindow, else the first window on the way up; null when neither is found
1374
+ let ow = attr(el, 'AXWindow');
1375
+ for (let up = el, d = 0; !(ow && ow.el) && d < 60; d++) {
1376
+ const p = attr(up, 'AXParent');
1377
+ if (!p || !p.el) break;
1378
+ if (attr(p.el, 'AXRole') === 'AXWindow') { ow = p; break; }
1379
+ up = p.el;
1380
+ }
1381
+ o.ownWindow = ow && ow.el ? String(attr(ow.el, 'AXTitle') || '') : null;
1382
+ }
1157
1383
  o.sheets = 0;
1158
1384
  for (const w of ws) for (const k of children(w)) if (attr(k, 'AXRole') === 'AXSheet') o.sheets++;
1159
1385
  o.menu = menuOpen(appEl);
@@ -1172,7 +1398,18 @@ function diffState(a, b, keys) {
1172
1398
  const allowed = Array.isArray(keys) ? new Set(keys) : null;
1173
1399
  // a key not read on either side (the element gone or unreadable there) proves nothing; neither does an unknown gone
1174
1400
  const known = (s, k) => (k === 'gone' ? s.gone !== null : !(s.gone !== false && s[k] === undefined));
1175
- const verified = changed.some(k => !WEAK_STATE_KEYS.has(k) && (!allowed || allowed.has(k)) && known(a, k) && known(b, k));
1401
+ // For an action on an element, the list of window titles changing is evidence only when a window opened,
1402
+ // closed or changed kind, or when the title that changed is the element's own window's: another window's
1403
+ // title moves on its own (an unread count, a timer, a terminal's title) while the action did nothing.
1404
+ // When the element cannot be asked for its window afterwards, its window is looked for in the list by the
1405
+ // title it had: one window fewer with that title is evidence, another title changing is not. An element
1406
+ // with no window to be found before the action is judged as it always was.
1407
+ const ownKnown = typeof a.ownWindow === 'string' && typeof b.ownWindow === 'string';
1408
+ const ownLost = typeof a.ownWindow === 'string' && b.ownWindow === null;
1409
+ const titled = (s, t) => (s.windows || []).filter(w => String(w).slice(String(w).indexOf(':') + 1) === t).length;
1410
+ const windowsCount = JSON.stringify(a.windowKinds) !== JSON.stringify(b.windowKinds)
1411
+ || (ownKnown ? a.ownWindow !== b.ownWindow : ownLost ? titled(b, a.ownWindow) < titled(a, a.ownWindow) : true);
1412
+ const verified = changed.some(k => !WEAK_STATE_KEYS.has(k) && (k !== 'windows' || windowsCount) && (!allowed || allowed.has(k)) && known(a, k) && known(b, k));
1176
1413
  const surfaces = [];
1177
1414
  if ((b.sheets || 0) > (a.sheets || 0)) surfaces.push('sheet');
1178
1415
  if (b.menu && !a.menu) surfaces.push('menu');
@@ -1196,6 +1433,7 @@ function opAct(req) {
1196
1433
  if (r.error) return fail(notDelivered(r.error));
1197
1434
  const w = waitActionable(r.el, clamp(req.timeout_ms, 0, 30000, 3000));
1198
1435
  if (w.error) return fail(w.error);
1436
+ { const cw = changedWhileWaited(req.target, r, w); if (cw) return fail(cw); }
1199
1437
  const v = w.v;
1200
1438
  const actions = actionNames(r.el);
1201
1439
  let action = req.action;
@@ -1249,7 +1487,13 @@ function opFrontmost(req) {
1249
1487
  // at: [x, y] also reports whose window is on top at that point (raw-coordinate clicks check it first)
1250
1488
  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]);
1251
1489
  if (req.pid !== undefined || req.app) {
1252
- const t = req.pid !== undefined ? runningApps().find(a => a.pid === Number(req.pid)) || null : findApp(req.app);
1490
+ let t = null;
1491
+ if (req.pid !== undefined) t = runningApps().find(a => a.pid === Number(req.pid)) || null;
1492
+ else {
1493
+ // a name several running apps share: no target — and the refusal goes along, for the caller to answer with
1494
+ const hit = appCandidates(req.app);
1495
+ if (hit.length > 1) out.ambiguous = ambiguousApp(req.app, hit); else t = hit[0] || null;
1496
+ }
1253
1497
  out.target = t ? { pid: t.pid, name: t.name, bundle: t.bundle } : null;
1254
1498
  out.match = Boolean(f && t && f.pid === t.pid);
1255
1499
  }
@@ -1280,8 +1524,27 @@ function dockStrips() {
1280
1524
  return dockStripsOf(screens);
1281
1525
  }
1282
1526
  function inRect(x, y, r) { return x >= r[0] && y >= r[1] && x < r[0] + r[2] && y < r[1] + r[3]; }
1527
+ // Where the Dock's tiles are drawn now, from accessibility (the frames of the Dock app's own elements, its list
1528
+ // of tiles), with a little margin for the platter. With "Automatically hide and show the Dock" on, macOS keeps
1529
+ // no strip for the Dock, so a Dock that had popped up over the bottom of the screen was not seen and a click
1530
+ // there would have landed on a Dock icon. Device run 2026-11-19, macOS 27.2, a 1440-pt display: the list's top
1531
+ // is at 1369 while the Dock shows and at 1440 (past the edge) while it is hidden, and the hidden Dock's
1532
+ // full-display window is not on screen at all.
1533
+ // Unreadable: none (the strip alone decides, as before).
1534
+ function dockDrawn() {
1535
+ try {
1536
+ const a = runningApps().find(x => x.bundle === 'com.apple.dock');
1537
+ if (!a) return [];
1538
+ const out = [];
1539
+ for (const k of children(appElement(a))) {
1540
+ const f = frameOf(readNode(k));
1541
+ if (f) out.push([f[0] - 6, f[1] - 6, f[2] + 12, f[3] + 12]);
1542
+ }
1543
+ return out;
1544
+ } catch (e) { return []; }
1545
+ }
1283
1546
  // While a banner or alert shows, Notification Center keeps one full-display window above everything (layer
1284
- // 23) that lets clicks through except where a notification is drawn (E2 run 2026-11-07, macOS 27.2: a
1547
+ // 23) that lets clicks through except where a notification is drawn (device run 2026-11-07, macOS 27.2: a
1285
1548
  // memory-warning banner at the top right made a point in the middle of the screen read as covered). The
1286
1549
  // frames of the banners and alerts on screen, from accessibility; null — the whole overlay counts as
1287
1550
  // covering — when Notification Center's list is open, an element cannot be read, or none is found.
@@ -1310,7 +1573,7 @@ function ncDrawnRects() {
1310
1573
  // The topmost on-screen window at a point, front to back, as the window server stacks them. Skipped:
1311
1574
  // invisible windows (alpha 0), desktop-level ones (negative layer), and the Dock's full-display overlay,
1312
1575
  // which lets clicks through — except over the strip macOS keeps for the Dock, where the Dock is drawn:
1313
- // there the overlay counts as covering (E2 run 2026-11-07: on macOS 27 the Dock has no window of its own
1576
+ // there the overlay counts as covering (device run 2026-11-07: on macOS 27 the Dock has no window of its own
1314
1577
  // for its platter, so a point under the Dock read as the window behind it). The strip is the whole width
1315
1578
  // (or height) the Dock reserves, the gaps beside its platter included. Other Dock-owned windows cover
1316
1579
  // what is under them. Notification Center's full-display overlay (shown with a banner or alert) is
@@ -1319,7 +1582,7 @@ function ncDrawnRects() {
1319
1582
  function cgTopAt(x, y) {
1320
1583
  const list = cast($.CGWindowListCopyWindowInfo((1 << 0) | (1 << 4), 0)); // on screen only, no desktop elements
1321
1584
  if (!list) return null;
1322
- let screens = null, strips = null, nc;
1585
+ let screens = null, strips = null, drawn = null, nc;
1323
1586
  for (let i = 0; i < Number(list.count); i++) {
1324
1587
  const d = list.objectAtIndex(i);
1325
1588
  const g = k => { const o = d.objectForKey(ks(k)); return o && !o.isNil() ? o.js : null; };
@@ -1335,7 +1598,11 @@ function cgTopAt(x, y) {
1335
1598
  if (screens.some(f => rectNear(f, [bx, by, bw, bh], 2))) {
1336
1599
  if (owner === 'Dock') {
1337
1600
  if (!strips) strips = dockStrips();
1338
- if (!strips.some(r => inRect(x, y, r))) continue;
1601
+ // outside the strip: covered where the Dock is drawn now (a Dock that hides itself has no strip)
1602
+ if (!strips.some(r => inRect(x, y, r))) {
1603
+ if (!drawn) drawn = dockDrawn();
1604
+ if (!drawn.some(r => inRect(x, y, r))) continue;
1605
+ }
1339
1606
  } else {
1340
1607
  if (nc === undefined) nc = ncDrawnRects();
1341
1608
  if (nc && !nc.some(r => inRect(x, y, r))) continue;
@@ -1355,15 +1622,24 @@ function opPhysicalPrep(req) {
1355
1622
  if (r.error) return fail(notDelivered(r.error));
1356
1623
  const w = waitActionable(r.el, clamp(req.timeout_ms, 0, 30000, 3000));
1357
1624
  if (w.error) return fail(w.error);
1625
+ { const cw = changedWhileWaited(req.target, r, w); if (cw) return fail(cw); }
1358
1626
  const fr = frameOf(w.v);
1359
1627
  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' } }));
1360
1628
  const x = Math.round(fr[0] + fr[2] / 2), y = Math.round(fr[1] + fr[3] / 2);
1361
1629
  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' } }));
1362
1630
  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' } }));
1363
- // the element's window id: its AXWindow or the window up its AXParent chain (R20); else, for a window
1631
+ // the element's window id: its AXWindow or the window up its AXParent chain; else, for a window
1364
1632
  // snapshot, the snapshot's window
1365
1633
  let ewid = windowIdOf(r.el);
1366
1634
  if (!ewid && req.target && req.target.container && req.target.container.kind === 'window') ewid = (r.containerEl && axWindowId(r.containerEl)) || req.target.container.wid || null;
1635
+ // Finder's desktop, whatever the snapshot was of: the window the snapshot was taken of, or — for an element of
1636
+ // an app-wide snapshot, whose container is the app — the element's own window (no window id; the desktop's
1637
+ // title, subrole and frame)
1638
+ const ownWin = ewid ? null : attr(r.el, 'AXWindow');
1639
+ const desktop = Boolean((req.target && req.target.container && isFinderDesktop(r.app, req.target.container))
1640
+ || (ownWin && ownWin.el && isFinderDesktop(r.app, windowInfo(ownWin.el, 0))));
1641
+ // no window id of its own: the window on top at the point is read before the hit test and again after it
1642
+ const topBefore = ewid ? null : cgTopAt(x, y);
1367
1643
  const h = hitTest(r.el, x, y);
1368
1644
  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 } }));
1369
1645
  if (h.verdict === 'unknown') {
@@ -1374,20 +1650,34 @@ function opPhysicalPrep(req) {
1374
1650
  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 } } }));
1375
1651
  // the app's own window, but not the one the element is in (a floating panel, another document)
1376
1652
  // the element's own window id; else its AXWindow's; else (a window snapshot) the snapshot's window —
1377
- // an unknown window id must not skip the check (R19)
1653
+ // an unknown window id must not skip the check
1378
1654
  // without the element's window id the topmost window cannot be confirmed to be that window: refuse
1379
- // (R20 follow-up) — except Finder's desktop, which sits below every window and has no id
1380
- const desktop = req.target && req.target.container && isFinderDesktop(r.app, req.target.container);
1381
- if (!ewid && !desktop) return fail(notDelivered({ code: 'OCCLUDED', message: `the hit test at ${x},${y} was inconclusive and the element's window has no window ID, so the window on top cannot be confirmed to be its own — use the element's semantic action (mechanism auto) or bring its window to the front and take a new snapshot`, details: { occluder: { app: top.owner, layer: top.layer, window_unverifiable: true } } }));
1655
+ // — except Finder's desktop, which sits below every window and has no id
1656
+ if (!ewid && !desktop) return fail(notDelivered({ code: 'OCCLUDED', message: `the hit test at ${x},${y} was inconclusive and the element's window has no window ID, so the window on top cannot be confirmed to be its own — nothing was sent. Mechanism "semantic" presses the element without the pointer when it has an accessibility action (under "auto" a click comes here only when it has none); otherwise bring its window to the front and take a new snapshot`, details: { occluder: { app: top.owner, layer: top.layer, window_unverifiable: true } } }));
1382
1657
  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 } } }));
1383
1658
  h.reason = (h.reason ? h.reason + '; ' : '') + 'the topmost window there is the app\'s own';
1384
1659
  }
1385
- return { ok: true, point: [x, y], hit: h.verdict, reason: h.reason, pid: r.app.pid, wid: ewid || null, before: observeState(r.el, r.appEl), role: w.v.AXRole, title: nameOf(w.v).slice(0, 60), how: r.how };
1660
+ // An element with no window id of its own (a menu item, a menu bar item, Finder's desktop): which window the
1661
+ // window server has on top at the point now is handed back (null: none), so that the server can tell right
1662
+ // before the click whether it is still that one. It is read on both sides of the hit test — a menu that closes
1663
+ // in between would otherwise leave what came up under it as the window to expect — and it has to be the app's
1664
+ // own (an open menu is), or the window server's for a menu bar item (the menu bar is its window): another app's
1665
+ // window at the point is not what was hit-tested.
1666
+ const topNow = ewid ? null : cgTopAt(x, y);
1667
+ if (!ewid) {
1668
+ if ((topBefore ? topBefore.wid : null) !== (topNow ? topNow.wid : null)) return fail(notDelivered({ code: 'OCCLUDED', message: `what is on top at ${x},${y} changed while the element was being checked (a menu that closed, a window that came up) — take a new snapshot`, details: { kind: 'top_changed' } }));
1669
+ // Finder's desktop is below every window, so a click meant for one of its icons lands on whatever window is at
1670
+ // the point — one of Finder's own included, which reads as "the app's own window" everywhere above
1671
+ if (desktop && topNow) return fail(notDelivered({ code: 'OCCLUDED', message: `a window of "${topNow.owner}" is on top of the desktop at ${x},${y} — move or close it, or use the icon's semantic action (mechanism auto)`, details: { kind: 'desktop_covered', occluder: { app: topNow.owner, layer: topNow.layer } } }));
1672
+ const barItem = w.v.AXRole === 'AXMenuBarItem' || Boolean(req.target && req.target.container && req.target.container.kind === 'menubar');
1673
+ if (topNow && topNow.pid !== r.app.pid && !(barItem && topNow.owner === 'Window Server')) return fail(notDelivered({ code: 'OCCLUDED', message: `a window of "${topNow.owner}" is on top at ${x},${y} — bring the element's app to the front or close what covers it`, details: { occluder: { app: topNow.owner, layer: topNow.layer } } }));
1674
+ }
1675
+ return { ok: true, point: [x, y], hit: h.verdict, reason: h.reason, pid: r.app.pid, wid: ewid || null, ...(ewid ? {} : { top_wid: topNow ? topNow.wid : null }), before: observeState(r.el, r.appEl), role: w.v.AXRole, title: nameOf(w.v).slice(0, 60), how: r.how };
1386
1676
  }
1387
1677
  const ABSENT_CODES = new Set(['STALE_REF', 'WINDOW_NOT_FOUND', 'APP_NOT_FOUND']);
1388
1678
  function resolveOrError(target, budgetMs) {
1389
1679
  let r;
1390
- try { r = resolveTarget(target, budgetMs); }
1680
+ try { r = resolveTarget(target, budgetMs, true); }
1391
1681
  catch (e) { return { error: { code: 'INTERNAL', message: String(e && e.message || e).slice(0, 200) } }; }
1392
1682
  try {
1393
1683
  if (!r.error) {
@@ -1491,13 +1781,13 @@ function opInsertText(req) {
1491
1781
  if (req.replace && !secure && sameText(before, text)) {
1492
1782
  return { ok: true, mechanism: 'semantic', via: 'AXValue', how, role: v.AXRole, app: appName, delivery: 'not_delivered', retry: 'safe', reason: 'already', note: `${label} already shows exactly this text — nothing sent` };
1493
1783
  }
1494
- // R36: appending through AXValue rewrites the whole value; when the value cannot be read, that would
1784
+ // Appending through AXValue rewrites the whole value; when the value cannot be read, that would
1495
1785
  // replace what is there with the text — refuse instead
1496
1786
  if (!req.replace && !canSel && typeof before !== 'string' && !secure) {
1497
1787
  return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${label} takes text only by rewriting its whole value, and its value cannot be read — appending would replace what is there; nothing was sent`, details: { kind: 'value_unreadable' } }));
1498
1788
  }
1499
- // a secure field never shows its value: rewriting it to append is safe only when it is known to be empty (audit
1500
- // S5A-s11-X-2: what was typed there was replaced by the new text)
1789
+ // a secure field never shows its value: rewriting it to append is safe only when it is known to be empty (
1790
+ // what was typed there was replaced by the new text)
1501
1791
  if (!req.replace && !canSel && secure && beforeLen !== 0) {
1502
1792
  return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${label} is a secure field that takes text only by rewriting its whole value, and it is not known to be empty — appending would replace what is there; nothing was sent`, details: { kind: 'value_unreadable', textlike: true } }));
1503
1793
  }
@@ -1544,7 +1834,7 @@ function opInsertText(req) {
1544
1834
  // after an accessibility write the app accepted, how long to look for the value to show it: the answer
1545
1835
  // only decides verified vs unverified (an unchanged value is still reported delivered_unverified)
1546
1836
  const WRITE_POLL_MS = 400;
1547
- // CP (Y6): a text verdict needs the change itself. Texts compare with line endings unified (\r\n and \r
1837
+ // A text verdict needs the change itself. Texts compare with line endings unified (\r\n and \r
1548
1838
  // become \n); set_value also ignores leading and trailing white space. "The value now contains the text
1549
1839
  // somewhere" is never enough — the text may have been there before the write.
1550
1840
  // a finite decimal written out (Number("") is 0 and Number(" ") is 0: those are not numbers here)
@@ -1586,6 +1876,8 @@ function chooseOption(r, want, timeoutMs) {
1586
1876
  const acts = actionNames(r.el);
1587
1877
  const opener = acts.indexOf('AXPress') >= 0 ? 'AXPress' : acts.indexOf('AXShowMenu') >= 0 ? 'AXShowMenu' : null;
1588
1878
  if (!opener) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: 'the control does not open a menu', details: { actions: acts } }));
1879
+ const shownOf = (v) => [v.AXValue, v.AXTitle, nameOf(v)].map(x => String(x === undefined || x === null ? '' : x));
1880
+ const before = shownOf(readNode(r.el));
1589
1881
  const e = perform(r.el, opener);
1590
1882
  if (e !== 0 && e !== -25204) return fail(axCallError(e, opener));
1591
1883
  let menu = null;
@@ -1601,16 +1893,26 @@ function chooseOption(r, want, timeoutMs) {
1601
1893
  if (hit.length !== 1 || !hit[0].enabled) {
1602
1894
  perform(menu, 'AXCancel');
1603
1895
  const why = hit.length > 1 ? `${hit.length} options match "${want}"` : hit.length ? `option "${hit[0].title}" is disabled` : `no option matches "${want}"`;
1604
- 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' });
1896
+ const code = hit.length > 1 ? 'AMBIGUOUS_TARGET' : 'ACTION_FAILED', details = { options: items.slice(0, 40).map(i => i.title) };
1897
+ // The menu was opened for this. It is "closed again" only when it is: one that would not close is still up,
1898
+ // and a retry would press the control under an open menu — that is not "nothing was sent, retry is safe".
1899
+ let up = true;
1900
+ // (this very menu: another menu that is up by then is not it)
1901
+ for (let i = 0; i < 4 && up; i++) { sleep(150); const m = findOpenMenu(r.el, r.appEl); up = Boolean(m && same(m, menu)); }
1902
+ if (up) return fail({ code, message: `${why} — the menu was opened and could not be closed again: it may still be open (mac_key escape closes it)`, details, delivery: 'unknown', retry: 'unsafe' });
1903
+ return fail({ code, message: `${why} (the menu was opened and closed again)`, details, delivery: 'not_delivered', retry: 'safe' });
1605
1904
  }
1606
1905
  const pe = perform(hit[0].el, 'AXPress');
1607
1906
  if (pe !== 0 && pe !== -25204) { perform(menu, 'AXCancel'); return fail(axCallError(pe, 'AXPress on the option')); }
1608
1907
  sleep(300);
1609
1908
  const after = readNode(r.el);
1610
- const shown = [after.AXValue, after.AXTitle, nameOf(after)].map(x => String(x === undefined || x === null ? '' : x));
1611
- const okv = shown.some(s => s === hit[0].title);
1612
- // a changed value that does not show the chosen option is not proof it was chosen
1613
- 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 };
1909
+ const shown = shownOf(after);
1910
+ // a changed value that does not show the chosen option is not proof it was chosen; nor is one the control showed
1911
+ // before, when the option's press did not answer (-25204): nothing says the press took
1912
+ const unanswered = pe === -25204 && before.some(s => s === hit[0].title);
1913
+ const okv = shown.some(s => s === hit[0].title) && !unanswered;
1914
+ 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,
1915
+ ...(unanswered ? { note: 'the option was pressed and did not answer, and the control showed this option before already: it is not known that the press took' } : {}) };
1614
1916
  }
1615
1917
 
1616
1918
  // Role-aware value setting: text, toggles (idempotent), disclosure, selection, menu options, numbers.
@@ -1630,6 +1932,7 @@ function setValueCore(req, r) {
1630
1932
  const timeoutMs = clamp(req.timeout_ms, 0, 30000, 3000);
1631
1933
  const w = waitActionable(r.el, timeoutMs);
1632
1934
  if (w.error) return fail(w.error);
1935
+ { const cw = changedWhileWaited(req.target, r, w); if (cw) return fail(cw); }
1633
1936
  const v = w.v;
1634
1937
  const role = roleKey(v);
1635
1938
  const val = String(req.value === undefined || req.value === null ? '' : req.value);
@@ -1646,7 +1949,7 @@ function setValueCore(req, r) {
1646
1949
  const e = perform(r.el, 'AXPress');
1647
1950
  if (e !== 0) return fail(axCallError(e, 'AXPress'));
1648
1951
  // a control can publish its new state late (or not be readable for a moment): wait for a definite state other
1649
- // than the one before; pressing again while the first press is still on its way would undo it (audit S5A-s11-X-4)
1952
+ // than the one before; pressing again while the first press is still on its way would undo it
1650
1953
  let afterState = cur;
1651
1954
  for (let i = 0; i < 5 && (afterState === cur || afterState === null); i++) { sleep(200); afterState = toggleState(readNode(r.el)); }
1652
1955
  if (afterState === cur || afterState === null) {
@@ -1656,7 +1959,7 @@ function setValueCore(req, r) {
1656
1959
  if (afterState !== want) {
1657
1960
  const e2 = perform(r.el, 'AXPress');
1658
1961
  if (e2 !== 0) return fail({ code: 'NOT_CONFIRMED', message: `pressed once, then second AXPress failed (${axCallError(e2, 'AXPress').message})`, delivery: 'unknown', retry: 'unsafe' });
1659
- // the same wait for the second press (review S5C-G-1: a control slow the first time is slow the second time)
1962
+ // the same wait for the second press (a control slow the first time is slow the second time)
1660
1963
  const mid = afterState;
1661
1964
  for (let i = 0; i < 5 && (afterState === mid || afterState === null); i++) { sleep(200); afterState = toggleState(readNode(r.el)); }
1662
1965
  }
@@ -1779,7 +2082,37 @@ function opScrollPrep(req) {
1779
2082
  const e = perform(r.el, 'AXScrollToVisible');
1780
2083
  if (e !== 0) return fail(axCallError(e, 'AXScrollToVisible'));
1781
2084
  sleep(250);
1782
- return Object.assign(verdict(before, observeState(r.el, r.appEl), { mechanism: 'semantic', action: 'AXScrollToVisible', role: v.AXRole }), { scrolled_into_view: true });
2085
+ // the action returning 0 says the app took it, not that the element can be seen now. What can be seen
2086
+ // of it is its frame cut by its window and by every scroll area above it; a part of that (8 pt each
2087
+ // way, or all of a smaller element) has to be left, on a display
2088
+ const fr = frameOf(readNode(r.el));
2089
+ let clip = fr && fr[2] > 0 && fr[3] > 0 ? fr.slice() : null;
2090
+ const cut = (pf) => {
2091
+ const x = Math.max(clip[0], pf[0]), y = Math.max(clip[1], pf[1]);
2092
+ clip = [x, y, Math.min(clip[0] + clip[2], pf[0] + pf[2]) - x, Math.min(clip[1] + clip[3], pf[1] + pf[3]) - y];
2093
+ };
2094
+ let up = attr(r.el, 'AXParent'), topped = false;
2095
+ for (let d = 0; clip && up && up.el && d < 200; d++) {
2096
+ const pv = readNode(up.el);
2097
+ if (pv.__err) break;
2098
+ const cuts = pv.AXRole === 'AXWindow' || pv.AXRole === 'AXScrollArea';
2099
+ const pf = cuts ? frameOf(pv) : null;
2100
+ if (cuts && !pf) { clip = null; break; } // a window or a scroll area whose frame cannot be read
2101
+ if (pf) cut(pf);
2102
+ if (pv.AXRole === 'AXWindow' || pv.AXRole === 'AXApplication') { topped = true; break; }
2103
+ up = attr(up.el, 'AXParent');
2104
+ }
2105
+ // the way up could not be followed to the top (a parent that did not answer): a scroll area above the
2106
+ // break may cut the element off, so nothing is known to be in view
2107
+ if (clip && !topped) clip = null;
2108
+ const inView = Boolean(clip) && clip[2] >= Math.min(fr[2], 8) && clip[3] >= Math.min(fr[3], 8) && onSomeDisplay(clip[0] + clip[2] / 2, clip[1] + clip[3] / 2);
2109
+ const out = Object.assign(verdict(before, observeState(r.el, r.appEl), { mechanism: 'semantic', action: 'AXScrollToVisible', role: v.AXRole }), { scrolled_into_view: inView });
2110
+ if (!inView) {
2111
+ // it moved, perhaps, but not into view: that is not what was asked for
2112
+ if (out.delivery === 'delivered_verified') out.delivery = 'delivered_unverified';
2113
+ out.note = 'the app accepted AXScrollToVisible, but the element is still outside the visible part of its window or scroll area';
2114
+ }
2115
+ return out;
1783
2116
  }
1784
2117
  const p = opPhysicalPrep(req);
1785
2118
  if (p.ok) p.role = v.AXRole;
@@ -1807,9 +2140,10 @@ function opWait(req) {
1807
2140
  const baseline = cond === 'notification' ? new Set(listNotifications().map(n => n.id)) : null;
1808
2141
  const check = () => {
1809
2142
  if (cond === 'app_running' || cond === 'app_gone') {
1810
- const a = findApp(req.app);
1811
- last = { running: Boolean(a) };
1812
- return cond === 'app_running' ? Boolean(a) : !a;
2143
+ // several running copies under the name: the app is running (app_gone waits until none is left)
2144
+ const n = appCandidates(req.app).length;
2145
+ last = n > 1 ? { running: true, copies: n } : { running: n > 0 };
2146
+ return cond === 'app_running' ? n > 0 : n === 0;
1813
2147
  }
1814
2148
  if (cond === 'notification') {
1815
2149
  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)));
@@ -1831,8 +2165,9 @@ function opWait(req) {
1831
2165
  if (p === 'gone') return false;
1832
2166
  if (p === 'enabled') return v.AXEnabled !== false;
1833
2167
  if (p === 'focused') return v.AXFocused === true;
1834
- if (p === 'value_equals') return String(v.AXValue) === String(req.value);
1835
- if (p === 'value_contains') return String(v.AXValue === undefined ? '' : v.AXValue).toLowerCase().indexOf(String(req.value).toLowerCase()) >= 0;
2168
+ // an element with no value does not have the value "undefined"
2169
+ if (p === 'value_equals') return v.AXValue !== undefined && v.AXValue !== null && String(v.AXValue) === String(req.value);
2170
+ if (p === 'value_contains') return v.AXValue !== undefined && v.AXValue !== null && String(v.AXValue).toLowerCase().indexOf(String(req.value).toLowerCase()) >= 0;
1836
2171
  return false;
1837
2172
  }
1838
2173
  const app = findApp(req.app);
@@ -1843,6 +2178,13 @@ function opWait(req) {
1843
2178
  }
1844
2179
  sawApp = true;
1845
2180
  const appEl = appElement(app);
2181
+ // an app that does not answer, or cannot be read at all, reads as no windows, no sheet and no open
2182
+ // menu: absence is not concluded from that — the wait goes on until the app can be read or the time is up
2183
+ // (the app itself, then its list of windows: no value / no such attribute is an app without windows,
2184
+ // any other error is a list that could not be read)
2185
+ const winErr = () => { const e = attrErr(appEl, 'AXWindows').err; return e === 0 || e === -25212 || e === -25205 ? 0 : e; };
2186
+ const appErr = ABSENCE_APP_CONDS.has(cond) ? (readNode(appEl).__err || (cond === 'menu_closed' ? 0 : winErr())) : 0;
2187
+ if (appErr) { last = appErr === -25204 ? { code: 'APP_UNRESPONSIVE' } : { code: 'AX_ERROR', ax_error: appErr }; return false; }
1846
2188
  if (cond === 'window' || cond === 'window_gone') {
1847
2189
  const titles = windowsOf(appEl).map(w => String(attr(w, 'AXTitle') || ''));
1848
2190
  last = { windows: titles.slice(0, 8) };
@@ -1924,22 +2266,38 @@ function opAppCtl(req) {
1924
2266
  sleep(800); // the request is delivered asynchronously; exiting at once can drop it
1925
2267
  return { ok: true, sent: true, name: a.name, pid: a.pid, method: req.force ? 'force' : 'graceful' };
1926
2268
  }
2269
+ if (action === 'activate') {
2270
+ // this process itself: "pid:<number>" names one of several copies, and `open -a` brings forward whichever of
2271
+ // them macOS picks. The server reads the frontmost app afterwards to say whether it took.
2272
+ let ok = false;
2273
+ try { ok = Boolean(a.ns.activateWithOptions((1 << 0) | (1 << 1))); } catch (e) { ok = false; }
2274
+ if (!ok) return fail(notDelivered({ code: 'ACTION_FAILED', message: `macOS refused to bring ${a.name} (pid ${a.pid}) forward` }));
2275
+ sleep(300);
2276
+ return { ok: true, sent: true, name: a.name, pid: a.pid };
2277
+ }
1927
2278
  if (action === 'hide' || action === 'unhide') {
1928
2279
  // NSRunningApplication's own `hidden` is a cached KVO value that never refreshes here (no run loop);
1929
2280
  // the app's AXHidden attribute is live
1930
2281
  const appEl = appElement(a);
1931
2282
  if (action === 'hide') a.ns.hide; else a.ns.unhide;
1932
2283
  sleep(400);
1933
- const hidden = attr(appEl, 'AXHidden') === true;
1934
- return { ok: true, delivery: hidden === (action === 'hide') ? 'delivered_verified' : 'delivered_unverified', retry: 'safe', name: a.name, pid: a.pid, hidden };
2284
+ // an AXHidden that could not be read verifies nothing: it was taken for "not hidden" — a verified unhide
2285
+ const h = attr(appEl, 'AXHidden');
2286
+ const hidden = h === true ? true : h === false ? false : null;
2287
+ return { ok: true, delivery: hidden !== null && hidden === (action === 'hide') ? 'delivered_verified' : 'delivered_unverified', retry: 'safe', name: a.name, pid: a.pid, hidden };
1935
2288
  }
1936
2289
  return fail(notDelivered({ code: 'INVALID_ARGS', message: `unknown app action "${action}"` }));
1937
2290
  }
1938
2291
  function opAppWait(req) {
1939
2292
  const end = now() + clamp(req.timeout_ms, 0, 60000, 15000);
1940
- let a = null, win = null;
2293
+ let a = null, win = null, several = null;
1941
2294
  while (now() < end) {
1942
- a = findApp(req.app);
2295
+ // while an app is started again its old process can still be listed next to the new one: the one named by
2296
+ // not_pid is left out before the rest is counted (alone, it is what the wait ends with, as before)
2297
+ const all = appCandidates(req.app);
2298
+ const fresh = all.filter(x => !req.not_pid || x.pid !== req.not_pid);
2299
+ several = fresh.length > 1 ? fresh : null;
2300
+ a = fresh.length === 1 ? fresh[0] : !fresh.length && all.length === 1 ? all[0] : null;
1943
2301
  if (a && (!req.not_pid || a.pid !== req.not_pid)) {
1944
2302
  if (!req.want_window) break;
1945
2303
  if ($.AXIsProcessTrusted()) {
@@ -1950,6 +2308,7 @@ function opAppWait(req) {
1950
2308
  sleep(250);
1951
2309
  }
1952
2310
  const front = frontApp();
2311
+ if (!a && several) return fail(ambiguousApp(req.app, several));
1953
2312
  if (!a) return fail({ code: 'TIMEOUT', message: `"${req.app}" did not start in time`, delivery: 'unknown', retry: 'unsafe', details: { kind: 'launch_timeout' } });
1954
2313
  const out = { ok: true, name: a.name, pid: a.pid, bundle_id: a.bundle, frontmost: Boolean(front && front.pid === a.pid) };
1955
2314
  if (win) out.window = { title: win.title, frame: win.frame };
@@ -1974,6 +2333,10 @@ function axWindowFor(req) {
1974
2333
  if (!cg) return { error: notDelivered({ code: 'WINDOW_NOT_FOUND', message: `no window with id ${req.window_id}` }) };
1975
2334
  const app = runningApps().find(x => x.pid === cg.pid);
1976
2335
  if (!app) return { error: notDelivered({ code: 'WINDOW_NOT_FOUND', message: 'the window\'s app is gone' }) };
2336
+ // an app given with the window_id must be the one that owns that window (the window_id used to win unannounced)
2337
+ if (req.app && !appCandidates(req.app).some(x => x.pid === app.pid)) {
2338
+ return { error: notDelivered({ code: 'INVALID_ARGS', message: `window ${Number(req.window_id)} belongs to "${app.name}" (pid ${app.pid}), not to "${String(req.app).slice(0, 80)}" — pass window_id alone, or with the app that owns it` }) };
2339
+ }
1977
2340
  const appEl = appElement(app);
1978
2341
  const ws = windowsOf(appEl);
1979
2342
  const infos = ws.map((w, i) => windowInfo(w, i));
@@ -2026,7 +2389,7 @@ function opWindowOp(req) {
2026
2389
  let err = 0, raiseErr = 0;
2027
2390
  if (action === 'focus' || action === 'raise') {
2028
2391
  // several steps change the window before AXRaise answers, so an AXRaise error is not "nothing
2029
- // sent": the result is decided by the state asked for (R19)
2392
+ // sent": the result is decided by the state asked for
2030
2393
  if (before.minimized) { setAttr(w.el, 'AXMinimized', NO()); sleep(150); }
2031
2394
  raiseErr = perform(w.el, 'AXRaise');
2032
2395
  setAttr(w.el, 'AXMain', YES());
@@ -2060,7 +2423,8 @@ function opWindowOp(req) {
2060
2423
  const fr = after.frame, near = (a, b) => Math.abs(a - b) <= 4;
2061
2424
  const want = {
2062
2425
  focus: () => Boolean(front && front.pid === w.app.pid && (after.focused || after.main)),
2063
- raise: () => after.main === true || changed,
2426
+ // the window on top of its app's windows: main, and not minimized (unminimizing alone is not a raise)
2427
+ raise: () => after.main === true && after.minimized === false,
2064
2428
  minimize: () => after.minimized === true,
2065
2429
  restore: () => after.minimized === false,
2066
2430
  move: () => Boolean(fr) && near(fr[0], Number(req.x)) && near(fr[1], Number(req.y)),
@@ -2196,6 +2560,8 @@ function keyboardLayoutId() {
2196
2560
  function opPaste(req) {
2197
2561
  const text = String(req.text === undefined || req.text === null ? '' : req.text);
2198
2562
  if (!text) return invalid('text required');
2563
+ // without the Accessibility permission the system drops ⌘V: say so before the clipboard is touched
2564
+ if (!$.AXIsProcessTrusted()) return fail(notDelivered(permError()));
2199
2565
  // ⌘V goes to the key that carries V in this layout (0.2.6: key code 9 is K on Dvorak, C on Workman — ⌘C would
2200
2566
  // copy over the text noracu put on the clipboard)
2201
2567
  const vKey = keyCodeForChar('v', KEY_FLAGS.cmd);
@@ -2262,7 +2628,7 @@ function opPaste(req) {
2262
2628
  }
2263
2629
  // ⌘V is the V key itself (vKey, found above) with the ⌘ flag, posted here. cliclick's `kd:cmd t:v ku:cmd`
2264
2630
  // types text, not that key: on macOS 27.2 TextEdit got a plain "v", or nothing, instead of a paste
2265
- // (E2 run 2026-11-07, T7).
2631
+ // (device run 2026-11-07).
2266
2632
  const sent = postKey(vKey, [[MOD_KEYCODES.cmd, KEY_FLAGS.cmd]], 0);
2267
2633
  releaseStuckModifiers(['cmd']);
2268
2634
  if (!sent) {
@@ -2276,7 +2642,7 @@ function opPaste(req) {
2276
2642
  // the clipboard stays ours for at least PASTE_MIN_HOLD_MS even then
2277
2643
  const holdMs = clamp(req.hold_ms, PASTE_MIN_HOLD_MS, 5000, 1000);
2278
2644
  const t0 = now();
2279
- // CP (Y6): evidence is the focused element's value becoming exactly the text pasted over the selection
2645
+ // Evidence is the focused element's value becoming exactly the text pasted over the selection
2280
2646
  // that was there; a change that does not match (or no readable insertion point) keeps waiting and
2281
2647
  // ends delivered_unverified with the reason
2282
2648
  let evidence = false, changed = false;
@@ -2287,7 +2653,7 @@ function opPaste(req) {
2287
2653
  const e = focusEvidence(appEl);
2288
2654
  if (ev0 && e && same(e.el, ev0.el) && e.key !== ev0.key) {
2289
2655
  changed = true;
2290
- // R36: the value itself must have changed — pasting over a selection that already held the same
2656
+ // The value itself must have changed — pasting over a selection that already held the same
2291
2657
  // text leaves an identical value, and a moved caret alone is no proof that ⌘V was handled
2292
2658
  if (expectAfter !== null && sameText(e.raw, expectAfter) && !sameText(e.raw, ev0.raw)) { evidence = true; break; }
2293
2659
  }
@@ -2311,7 +2677,7 @@ function opClipboard(req) {
2311
2677
  const out = { ok: true, types: types.slice(0, 20), change_count: Number(pb.changeCount) };
2312
2678
  // a concealed mark on any item (types lists only the first item's) withholds the whole clipboard
2313
2679
  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; }
2314
- // review 0.2.6 #4: Universal Clipboard content lives on the other device until it is read — say where
2680
+ // Universal Clipboard content lives on the other device until it is read — say where
2315
2681
  // it came from (mac_paste refuses it; reading it is what this tool is for)
2316
2682
  if (types.indexOf(PB_REMOTE) >= 0) { out.remote = true; out.note = 'Universal Clipboard content copied on another device: reading it makes macOS fetch it from that device'; }
2317
2683
  const fmt = req.format || 'auto';
@@ -2383,8 +2749,13 @@ function listNotifications() {
2383
2749
  if (!a) return [];
2384
2750
  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 }));
2385
2751
  }
2386
- // Notification Center's history opens from the clock in the menu bar, when accessibility exposes it.
2752
+ // Notification Center's history opens from the clock in the menu bar, when accessibility exposes it. The clock
2753
+ // by its identifier; else an item named exactly "Clock" or "Notification Center". (Any item whose identifier or
2754
+ // name merely contained "clock" was taken, and it could be another extra — a timer, a world clock — that the
2755
+ // click then opened.)
2756
+ const CLOCK_EXTRA_ID = 'com.apple.menuextra.clock';
2387
2757
  function clockExtra() {
2758
+ let named = null;
2388
2759
  for (const b of ['com.apple.controlcenter', 'com.apple.systemuiserver', 'com.apple.notificationcenterui']) {
2389
2760
  const a = runningApps().find(x => x.bundle === b);
2390
2761
  if (!a) continue;
@@ -2392,16 +2763,16 @@ function clockExtra() {
2392
2763
  if (!mb || !mb.el) continue;
2393
2764
  for (const it of children(mb.el)) {
2394
2765
  const v = readNode(it);
2395
- const tag = [v.AXIdentifier, v.AXTitle, v.AXDescription].map(x => String(x || '')).join(' ').toLowerCase();
2396
- if (/clock|notification center/.test(tag)) return it;
2766
+ if (v.AXIdentifier === CLOCK_EXTRA_ID) return it;
2767
+ if (!named && [v.AXTitle, v.AXDescription].some(x => /^(clock|notification cent(er|re))$/i.test(String(x || '').trim()))) named = it;
2397
2768
  }
2398
2769
  }
2399
- return null;
2770
+ return named;
2400
2771
  }
2401
2772
  // True only on positive evidence that Notification Center's panel is already open: the menu-bar clock reads
2402
2773
  // selected / expanded, or a window holds a Notification Center element that is not a banner or alert.
2403
2774
  // Desktop widgets are windows of the same process (macOS 27.2: 180 × 180 AXUnknown windows, verified on a
2404
- // real Mac), so "it has a window" is no evidence (t10 review).
2775
+ // real Mac), so "it has a window" is no evidence.
2405
2776
  function ncCenterOpen(appEl, clock) {
2406
2777
  if (clock && (attr(clock, 'AXSelected') === true || attr(clock, 'AXExpanded') === true)) return true;
2407
2778
  for (const w of windowsOf(appEl)) {
@@ -2471,7 +2842,7 @@ function opNotifications(req) {
2471
2842
  const e = perform(n.el, n.rawActions[idx]);
2472
2843
  if (e !== 0) {
2473
2844
  // only "invalid element" proves it was gone before the action ran; after any other error a missing
2474
- // notification may be this action's own effect, so delivery stays what the error says (t10 review)
2845
+ // notification may be this action's own effect, so delivery stays what the error says
2475
2846
  const goneNow = e !== -25202 && !collectNotifications(appEl).some(x => x.id === n.id);
2476
2847
  close();
2477
2848
  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)` }));
@@ -2541,6 +2912,13 @@ function menuChord(cmdChar, mods, vk) {
2541
2912
  if (m & 1) ms.push('shift');
2542
2913
  return ms.concat(key).join('+');
2543
2914
  }
2915
+ // Whether the keyboard or mouse was used since `t` (a now() value): the HID system's "seconds since the last
2916
+ // input event" is shorter than the time that has passed. An accessibility action posts no input event, so an
2917
+ // event in that time is the person's. false when the system gives no answer.
2918
+ function inputSince(t) {
2919
+ const idle = Number($.CGEventSourceSecondsSinceLastEventType($.kCGEventSourceStateHIDSystemState, 0xFFFFFFFF));
2920
+ return Number.isFinite(idle) && idle >= 0 && idle * 1000 < now() - t;
2921
+ }
2544
2922
  function opMenu(req) {
2545
2923
  if (!$.AXIsProcessTrusted()) return fail(permError());
2546
2924
  const app = findApp(req.app);
@@ -2559,7 +2937,20 @@ function opMenu(req) {
2559
2937
  const itemPath = h.path.join(' > ');
2560
2938
  // the shortcut is read for the chosen item only (not for every item walked)
2561
2939
  const chord = menuChord(attr(h.el, 'AXMenuItemCmdChar'), attr(h.el, 'AXMenuItemCmdModifiers'), attr(h.el, 'AXMenuItemCmdVirtualKey'));
2562
- const isQuit = chord === 'cmd+q' || chord === 'alt+cmd+q' || h.id === 'terminate:' || h.id === 'NSAlternateQuitMenuItem';
2940
+ // Quit is known by its shortcut or its AppKit action; a menu built without either (some toolkits) still
2941
+ // names it: "Quit", "Quit <anything>", "Exit", or "Exit <anything>" in the application menu or the menu
2942
+ // next to it (File) — not "Exit Full Screen" under View
2943
+ const lastTitle = normMenu(h.path[h.path.length - 1]);
2944
+ const quitByTitle = lastTitle === 'quit' || lastTitle === 'exit' || lastTitle.indexOf('quit ') === 0 || (lastTitle.indexOf('exit ') === 0 && h.bar <= 2);
2945
+ const isQuit = chord === 'cmd+q' || chord === 'alt+cmd+q' || h.id === 'terminate:' || h.id === 'NSAlternateQuitMenuItem' || quitByTitle;
2946
+ const guarded = PROTECTED_BUNDLES.has(app.bundle) || (req.protect_pids || []).indexOf(app.pid) >= 0;
2947
+ // Quit lives in the application menu. An item directly in that menu of an app that must not be quit,
2948
+ // with no identifier, cannot be told apart from Quit (a title in another language, a shortcut that was
2949
+ // changed): it is not pressed. Items of other menus and of submenus are not judged this way — many of
2950
+ // them have no identifier (60 of 262 in an Electron app, 30 of 315 in Finder, read on macOS 27.2).
2951
+ if (guarded && !isQuit && !h.id && h.bar === 1 && h.path.length === 2) {
2952
+ return fail(notDelivered({ code: 'POLICY_DENIED', message: `"${itemPath}" in ${app.name}: this item has no identifier, so it cannot be told apart from Quit, and ${app.name} must not be quit from here — nothing was sent`, details: { kind: 'menu_item_unidentified' } }));
2953
+ }
2563
2954
  if (isQuit && PROTECTED_BUNDLES.has(app.bundle)) {
2564
2955
  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` }));
2565
2956
  }
@@ -2581,6 +2972,7 @@ function opMenu(req) {
2581
2972
  const before = observeState(null, appEl);
2582
2973
  const focusEl = attr(appEl, 'AXFocusedUIElement');
2583
2974
  const fBefore = focusEl && focusEl.el ? observeState(focusEl.el, appEl) : null;
2975
+ const pressedAt = now();
2584
2976
  const e = perform(h.el, 'AXPress');
2585
2977
  if (e !== 0 && e !== -25204) return fail(axCallError(e, 'AXPress'));
2586
2978
  sleep(clamp(req.settle_ms, 0, 3000, 300));
@@ -2589,7 +2981,10 @@ function opMenu(req) {
2589
2981
  if (fBefore && v.delivery === 'delivered_unverified') {
2590
2982
  const fAfter = observeState(focusEl.el, appEl);
2591
2983
  const d = diffState(fBefore, fAfter);
2592
- if (d.verified) { v.delivery = 'delivered_verified'; v.changed = d.changed; }
2984
+ // …unless the keyboard or mouse was used since the item was pressed: the change may be the person's own
2985
+ // (a selection they moved), so it is not counted as the command's
2986
+ if (d.verified && inputSince(pressedAt)) v.note = 'the focused element changed, but the keyboard or mouse was used meanwhile, so the change is not counted as the command\'s effect';
2987
+ else if (d.verified) { v.delivery = 'delivered_verified'; v.changed = d.changed; }
2593
2988
  }
2594
2989
  if (!h.enabled && v.delivery !== 'delivered_verified') v.note = 'the item reported disabled (menus refresh that state lazily) and nothing observable changed';
2595
2990
  if (e === -25204) { v.delivery = 'unknown'; v.note = 'the app did not answer in time (a modal menu or dialog may be open)'; }
@@ -2624,6 +3019,8 @@ function keyCodeForChar(ch, flags) {
2624
3019
  }
2625
3020
  const FLAG_NUMPAD = 0x200000;
2626
3021
  const HELD_MASK = KEY_FLAGS.cmd | KEY_FLAGS.shift | KEY_FLAGS.alt | KEY_FLAGS.ctrl;
3022
+ // the left / right device bits that travel with each modifier's flag (IOLLEvent.h, NX_DEVICE…KEYMASK)
3023
+ const DEVICE_BITS = { cmd: 0x08 | 0x10, shift: 0x02 | 0x04, alt: 0x20 | 0x40, ctrl: 0x01 | 0x2000 };
2627
3024
  const EV_FLAGS_CHANGED = 12;
2628
3025
  function postKey(code, modKeys, extra) {
2629
3026
  const src = $.CGEventSourceCreate($.kCGEventSourceStateHIDSystemState);
@@ -2659,17 +3056,22 @@ function postKey(code, modKeys, extra) {
2659
3056
  // Returns the names still held after that (normally none).
2660
3057
  function releaseStuckModifiers(names) {
2661
3058
  const mask = names.reduce((a, m) => a | KEY_FLAGS[m], 0) & HELD_MASK;
2662
- const now = () => Number($.CGEventSourceFlagsState($.kCGEventSourceStateHIDSystemState)) & mask;
2663
- if (!mask || !now()) return [];
3059
+ const all = () => Number($.CGEventSourceFlagsState($.kCGEventSourceStateHIDSystemState));
3060
+ let flags = all();
3061
+ if (!mask || !(flags & mask)) return [];
2664
3062
  const src = $.CGEventSourceCreate($.kCGEventSourceStateHIDSystemState);
3063
+ // a release goes only to a modifier whose own bit is still set, and the event carries every other flag
3064
+ // as it is (a key the person is holding, Caps Lock): flags 0 would tell apps those were let go as well
2665
3065
  for (const m of names) {
2666
- if (!MOD_KEYCODES[m]) continue;
3066
+ if (!MOD_KEYCODES[m] || !(flags & KEY_FLAGS[m])) continue;
2667
3067
  const e = $.CGEventCreateKeyboardEvent(src, MOD_KEYCODES[m], false);
2668
3068
  if (!e) continue;
2669
- $.CGEventSetType(e, EV_FLAGS_CHANGED); $.CGEventSetFlags(e, 0); $.CGEventPost($.kCGHIDEventTap, e);
3069
+ // its device bits go with it; >>> 0 keeps the value unsigned
3070
+ flags = (flags & ~(KEY_FLAGS[m] | DEVICE_BITS[m])) >>> 0;
3071
+ $.CGEventSetType(e, EV_FLAGS_CHANGED); $.CGEventSetFlags(e, flags); $.CGEventPost($.kCGHIDEventTap, e);
2670
3072
  }
2671
3073
  sleep(30);
2672
- const left = now();
3074
+ const left = all() & mask;
2673
3075
  return names.filter(m => MOD_KEYCODES[m] && (left & KEY_FLAGS[m]));
2674
3076
  }
2675
3077
  function opKey(req) {
@@ -2718,6 +3120,14 @@ const OPS = {
2718
3120
  menu: opMenu, wait: opWait, frontmost: opFrontmost, app_info: opAppInfo, app_ctl: opAppCtl, app_wait: opAppWait, window_op: opWindowOp, clipboard: opClipboard, paste: opPaste, notifications: opNotifications,
2719
3121
  };
2720
3122
 
3123
+ // One op, as run() answers it. An app name that several running apps share ends the op with that answer, wherever
3124
+ // in it the app was looked up (findApp).
3125
+ function dispatch(req) {
3126
+ const fn = OPS[req && req.op];
3127
+ if (!fn) return { ok: false, code: 'INVALID_ARGS', message: `unknown op "${req && req.op}"` };
3128
+ try { return fn(req); } catch (e) { if (e && e.noracu) return fail(e.noracu); throw e; }
3129
+ }
3130
+
2721
3131
  function readStdin() {
2722
3132
  const d = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile;
2723
3133
  return $.NSString.alloc.initWithDataEncoding(d, $.NSUTF8StringEncoding).js;
@@ -2731,5 +3141,5 @@ function run(argv) {
2731
3141
  // the system-wide element's messaging timeout is this process's default for every element whose own
2732
3142
  // timeout is unset (children, parents, hit-test results): a hung app costs at most this per call
2733
3143
  try { $.AXUIElementSetMessagingTimeout($.AXUIElementCreateSystemWide(), AX_MSG_TIMEOUT_S); } catch (e) { /* keep the default */ }
2734
- try { return JSON.stringify(fn(req)); } catch (e) { return JSON.stringify({ ok: false, code: 'INTERNAL', message: String(e).slice(0, 300) }); }
3144
+ try { return JSON.stringify(dispatch(req)); } catch (e) { return JSON.stringify({ ok: false, code: 'INTERNAL', message: String(e).slice(0, 300) }); }
2735
3145
  }