noracu 0.3.1 → 0.3.3

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/doctor.js CHANGED
@@ -18,6 +18,41 @@ const VERSION = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")).ver
18
18
  // "not found" answer names.
19
19
  export const CLICLICK_PLACES = ["/opt/homebrew/bin/cliclick", "/usr/local/bin/cliclick"];
20
20
  export function defaultCliclick(exists = existsSync) { return CLICLICK_PLACES.find((p) => exists(p)) || CLICLICK_PLACES[0]; }
21
+ // What macOS counts when noracu reads the screen or acts on an app. Claude Desktop starts each local server as a
22
+ // process of its own, through a launcher in Claude.app/Contents/Helpers: what that launcher started (the node of a
23
+ // configuration, or npx, a shell or a version manager's shim in front of it) counts, for itself and for everything it
24
+ // starts in turn, noracu included; an extension counts as Claude Desktop's helper process. Under Cursor, or a
25
+ // terminal running Claude Code, the app counts. execPath: the server's process.execPath; ancestors: the executables
26
+ // of its parent, its parent's parent and on up, as far as they were read (one path is taken as the parent's).
27
+ export function grantTarget(execPath = "", ancestors = []) {
28
+ const chain = (Array.isArray(ancestors) ? ancestors : [ancestors]).map(String);
29
+ const helper = String(execPath).match(/\/Claude\.app\/Contents\/Frameworks\/(Claude Helper[^/]*)\.app\//);
30
+ if (helper) return { kind: "extension", name: `"${helper[1]}"`, why: "the process Claude Desktop runs this extension in; turning on Claude is not enough", reopen: "Claude Desktop" };
31
+ const at = chain.findIndex((p) => /\/Claude\.app\/Contents\/Helpers\//.test(p));
32
+ if (at >= 0) {
33
+ // the launcher's own child: noracu itself, or what stands between them
34
+ const exe = at === 0 ? String(execPath) : chain[at - 1];
35
+ const shown = exe.length > 60 ? `…${exe.slice(-59)}` : exe;
36
+ const program = exe.split("/").pop() || "node";
37
+ return { kind: "node", program, name: `${program} (${shown})`, why: "Claude Desktop starts noracu with it as a process of its own; turning on Claude is not enough", reopen: "Claude Desktop" };
38
+ }
39
+ return { kind: "host", name: "the MCP host app (Claude Desktop, Cursor or the terminal, not node)", why: "", reopen: "the host" };
40
+ }
41
+ // mac_status's hint when a permission is off: off names the permissions ("Accessibility", "Screen Recording"), t is
42
+ // grantTarget's answer
43
+ export function permissionHint(off, t) {
44
+ const what = off.join(" and ");
45
+ return t.kind === "host" ? `the person grants ${what} to the MCP host app (Claude Desktop, Cursor or the terminal — not to node), then quits and reopens the host`
46
+ : `the person turns on ${what} for ${t.name} (${t.why}), then quits and reopens ${t.reopen}`;
47
+ }
48
+ // permission_denied's text after its code when Accessibility is off under Claude Desktop (t: grantTarget's node or
49
+ // extension answer; the host's case keeps the engine's text). The program by name, mac_status for its path and the
50
+ // pane: with the code and the delivery marker it stays within 240 characters (a name over 32 characters is cut).
51
+ export function permissionDenied(t) {
52
+ const name = t.program || t.name;
53
+ const who = name.length > 32 ? `${name.slice(0, 31)}…` : name;
54
+ return `Accessibility is off for ${who} — stop and tell the person to turn it on (mac_status says which and where) and reopen ${t.reopen}; do not retry until then`;
55
+ }
21
56
  const ISSUES = "https://github.com/sgInnora/noracu/issues/new/choose";
22
57
  // the settings the server accepts (server.mjs LAYERS, PHONE_BACKEND); a value it would refuse or replace is not copied
23
58
  // into a configuration
@@ -42,16 +77,18 @@ function stableNodePath() {
42
77
  return real;
43
78
  }
44
79
 
45
- export const HELP = `noracu ${VERSION} — a local MCP server: macOS apps and a browser by element index, plus iPhone (experimental).
80
+ export const HELP = `noracu ${VERSION} — local MCP server: operates Mac apps and a browser, yields to keyboard/mouse, and reports delivery.
81
+ The iPhone layers (Mirroring and XCUITest) are experimental and off by default.
46
82
 
47
83
  It is started by an MCP client (Claude Desktop, Claude Code, Cursor), not by hand: it speaks JSON-RPC on stdin / stdout.
48
84
 
49
85
  noracu the MCP server on stdio (what a client runs)
50
- noracu doctor check this machine and print the client configuration with absolute paths
51
- (also: noracu --doctor); exits 1 when something the server needs is missing
86
+ noracu doctor check this machine and print the client configuration with absolute paths;
87
+ exits 1 when something the server needs is missing
52
88
  noracu doctor --json the same as JSON
53
- noracu ios-setup … build the on-device runner of the XCUITest iPhone backend
89
+ noracu ios-setup … build the runner for the experimental XCUITest backend (see noracu ios-setup --help)
54
90
  noracu --version print the version
91
+ noracu --help print this text
55
92
 
56
93
  Documentation: https://github.com/sgInnora/noracu#readme
57
94
  `;
@@ -98,6 +135,8 @@ export async function collect(env = process.env, sys = {}) {
98
135
  ...(cliclickUse || !needsCliclick ? [] : ["cliclick: not found — brew install cliclick"]),
99
136
  ...(layersOk ? [] : [`NORACU_LAYERS=${JSON.stringify(env.NORACU_LAYERS.slice(0, 40))}: not a comma-separated list of mac, browser, iphone — the server would not start; left out of the configuration`]),
100
137
  ...(backendOk ? [] : [`NORACU_PHONE_BACKEND=${JSON.stringify(env.NORACU_PHONE_BACKEND.slice(0, 20))}: not mirror or xcuitest — left out of the configuration`]),
138
+ // with downloads turned off, a missing Chromium is missing: browser_launch would refuse instead of fetching it
139
+ ...(env.NORACU_DISABLE_AUTO_INSTALL === "1" && layers.includes("browser") && !browser.installed ? ["Chromium: not installed, and NORACU_DISABLE_AUTO_INSTALL=1 keeps browser_launch from downloading it — npx playwright install chromium"] : []),
101
140
  ];
102
141
  // a line for a bug report: versions and what was found, no path and no user name
103
142
  const report = `noracu ${VERSION} · node ${process.version} · ${platform === "darwin" ? `macOS ${macos || "?"}` : platform} ${process.arch} · cliclick ${cliclickUse ? "found" : "missing"} · Chromium ${browser.installed ? "installed" : "not installed"} · layers ${layersSet && layersOk ? env.NORACU_LAYERS.trim() : "mac,browser (default)"}${backendSet && backendOk ? ` · iPhone backend ${env.NORACU_PHONE_BACKEND.trim().toLowerCase()}` : ""}`;
@@ -125,17 +164,26 @@ export function render(d) {
125
164
  d.platform.ok ? "" : d.platform.needed === false ? "NORACU_LAYERS=browser: the browser layer does not need macOS" : "the Mac and iPhone layers need macOS; start the server with NORACU_LAYERS=browser to use the browser layer alone"));
126
165
  out.push(row("cliclick", d.cliclick.found ? d.cliclick.path : `not at ${d.cliclick.path}`,
127
166
  d.cliclick.found ? (d.cliclick.path !== d.cliclick.default ? "not where the server looks by default — the configuration below passes it as NORACU_CLICLICK" : "") : d.cliclick.elsewhere ? (d.cliclick.elsewhere === d.cliclick.default ? `found at ${d.cliclick.elsewhere}, where the server looks by default — the configuration below leaves NORACU_CLICLICK out` : `found at ${d.cliclick.elsewhere} — the configuration below passes it as NORACU_CLICLICK`) : d.cliclick.needed === false ? "not needed: NORACU_LAYERS leaves the Mac layer out" : "physical Mac input needs it (mac_key, mac_drag, physical clicks and typing): brew install cliclick. Reading and semantic actions work without it."));
167
+ const noFetch = d.problems.some((p) => p.startsWith("Chromium:"));
128
168
  out.push(row("browser", d.browser.installed ? "Playwright's Chromium is installed" : "Playwright's Chromium is not installed yet",
129
- d.browser.installed ? "" : d.browser.error ? `playwright could not be loaded: ${d.browser.error}` : "the first browser_launch downloads it (the one download noracu makes); or run: npx playwright install chromium"));
130
- out.push(row("layers", d.layers, d.config.mcpServers.noracu.env?.NORACU_LAYERS ? "set in this shell — the configuration below passes it as NORACU_LAYERS" : d.problems.some((p) => p.startsWith("NORACU_LAYERS")) ? "not valid — the server would not start with it; the configuration below leaves it out" : "NORACU_LAYERS=mac,browser,iphone turns the experimental iPhone layer on"));
169
+ d.browser.installed ? "" : d.browser.error ? `playwright could not be loaded: ${d.browser.error}` : noFetch ? "NORACU_DISABLE_AUTO_INSTALL=1 keeps browser_launch from downloading it: run npx playwright install chromium" : "the first browser_launch downloads it (or run npx playwright install chromium)"));
170
+ out.push(row("layers", d.layers === "mac,browser (default)" ? "mac,browser (default; the iPhone layers are experimental and off by default)" : d.layers, d.config.mcpServers.noracu.env?.NORACU_LAYERS ? "set in this shell — the configuration below passes it as NORACU_LAYERS" : d.problems.some((p) => p.startsWith("NORACU_LAYERS")) ? "not valid — the server would not start with it; the configuration below leaves it out" : ""));
131
171
  out.push(row("server", d.server.path, d.server.in_npx_cache ? "this copy is in npx's cache, which npm may clear: for a client configuration that keeps working, install it in a folder you keep (npm install noracu) and run doctor from there" : ""));
132
- out.push("", "macOS permissions (Accessibility, Screen Recording) are granted to the app that runs noracu — Claude Desktop,",
133
- "Cursor, or your terminal for Claude Code — not to node, and they apply after that app is quit and reopened.",
134
- "This check cannot see them from here: once the client is set up, ask it to call mac_status.", "",
135
- "Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json) and Cursor (~/.cursor/mcp.json):", "",
172
+ // the verdict right under the checks: what is missing, each with the command that fixes it
173
+ const human = (p) => (p.startsWith("cliclick:") ? "cliclick — run brew install cliclick (or set NORACU_CLICLICK)"
174
+ : p.startsWith("Chromium:") ? "Chromium — run npx playwright install chromium (NORACU_DISABLE_AUTO_INSTALL=1 keeps browser_launch from downloading it)"
175
+ : p.startsWith("node:") ? "Node 20 or later"
176
+ : p.startsWith("system:") ? "macOS — the Mac and iPhone layers need it (NORACU_LAYERS=browser runs the browser layer alone)" : p);
177
+ const head = d.problems.every((p) => !p.startsWith("NORACU_")) ? "Missing" : "Missing or not valid";
178
+ out.push("", d.ok ? "Nothing is missing." : d.problems.length === 1 ? `${head}: ${human(d.problems[0])}` : `${head}:\n${d.problems.map((p) => ` - ${human(p)}`).join("\n")}`);
179
+ out.push("", "macOS permissions (Accessibility, Screen & System Audio Recording) go to what macOS sees running noracu:",
180
+ "with Claude Desktop, the node in its configuration (Claude Desktop starts each server as a process of its own);",
181
+ "with Cursor, Cursor; with Claude Code, the terminal. They apply after the client is quit and reopened. This check",
182
+ "cannot see them from here: once the client is set up, ask it to call mac_status.", "",
183
+ "Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json) and Cursor (~/.cursor/mcp.json):",
184
+ "add this entry under \"mcpServers\", then quit and reopen the client.", "",
136
185
  JSON.stringify(d.config, null, 2), "", "Claude Code (for every project of yours; drop `-s user` to add it to the current project only):", "", ` ${d.claude_code}`, "");
137
- out.push(d.ok ? "Nothing is missing." : `Missing or not valid (exit code 1):\n${d.problems.map((p) => ` - ${p}`).join("\n")}`, "",
138
- `Something does not work? Open an issue at ${ISSUES} with the tool, the steps, and this line (it holds no path or user name):`, "", ` ${d.report}`, "");
186
+ out.push(`Something does not work? Open an issue at ${ISSUES} with the tool, the steps, and this line (it holds no path or user name):`, "", ` ${d.report}`, "");
139
187
  return out.join("\n");
140
188
  }
141
189
 
@@ -128,7 +128,8 @@ export function createIosSession({
128
128
  async function resolveDevice() {
129
129
  const want = String(env.NORACU_IOS_UDID || "").trim();
130
130
  if (want && !api.validUdid(want)) return { ok: false, error: "ios_config", message: "NORACU_IOS_UDID is not a device identifier" };
131
- const list = await api.listDevices();
131
+ // a simulator named in NORACU_IOS_UDID is looked up with simctl alone; devicectl answers for iPhones
132
+ const list = await (want && api.isSimulatorUdid(want) ? api.listSimulators() : api.listDevices());
132
133
  if (!list.ok) return list;
133
134
  let d;
134
135
  if (want) {
@@ -176,15 +177,15 @@ export function createIosSession({
176
177
  const d = runner?.device;
177
178
  if (!d || d.simulated || (!force && now() - lockOkAt <= LOCK_FRESH_MS)) return null;
178
179
  const lock = await api.lockState(d.udid);
179
- if (!lock.ok) return { error: "lock_unknown", message: `could not read the iPhone's lock state (${lock.message}) — refused (fail closed)` };
180
- if (lock.locked) return { error: "device_locked", message: "the iPhone is locked — unlock it" };
180
+ if (!lock.ok) return { error: "lock_unknown", message: `could not read the iPhone's lock state (${String(lock.message).slice(0, 80)}), so it counts as locked — stop and tell the person to check the iPhone; do not retry` };
181
+ if (lock.locked) return { error: "device_locked", message: "the iPhone is locked — stop and tell the person to unlock it" };
181
182
  lockOkAt = now();
182
183
  return null;
183
184
  }
184
185
 
185
186
  async function startOnce() {
186
187
  // observation-only mode never starts the runner: a starting runner puts its own app in front of whatever the iPhone shows
187
- if (readOnly) return { ok: false, error: "runner_not_started", message: "NORACU_READ_ONLY=1 does not start the runner: starting it puts the runner's own app in front of whatever the iPhone shows — ios_status still answers; unset NORACU_READ_ONLY to read the screen" };
188
+ if (readOnly) return { ok: false, error: "runner_not_started", message: "NORACU_READ_ONLY=1 does not start the runner, which would put its own app in front of what the iPhone shows — call ios_status, or stop and tell the person" };
188
189
  const g = gen; // read before anything is waited for: a shutdown during any wait below stops this start
189
190
  const shut = { ok: false, error: "runner_start_failed", message: "the session was shut down while the runner was starting" };
190
191
  // two test sessions on one device at once do not work: a runner that was stopped must be gone first
@@ -200,12 +201,12 @@ export function createIosSession({
200
201
  if (!bind.ok) return bind;
201
202
  if (!device.simulated) {
202
203
  const lock = await api.lockState(device.udid);
203
- if (!lock.ok) return { ok: false, error: "lock_unknown", message: `could not read the iPhone's lock state (${lock.message})` };
204
- if (lock.locked) return { ok: false, error: "device_locked", message: "the iPhone is locked — unlock it" };
204
+ if (!lock.ok) return { ok: false, error: "lock_unknown", message: `could not read the iPhone's lock state (${String(lock.message).slice(0, 80)}) — stop and tell the person to check the iPhone; do not retry` };
205
+ if (lock.locked) return { ok: false, error: "device_locked", message: "the iPhone is locked — stop and tell the person to unlock it" };
205
206
  lockOkAt = now();
206
207
  }
207
208
  const xctestrun = await api.findXctestrun(join(dir, device.udid));
208
- if (!xctestrun) return { ok: false, error: "ios_setup_required", message: `no runner build for this device — run: npx noracu ios-setup ${device.simulated ? "" : "--team <TeamID> "}--udid ${device.udid}` };
209
+ if (!xctestrun) return { ok: false, error: "ios_setup_required", message: `no runner build for this device — stop and tell the person to run: npx noracu ios-setup ${device.simulated ? "" : "--team <TeamID> "}--udid ${device.udid}` };
209
210
  if (g !== gen) return shut; // shut down while the device, the lock or the build was looked up: nothing is started
210
211
  const start = () => api.startRunner({ udid: device.udid, xctestrun, bind: bind.bind, spawnImpl, env });
211
212
  let r = await start();
@@ -342,7 +343,7 @@ export function createIosSession({
342
343
  const st = await cur.client.call("app_state", { bundle_id: args.bundle_id }, { timeoutMs: 10000 });
343
344
  if (runner !== cur) return { ok: false, error: "runner_unreachable", message: "the runner stopped", delivery: "not_delivered" };
344
345
  if (!st.ok) return unread(st);
345
- if (st.result?.state === 4) return { ok: false, error: "system_overlay", message: "the iPhone is showing something of its own over the app (Control Center pulled down, or the Home Screen while an app is still coming forward) — nothing was sent; look again with ios_snapshot in a moment, and if it is still there, ios_home closes it but leaves the app for the Home Screen (ios_launch brings the app back)", delivery: "not_delivered" };
346
+ if (st.result?.state === 4) return { ok: false, error: "system_overlay", message: "something of the iPhone's own is over the app (Control Center, for example) — call ios_snapshot in a moment; if it stays, ios_home leaves the app and ios_launch brings the app back", delivery: "not_delivered" };
346
347
  }
347
348
  }
348
349
  // The reads above can take seconds after the queue looked at the stop file and the gate at the lock (SpringBoard
@@ -360,10 +361,11 @@ export function createIosSession({
360
361
  const stop = stopCheck();
361
362
  if (!stop) return null;
362
363
  const m = /^(\w+): ([\s\S]*)$/.exec(stop) || [null, "user_stopped", stop];
363
- return { ok: false, error: m[1], message: m[2].replace(/\s*[—;,]?\s*nothing was sent \((?:fail closed; )?delivery=not_delivered, retry=safe\)/, ""), delivery: "not_delivered" };
364
+ // the refusal's own delivery marker comes off (the input error adds one); an older wording said "nothing was sent" before it
365
+ return { ok: false, error: m[1], message: m[2].replace(/\s*[—;,]?\s*nothing was sent \((?:fail closed; )?delivery=not_delivered, retry=safe\)/, "").replace(/\s*\(delivery=[a-z_]+, retry=(?:safe|unsafe)\)\s*$/, ""), delivery: "not_delivered" };
364
366
  } : undefined;
365
367
  let r = await cur.client.call(op, args, { timeoutMs, beforeSend });
366
- if (homeCovered && !r.ok && r.error === "app_not_foreground") r = { ...r, message: "the Home Screen is not what the iPhone is showing: an app or Spotlight is in front, and under com.apple.springboard only one tap on a button of a system alert is sent there — name the app that is in front (ios_snapshot with its bundle_id), or go to the Home Screen with ios_home", plain: true };
368
+ if (homeCovered && !r.ok && r.error === "app_not_foreground") r = { ...r, message: "the Home Screen is not what the iPhone is showing — an app or Spotlight is in front; name that app (ios_snapshot shows its bundle_id) or call ios_home", plain: true };
367
369
  // An input that got no answer may still be waiting inside the test session: the session ends now, so the
368
370
  // gesture cannot go out later (the protocol always said so). Any failure XCTest recorded ends it
369
371
  // as well, whichever command was answered with it — an input, a read, or the next command after a late one:
@@ -397,7 +399,7 @@ export function createIosSession({
397
399
  app_not_foreground: " — the app is not in front; call ios_launch first",
398
400
  app_not_running: " — the app is not running; call ios_launch first",
399
401
  // device run 2026-11-15: the refusal did not say which prompt was up, so the agent could not tell the person what to answer
400
- system_alert: " — a system prompt is up on the iPhone; the person answers it there (noracu does not send input while one is up); look at it with ios_screenshot to tell them what it asks",
402
+ system_alert: " — a system prompt is up on the iPhone: look at it with ios_screenshot, then stop and tell the person what it asks; only the person answers it",
401
403
  no_keyboard: " — no keyboard is up; tap a text field first (ios_type with element_index does that)",
402
404
  ios_timeout: " — look before acting again (ios_snapshot)",
403
405
  xctest_issue: " — XCTest reported a failure while the command ran; look before acting again (ios_snapshot)",
@@ -413,7 +415,7 @@ export function createIosSession({
413
415
  const sbNever = (bundle) => {
414
416
  if (bundle !== SPRINGBOARD || !springboardDenied()) return null;
415
417
  const denied = approve(bundle, "input");
416
- return { error: denied || `input_denied: input that names com.apple.springboard (the Home Screen) is not sent while app rules are in force (NORACU_APPROVAL_FILE or NORACU_DENY_APPS) — not even one tap on a system prompt's button; open apps with ios_launch, go home with ios_home ${NOT_SENT}` };
418
+ return { error: denied || `input_denied: input that names com.apple.springboard (the Home Screen) is not sent while app rules are on (NORACU_APPROVAL_FILE or NORACU_DENY_APPS) — open apps with ios_launch, go home with ios_home ${NOT_SENT}` };
417
419
  };
418
420
  // system_alert comes with two messages: an alert is up, or SpringBoard could not be read so one could not be ruled
419
421
  // out — only the first is told "a system prompt is up"
@@ -424,7 +426,7 @@ export function createIosSession({
424
426
  const readError = (r) => ({ error: `${r.error}: ${r.message || "the runner refused"}${r.error === "app_not_running" ? HINTS.app_not_running : ""}` });
425
427
  function pickBundle(a, input) {
426
428
  const b = a.bundle_id ?? current;
427
- return b ? { bundle: b } : { error: `bundle_id required: name the app (ios_launch sets it for later calls)${input ? ` ${NOT_SENT}` : ""}` };
429
+ return b ? { bundle: b } : { error: `invalid_args: bundle_id is required — name the app, or call ios_launch first (it sets the app for later calls)${input ? ` ${NOT_SENT}` : ""}` };
428
430
  }
429
431
 
430
432
  // ---------- elements ----------
@@ -610,7 +612,7 @@ export function createIosSession({
610
612
  // only a text input is tapped to take the text: the index of a button or a row would be tapped as what
611
613
  // it is — a real press on it — and the text would then go to whatever holds the keyboard. Before the
612
614
  // gate: nothing is asked for an input that is not going to be sent.
613
- if (!TEXTY.has(it.type) && it.type !== "secureTextField") return { error: `not_a_text_field: element_index ${a.element_index} is a ${it.type}${it.label ? ` (${JSON.stringify(String(it.label).slice(0, 40))})` : ""}, not a text field — nothing was tapped or typed; tap what brings the keyboard up with ios_tap, then call ios_type without element_index (delivery=not_delivered, retry=safe)` };
615
+ if (!TEXTY.has(it.type) && it.type !== "secureTextField") return { error: `not_a_text_field: element_index ${a.element_index} is a ${it.type}${it.label ? ` (${JSON.stringify(String(it.label).slice(0, 40))})` : ""}, not a text field — call ios_tap on what brings the keyboard up, then ios_type without element_index (delivery=not_delivered, retry=safe)` };
614
616
  const g = await gate(it.bundle);
615
617
  if (g) return g;
616
618
  if (it.epoch !== epoch) return stale(a.element_index); // the gate started a runner: what was read is gone
@@ -660,7 +662,7 @@ export function createIosSession({
660
662
  const after = await textFields(bundle);
661
663
  // a failure XCTest recorded once the text had gone out: the "ok" the runner gave for it is in doubt
662
664
  if (heldIssue) return issueAt(takeHeld(), true);
663
- const notConfirmed = { error: `type_not_confirmed: ${n} characters were typed in ${bundle} but ${key ? "the field that was tapped was not" : "no text field was"} seen to gain exactly that text (autocorrection or a field that hides its value can cause this) — read the field (ios_snapshot) before typing again ${UNKNOWN}` };
665
+ const notConfirmed = { error: `type_not_confirmed: ${n} characters were typed in ${bundle}, but ${key ? "the tapped field did not show" : "no text field showed"} exactly that text (autocorrection, or a hidden value) — check with ios_snapshot before typing again ${UNKNOWN}` };
664
666
  // The fields could not be read afterwards (the read failed, or the app has more elements than are read): the
665
667
  // text was not seen to be missing, which type_not_confirmed would say — unverified, and the result names the
666
668
  // side that could not be read
package/src/ios-setup.js CHANGED
@@ -1,7 +1,8 @@
1
1
  // ios-setup — `noracu ios-setup`: build the on-device runner for one iPhone or simulator (0.3.0, EXPERIMENTAL).
2
2
  //
3
3
  // An explicit command; nothing runs on install. It uses Apple's own tools on this Mac:
4
- // xcrun devicectl list devices which device
4
+ // xcrun devicectl list devices which iPhone
5
+ // xcrun simctl list --json which simulator (a simulator's udid is looked up here, not with devicectl)
5
6
  // xcodebuild build-for-testing the runner in ios-runner/, into ~/.noracu/ios-runner/<udid>
6
7
  // For an iPhone the build is signed for the developer team given with --team, and Xcode may create or
7
8
  // update a development provisioning profile in that team (-allowProvisioningUpdates talks to Apple's
@@ -15,16 +16,25 @@ import { fileURLToPath } from "node:url";
15
16
  import * as iosApi from "./ios-xcuitest.js";
16
17
 
17
18
  const PROJECT = join(dirname(fileURLToPath(import.meta.url)), "..", "ios-runner", "NoracuRunner.xcodeproj");
18
- export const USAGE = `usage: noracu ios-setup --team <TeamID> [--udid <udid>] [--bundle-prefix <prefix>] [--register-device]
19
+ export const USAGE = `noracu ios-setup — build the XCUITest runner for the iPhone layer (experimental and off by default)
20
+
21
+ usage: noracu ios-setup --team <TeamID> [--udid <udid>] [--bundle-prefix <prefix>] [--register-device]
19
22
  noracu ios-setup --udid <simulator udid>
20
23
 
21
- Builds noracu's on-device runner (a UI-test bundle, source in ios-runner/) for one device and leaves it in
22
- ~/.noracu/ios-runner/<udid>. Then start the MCP server with NORACU_PHONE_BACKEND=xcuitest.
24
+ Builds noracu's runner (a UI-test bundle, source in ios-runner/) for one iPhone or one booted iOS Simulator and leaves
25
+ it in ~/.noracu/ios-runner/<udid> (NORACU_IOS_RUNNER_DIR names another folder). Requires Xcode; an iPhone also needs
26
+ a developer team, Developer Mode, and to be unlocked.
27
+
28
+ This command does not enable the iPhone layer. To use the runner, start the MCP server with both
29
+ NORACU_LAYERS=mac,browser,iphone and NORACU_PHONE_BACKEND=xcuitest.
23
30
 
24
31
  --team <TeamID> your Apple developer team (10 characters); needed for an iPhone, not for a simulator
25
- --udid <udid> the device; may be left out when exactly one iPhone is connected
32
+ --udid <udid> the iPhone or the booted simulator; may be left out when exactly one iPhone is connected
26
33
  --bundle-prefix <p> bundle identifier prefix for the runner (default: dev.noracu.<teamid>)
27
- --register-device let Xcode register this iPhone in the team if it is not registered yet`;
34
+ --register-device let Xcode register this iPhone in the team if it is not registered yet
35
+ --help print this text
36
+
37
+ More: https://github.com/sgInnora/noracu/blob/main/docs/iphone.md`;
28
38
 
29
39
  const TEAM_RE = /^[A-Z0-9]{10}$/, PREFIX_RE = /^(?=.{3,101}$)[A-Za-z0-9][A-Za-z0-9-]*(?:\.[A-Za-z0-9-]+)*$/; // parts between single dots: none empty
30
40
 
@@ -104,12 +114,14 @@ export async function main(argv, { log = (s) => process.stdout.write(s + "\n"),
104
114
  const o = parseArgs(argv);
105
115
  if (o.error) { log(`noracu ios-setup: ${o.error}\n\n${USAGE}`); return 2; }
106
116
  if (o.help) { log(USAGE); return 0; }
107
- const list = await api.listDevices();
108
- if (!list.ok) { log(`noracu ios-setup: could not list devices (${list.message}) — is Xcode installed?`); return 1; }
117
+ // a simulator's udid is looked up with simctl alone, an iPhone's with devicectl (src/ios-xcuitest.js, listSimulators)
118
+ const sim = o.udid !== null && api.isSimulatorUdid(o.udid);
119
+ const list = await (sim ? api.listSimulators() : api.listDevices());
120
+ if (!list.ok) { log(`noracu ios-setup: could not list ${sim ? "simulators" : "devices"} (${list.message}) — is Xcode installed?`); return 1; }
109
121
  let device;
110
122
  if (o.udid) {
111
123
  device = list.devices.find((d) => d.udid.toLowerCase() === o.udid.toLowerCase());
112
- if (!device) { log("noracu ios-setup: this Mac does not list the device named with --udid"); return 1; }
124
+ if (!device) { log(`noracu ios-setup: this Mac does not list the ${sim ? "simulator" : "device"} named with --udid${sim ? " (xcrun simctl list devices shows the simulators it has)" : ""}`); return 1; }
113
125
  } else {
114
126
  const phones = list.devices.filter((d) => !d.simulated && d.paired && d.tunnel);
115
127
  if (phones.length !== 1) { log(`noracu ios-setup: ${phones.length ? "several iPhones are connected" : "no connected iPhone found"} — name the device with --udid${phones.length ? ": " + phones.map((d) => `${d.udid} (${d.name})`).join(", ") : ""}`); return 1; }
@@ -164,6 +176,6 @@ export async function main(argv, { log = (s) => process.stdout.write(s + "\n"),
164
176
  }
165
177
  }
166
178
  try { writeFileSync(stampPath, JSON.stringify({ prefix: want, built: new Date().toISOString() }) + "\n", { mode: 0o600 }); } catch { /* the next build cleans up instead */ }
167
- log(`Built: ${xctestrun}${unchecked}\nNext: start the MCP server with NORACU_PHONE_BACKEND=xcuitest${o.udid ? ` and NORACU_IOS_UDID=${device.udid}` : ""} in its environment, keep the iPhone unlocked, and call ios_status.`);
179
+ log(`Built: ${xctestrun}${unchecked}\nNext: start the MCP server with NORACU_LAYERS=mac,browser,iphone and NORACU_PHONE_BACKEND=xcuitest${o.udid ? ` and NORACU_IOS_UDID=${device.udid}` : ""} in its environment, keep the iPhone unlocked, and call ios_status.`);
168
180
  return 0;
169
181
  }
@@ -6,11 +6,14 @@
6
6
  // This module finds the device, starts the runner through xcodebuild, and talks to it.
7
7
  //
8
8
  // What it keeps to:
9
- // • No internet. xcodebuild and devicectl are local tools; the socket goes to a paired device over
9
+ // • No internet. xcodebuild, devicectl and simctl are local tools; the socket goes to a paired device over
10
10
  // Apple's tunnel, or to 127.0.0.1 for a simulator.
11
11
  // • Every subprocess gets its arguments as an argv array — nothing is put into a shell line.
12
12
  // • devicectl answers are read from --json-output files, never from terminal text (Apple documents
13
- // the JSON as the stable interface and the terminal output as free to change).
13
+ // the JSON as the stable interface and the terminal output as free to change); the simulator list is
14
+ // simctl's --json output.
15
+ // • iPhones are found with devicectl, simulators with simctl: devicectl does not list simulators with
16
+ // every Xcode (see listSimulators).
14
17
  // • Every runner call has a hard time limit. A call that timed out, or whose connection broke after
15
18
  // the request left, is reported as such — "delivery unknown" for input commands — and never
16
19
  // re-sent. The connection is dropped so a late answer cannot be taken for the next call's.
@@ -121,6 +124,38 @@ export async function listDevices(opts = {}) {
121
124
  return { ok: true, devices };
122
125
  }
123
126
 
127
+ // The iOS simulators `simctl list --json` reports (its devices, runtimes and device types), with the fields
128
+ // parseDevice gives — set as devicectl reports a simulator: paired, on this same Mac, its tunnel up while it is
129
+ // booted, no Developer Mode. One that simctl marks unavailable (its runtime is gone) is left out.
130
+ export function parseSimulators(doc) {
131
+ const runtimes = new Map((Array.isArray(doc?.runtimes) ? doc.runtimes : []).map((r) => [r?.identifier, r]));
132
+ const types = new Map((Array.isArray(doc?.devicetypes) ? doc.devicetypes : []).map((t) => [t?.identifier, t]));
133
+ const out = [];
134
+ for (const [key, list] of Object.entries(doc?.devices && typeof doc.devices === "object" ? doc.devices : {})) {
135
+ const rt = runtimes.get(key), m = /SimRuntime\.iOS-(\d+)-(\d+)(?:-(\d+))?$/.exec(key);
136
+ if ((rt?.platform ?? (m ? "iOS" : null)) !== "iOS" || !Array.isArray(list)) continue;
137
+ const os = typeof rt?.version === "string" ? rt.version : m ? [m[1], m[2], m[3]].filter((x) => x !== undefined).join(".") : null;
138
+ for (const d of list) {
139
+ if (typeof d?.udid !== "string" || d.isAvailable === false) continue;
140
+ const booted = d.state === "Booted";
141
+ out.push({ udid: d.udid, name: typeof d.name === "string" ? d.name : null, model: types.get(d.deviceTypeIdentifier)?.name ?? null, os, platform: "iOS",
142
+ simulated: true, transport: "sameMachine", paired: true, tunnel: booted, tunnelIP: null, developerMode: false, booted });
143
+ }
144
+ }
145
+ return out;
146
+ }
147
+
148
+ // Simulators are looked up with simctl, never with devicectl: devicectl does not list them with every Xcode. With
149
+ // Xcode 26.6 (a macOS 26 CI runner, 2026-11) it listed none, or gave no answer in 30 s; Xcode 27.2 lists them.
150
+ export async function listSimulators({ run = defaultRun, timeoutMs = 30000 } = {}) {
151
+ const r = await run(XCRUN, ["simctl", "list", "--json"], { timeoutMs });
152
+ if (r.timedOut) return { ok: false, error: "simctl_timeout", message: `simctl list gave no answer in ${timeoutMs} ms` };
153
+ let doc = null;
154
+ try { doc = JSON.parse(r.stdout); } catch { /* reported below */ }
155
+ if (r.code !== 0 || !doc || typeof doc !== "object") return { ok: false, error: "simctl_failed", message: oneLine(r.stderr || (r.code === 0 ? "simctl list did not answer in JSON" : `exit ${r.code}`)) };
156
+ return { ok: true, devices: parseSimulators(doc) };
157
+ }
158
+
124
159
  export async function deviceDetails(udid, opts = {}) {
125
160
  if (!validUdid(udid)) return { ok: false, error: "invalid_args", message: "udid is not a device identifier" };
126
161
  const r = await devicectl(["device", "info", "details", "--device", udid], opts);
package/src/mac-ax.js CHANGED
@@ -258,7 +258,7 @@ function appCandidates(spec) {
258
258
  function ambiguousApp(spec, hit) {
259
259
  const front = frontApp();
260
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 } });
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 one of them as "pid:<number>" (mac_apps lists them)`, details: { apps } });
262
262
  }
263
263
  // One app, none (null), or — thrown, and answered by dispatch — the refusal for a name several apps share.
264
264
  function findApp(spec) {
@@ -1579,6 +1579,9 @@ function ncDrawnRects() {
1579
1579
  // what is under them. Notification Center's full-display overlay (shown with a banner or alert) is
1580
1580
  // skipped the same way except over a banner or alert frame (ncDrawnRects), or everywhere when those
1581
1581
  // frames cannot be told.
1582
+ // The pointer: at times the window server draws it as a window of its own ("Cursor", at the cursor level), and then
1583
+ // that window sits on the very point a click goes to. It never takes a click, so it never covers anything.
1584
+ const CURSOR_LAYER = 2147483630; // kCGCursorWindowLevel
1582
1585
  function cgTopAt(x, y) {
1583
1586
  const list = cast($.CGWindowListCopyWindowInfo((1 << 0) | (1 << 4), 0)); // on screen only, no desktop elements
1584
1587
  if (!list) return null;
@@ -1589,6 +1592,7 @@ function cgTopAt(x, y) {
1589
1592
  const layer = Number(g('kCGWindowLayer')), alpha = Number(g('kCGWindowAlpha'));
1590
1593
  const owner = String(g('kCGWindowOwnerName') || '');
1591
1594
  if (!(alpha > 0) || layer < 0) continue;
1595
+ if (owner === 'Window Server' && layer === CURSOR_LAYER) continue;
1592
1596
  const b = d.objectForKey(ks('kCGWindowBounds'));
1593
1597
  if (!b || b.isNil()) continue;
1594
1598
  const [bx, by, bw, bh] = ['X', 'Y', 'Width', 'Height'].map(k => Number(b.objectForKey(ks(k)).js));
@@ -2805,7 +2809,7 @@ function opNotifications(req) {
2805
2809
  if (ncCenterOpen(appEl, clock)) {
2806
2810
  alreadyOpen = true;
2807
2811
  } else {
2808
- if (!clock) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: 'accessibility does not expose the menu-bar clock here, so Notification Center cannot be opened from noracu — open it yourself (click the clock) and list again; banners on screen are listed without it', details: { kind: 'open_center_unavailable' } }));
2812
+ if (!clock) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: 'accessibility does not expose the menu-bar clock here, so Notification Center cannot be opened from noracu — ask the person to open it (click the clock), then list again; banners on screen are listed without it', details: { kind: 'open_center_unavailable' } }));
2809
2813
  if (perform(clock, 'AXPress') === 0) { opened = true; sleep(900); }
2810
2814
  }
2811
2815
  }
@@ -2986,11 +2990,21 @@ function opMenu(req) {
2986
2990
  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
2991
  else if (d.verified) { v.delivery = 'delivered_verified'; v.changed = d.changed; }
2988
2992
  }
2989
- if (!h.enabled && v.delivery !== 'delivered_verified') v.note = 'the item reported disabled (menus refresh that state lazily) and nothing observable changed';
2993
+ const dn = disabledNote(h.enabled, v, app, frontApp());
2994
+ if (dn) v.note = dn;
2990
2995
  if (e === -25204) { v.delivery = 'unknown'; v.note = 'the app did not answer in time (a modal menu or dialog may be open)'; }
2991
2996
  return v;
2992
2997
  }
2993
2998
 
2999
+ // A menu item that read as disabled and was pressed anyway: the note says so only when nothing else was noted and
3000
+ // nothing observable changed; an app in the background may not act on a menu item at all (TextEdit's View > Zoom Out,
3001
+ // 2026-11-25), so for one the note says to bring it forward.
3002
+ function disabledNote(enabled, v, app, front) {
3003
+ if (enabled || v.delivery === 'delivered_verified' || v.note || (v.changed && v.changed.length)) return null;
3004
+ return 'the item reported disabled (menus refresh that state lazily) and nothing observable changed'
3005
+ + (front && front.pid !== app.pid ? ` — ${app.name} is in the background, where a menu item may not act; bring it forward (mac_app, action activate) and check before running the command again` : '');
3006
+ }
3007
+
2994
3008
  // A named key (return, esc, tab, arrows, F-keys…) with optional modifiers, posted to the frontmost app at
2995
3009
  // the HID level from a HID-state event source, the way a hardware keyboard sends it: each modifier pressed
2996
3010
  // (a flags-changed event), the key down and up 20 ms apart, the modifiers released last-first. Chrome's
@@ -0,0 +1,3 @@
1
+ // Start file of the Claude Desktop extension (.mcpb): Claude Desktop's installer turned down src/server.mjs as the
2
+ // entry point ("requires a resolvable entry point") and takes this .js file, which only loads the server.
3
+ import "./server.mjs";