noracu 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,155 @@
1
+ // ios-setup — `noracu ios-setup`: build the on-device runner for one iPhone or simulator (0.3.0, EXPERIMENTAL).
2
+ //
3
+ // An explicit command; nothing runs on install. It uses Apple's own tools on this Mac:
4
+ // xcrun devicectl list devices which device
5
+ // xcodebuild build-for-testing the runner in ios-runner/, into ~/.noracu/ios-runner/<udid>
6
+ // For an iPhone the build is signed for the developer team given with --team, and Xcode may create or
7
+ // update a development provisioning profile in that team (-allowProvisioningUpdates talks to Apple's
8
+ // developer service — the one step of this backend that leaves the Mac, and only when you run this
9
+ // command). A device is registered in the team only with --register-device. A simulator build is not signed.
10
+ import { spawn } from "node:child_process";
11
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { dirname, join } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import * as iosApi from "./ios-xcuitest.js";
16
+
17
+ 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
+ noracu ios-setup --udid <simulator udid>
20
+
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.
23
+
24
+ --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
26
+ --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`;
28
+
29
+ const TEAM_RE = /^[A-Z0-9]{10}$/, PREFIX_RE = /^[A-Za-z0-9][A-Za-z0-9.-]{2,100}$/;
30
+
31
+ export function parseArgs(argv) {
32
+ const o = { team: null, udid: null, prefix: null, register: false, help: false };
33
+ for (let i = 0; i < argv.length; i++) {
34
+ const a = argv[i];
35
+ if (a === "--help" || a === "-h") o.help = true;
36
+ else if (a === "--register-device") o.register = true;
37
+ else if (a === "--team" || a === "--udid" || a === "--bundle-prefix") {
38
+ const v = argv[++i];
39
+ if (v === undefined || v.startsWith("--")) return { error: `${a} needs a value` };
40
+ o[a === "--team" ? "team" : a === "--udid" ? "udid" : "prefix"] = v;
41
+ } else return { error: `unknown argument ${JSON.stringify(a.slice(0, 40))}` };
42
+ }
43
+ if (o.team !== null && !TEAM_RE.test(o.team)) return { error: "--team must be a 10-character team identifier (letters and digits, as shown in your Apple developer account)" };
44
+ if (o.udid !== null && !iosApi.validUdid(o.udid)) return { error: "--udid is not a device identifier" };
45
+ if (o.prefix !== null && !PREFIX_RE.test(o.prefix)) return { error: "--bundle-prefix must look like a bundle identifier prefix (letters, digits, dots, hyphens)" };
46
+ return o;
47
+ }
48
+
49
+ // Every value is an argument of its own: nothing is put into a shell line.
50
+ export function buildArgv({ project = PROJECT, udid, simulated, out, team, prefix, register }) {
51
+ const argv = ["build-for-testing", "-project", project, "-scheme", "NoracuRunner", "-destination", `id=${udid}`, "-derivedDataPath", out];
52
+ if (simulated) argv.push("CODE_SIGNING_ALLOWED=NO");
53
+ else argv.push(`DEVELOPMENT_TEAM=${team}`, `NORACU_BUNDLE_PREFIX=${prefix}`, "-allowProvisioningUpdates", ...(register ? ["-allowProvisioningDeviceRegistration"] : []));
54
+ return argv;
55
+ }
56
+
57
+ // What a failed build most likely means, from xcodebuild's own words.
58
+ export function explain(output, team = "your team") {
59
+ const t = String(output || "");
60
+ if (/Program License Agreement|PLA Update available|agree to the latest/i.test(t)) return "Apple asks the account holder of the team to accept an updated agreement: sign in at developer.apple.com/account, accept it, then run this again.";
61
+ if (/cannot be registered to your development team|Failed to register bundle identifier|app identifier .{0,80}not available/i.test(t)) return "the runner's bundle identifier is taken by another team: pass --bundle-prefix with a prefix of your own.";
62
+ if (/isn.t registered|is not registered|doesn.t include the currently selected device|Device .{0,80}isn.t included/i.test(t)) return `this iPhone is not registered in ${team}: run again with --register-device (it adds the device to the team), or register it at developer.apple.com.`;
63
+ if (/No Account for Team|No profiles for|requires a development team|no signing certificate|Signing for .{0,80}requires/i.test(t)) return `Xcode has no account or certificate for ${team}: open Xcode › Settings › Accounts, sign in, then run this again.`;
64
+ if (/Developer Mode/i.test(t)) return "turn on Developer Mode on the iPhone (Settings › Privacy & Security › Developer Mode), then run this again.";
65
+ if (/device is locked|unlock the device|is locked/i.test(t)) return "unlock the iPhone and run this again.";
66
+ return null;
67
+ }
68
+
69
+ export const BUILD_TIMEOUT_MS = 15 * 60 * 1000;
70
+
71
+ // xcodebuild runs in a process group of its own, so the compilers it starts end with it. On the time limit the
72
+ // group gets SIGTERM, after killGraceMs SIGKILL, and the answer waits for xcodebuild to be gone (at most
73
+ // killGraceMs more). Ctrl-C on this command ends the group too.
74
+ function run(file, argv, spawnImpl, timeoutMs, killGraceMs = 3000, exit = (code) => process.exit(code)) {
75
+ return new Promise((resolve) => {
76
+ let out = "", child, settled = false, timer = null, sigTimer = null, timedOut = false, signalled = false;
77
+ const signal = (sig) => { try { process.kill(-child.pid, sig); } catch { try { child.kill(sig); } catch { /* already gone */ } } };
78
+ // Ctrl-C: the group is told to end and this command exits with 130 once xcodebuild is gone, a second later at the latest
79
+ const interrupted = () => { if (settled) return; exit(130); done({ code: null, out, signalled: true }); };
80
+ const onSignal = () => { if (signalled) return; signalled = true; signal("SIGTERM"); sigTimer = setTimeout(() => { signal("SIGKILL"); interrupted(); }, 1000); sigTimer.unref?.(); };
81
+ const done = (v) => { if (settled) return; settled = true; clearTimeout(timer); clearTimeout(sigTimer); process.removeListener("SIGINT", onSignal); process.removeListener("SIGTERM", onSignal); resolve(v); };
82
+ try { child = spawnImpl(file, argv, { stdio: ["ignore", "pipe", "pipe"], detached: true }); } catch (e) { return done({ code: null, out: String(e && e.message) }); }
83
+ process.once("SIGINT", onSignal); process.once("SIGTERM", onSignal);
84
+ timer = setTimeout(() => {
85
+ timedOut = true;
86
+ signal("SIGTERM");
87
+ timer = setTimeout(() => { signal("SIGKILL"); timer = setTimeout(() => done({ code: null, out, timedOut: true }), killGraceMs); }, killGraceMs);
88
+ }, timeoutMs);
89
+ const add = (d) => { out = (out + String(d)).slice(-200000); };
90
+ child.stdout?.on("data", add); child.stderr?.on("data", add);
91
+ child.on("error", (e) => done({ code: null, out: String(e && e.message) }));
92
+ child.on("close", (code) => (signalled ? interrupted() : done(timedOut ? { code: null, out, timedOut: true } : { code, out })));
93
+ });
94
+ }
95
+
96
+ // → the process exit code
97
+ export async function main(argv, { log = (s) => process.stdout.write(s + "\n"), api = iosApi, spawnImpl = spawn, home = homedir(), env = process.env, buildTimeoutMs = BUILD_TIMEOUT_MS, killGraceMs = 3000, exit = (code) => process.exit(code) } = {}) {
98
+ const o = parseArgs(argv);
99
+ if (o.error) { log(`noracu ios-setup: ${o.error}\n\n${USAGE}`); return 2; }
100
+ if (o.help) { log(USAGE); return 0; }
101
+ const list = await api.listDevices();
102
+ if (!list.ok) { log(`noracu ios-setup: could not list devices (${list.message}) — is Xcode installed?`); return 1; }
103
+ let device;
104
+ if (o.udid) {
105
+ device = list.devices.find((d) => d.udid.toLowerCase() === o.udid.toLowerCase());
106
+ if (!device) { log("noracu ios-setup: this Mac does not list the device named with --udid"); return 1; }
107
+ } else {
108
+ const phones = list.devices.filter((d) => !d.simulated && d.paired && d.tunnel);
109
+ 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; }
110
+ device = phones[0];
111
+ }
112
+ if (!device.simulated && !o.team) { log(`noracu ios-setup: an iPhone build must be signed — pass --team <TeamID>\n\n${USAGE}`); return 2; }
113
+ const prefix = o.prefix || (o.team ? `dev.noracu.${o.team.toLowerCase()}` : null);
114
+ // the same place the server looks in (NORACU_IOS_RUNNER_DIR, default ~/.noracu/ios-runner)
115
+ const root = join(home, ".noracu"), base = env.NORACU_IOS_RUNNER_DIR || join(root, "ios-runner"), out = join(base, device.udid);
116
+ for (const d of env.NORACU_IOS_RUNNER_DIR ? [base, out] : [root, base, out]) { mkdirSync(d, { recursive: true, mode: 0o700 }); try { chmodSync(d, 0o700); } catch { /* not ours to change */ } }
117
+ // A build for another bundle prefix in the same folder leaves products the next build can keep: the runner it names
118
+ // then still carries the old bundle id, and the server starts an old runner (device run 2026-11-13). When the prefix
119
+ // changes — or a folder from before this check holds a build of unknown prefix — the earlier build is removed first.
120
+ const stampPath = join(out, "noracu-setup.json"), want = device.simulated ? "(simulator)" : prefix;
121
+ let prev = null;
122
+ try { prev = JSON.parse(readFileSync(stampPath, "utf8")); } catch { /* none yet */ }
123
+ if (prev ? prev.prefix !== want : existsSync(join(out, "Build"))) {
124
+ rmSync(join(out, "Build"), { recursive: true, force: true });
125
+ try { rmSync(stampPath, { force: true }); } catch { /* gone */ }
126
+ log(`Removed the earlier build in ${out}: it was made ${prev ? `for bundle prefix ${prev.prefix}` : "before this version recorded its bundle prefix"}.`);
127
+ }
128
+ log(`Building the runner for ${device.name || device.udid}${device.simulated ? " (simulator)" : ` (team ${o.team}, bundle prefix ${prefix})`} — this takes a minute or two…`);
129
+ const r = await run(api.XCODEBUILD, buildArgv({ udid: device.udid, simulated: device.simulated, out, team: o.team, prefix, register: o.register }), spawnImpl, buildTimeoutMs, killGraceMs, exit);
130
+ if (r.signalled) return 130; // Ctrl-C: not a failed build
131
+ if (r.timedOut) {
132
+ log(`noracu ios-setup: the build did not finish in ${Math.round(buildTimeoutMs / 60000)} min and was stopped — a signing or keychain prompt may be waiting on this Mac's screen; answer it and run the command again.\n--- last lines of xcodebuild ---\n${r.out.trim().split("\n").slice(-15).join("\n")}`);
133
+ return 1;
134
+ }
135
+ const xctestrun = r.code === 0 ? await api.findXctestrun(out) : null;
136
+ if (!xctestrun) {
137
+ const why = r.code === null ? `xcodebuild could not be run (${r.out.slice(0, 200)}) — is Xcode installed?` : explain(r.out, o.team ? `team ${o.team}` : "your team");
138
+ log(`noracu ios-setup: the build failed${why ? `: ${why}` : "."}\n--- last lines of xcodebuild ---\n${r.out.trim().split("\n").slice(-15).join("\n")}`);
139
+ return 1;
140
+ }
141
+ let unchecked = "";
142
+ if (!device.simulated) {
143
+ // the build must name a runner under this prefix — never report an older runner as built
144
+ const hosts = await (api.xctestrunHostIds || iosApi.xctestrunHostIds)(xctestrun);
145
+ if (!hosts || !hosts.length) unchecked = `\nNot checked: no runner bundle id could be read from ${xctestrun}, so whether it is one under ${prefix} is not known.`;
146
+ const other = (hosts || []).filter((h) => !h.startsWith(`${prefix}.`));
147
+ if (other.length) {
148
+ log(`noracu ios-setup: the build names a runner with another bundle id (${other.join(", ")}), not one under ${prefix} — remove ${join(out, "Build")} and run this again.`);
149
+ return 1;
150
+ }
151
+ }
152
+ try { writeFileSync(stampPath, JSON.stringify({ prefix: want, built: new Date().toISOString() }) + "\n", { mode: 0o600 }); } catch { /* the next build cleans up instead */ }
153
+ 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.`);
154
+ return 0;
155
+ }
@@ -0,0 +1,373 @@
1
+ // ios-xcuitest — Mac side of the experimental XCUITest iPhone backend (0.3.0). src/ios-session.js builds the
2
+ // ios_* tools on it.
3
+ //
4
+ // The phone runs a small UI-test bundle ("runner", ios-runner/) that listens on the device's own
5
+ // CoreDevice tunnel address and executes one JSON command per line (docs/ios-runner-protocol.md).
6
+ // This module finds the device, starts the runner through xcodebuild, and talks to it.
7
+ //
8
+ // What it keeps to:
9
+ // • No internet. xcodebuild and devicectl are local tools; the socket goes to a paired device over
10
+ // Apple's tunnel, or to 127.0.0.1 for a simulator.
11
+ // • Every subprocess gets its arguments as an argv array — nothing is put into a shell line.
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).
14
+ // • Every runner call has a hard time limit. A call that timed out, or whose connection broke after
15
+ // the request left, is reported as such — "delivery unknown" for input commands — and never
16
+ // re-sent. The connection is dropped so a late answer cannot be taken for the next call's.
17
+ // • Launching an app and reading the lock state go through devicectl, not the runner: on a real
18
+ // iPhone XCUIApplication.activate() was seen to wait 33–60 s for an app to settle (probe 2026-11-10).
19
+
20
+ import { execFile, spawn } from "node:child_process";
21
+ import { createHash, randomBytes, randomInt } from "node:crypto";
22
+ import { readFileSync, readdirSync } from "node:fs";
23
+ import { mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises";
24
+ import net from "node:net";
25
+ import { tmpdir } from "node:os";
26
+ import { dirname, join } from "node:path";
27
+ import { fileURLToPath } from "node:url";
28
+
29
+ export const PROTOCOL_VERSION = 1;
30
+ export const MAX_ANSWER_BYTES = 16 * 1024 * 1024; // a screenshot answer is the largest line
31
+ export const MAX_REQUEST_BYTES = 64 * 1024; // the runner closes the connection on a longer line
32
+ export const INPUT_OPS = new Set(["tap", "press", "drag", "type", "keys", "home"]);
33
+ // The runner's one long test. The method must not be called testRun: XCTest has a property of that name,
34
+ // and a test with that name "passes" in a few milliseconds without its body ever running (seen 2026-11-10).
35
+ export const RUNNER_TEST_ID = "NoracuRunnerUITests/NoracuRunner/testServe";
36
+ // refusals the protocol defines as "checked before anything is sent"
37
+ const NOTHING_SENT = new Set(["auth", "invalid_args", "app_not_running", "app_not_foreground", "no_keyboard", "unknown_op"]);
38
+
39
+ const UDID_RE = /^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{16}$|^[0-9A-Fa-f]{8}(-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$|^[0-9A-Fa-f]{40}$/;
40
+ const BUNDLE_RE = /^[A-Za-z0-9][A-Za-z0-9.-]{0,154}$/;
41
+ const TOKEN_RE = /^[0-9a-f]{32}$/;
42
+ export const validUdid = (s) => typeof s === "string" && UDID_RE.test(s);
43
+ export const validBundleId = (s) => typeof s === "string" && BUNDLE_RE.test(s);
44
+
45
+ // Apple's tools, by absolute path. The two variables exist for the test suite (a fake xcrun and a fake
46
+ // xcodebuild), like NORACU_AX_ENGINE for the Mac layer.
47
+ export const XCRUN = process.env.NORACU_IOS_XCRUN || "/usr/bin/xcrun";
48
+ export const XCODEBUILD = process.env.NORACU_IOS_XCODEBUILD || "/usr/bin/xcodebuild";
49
+ // A simulator's identifier is a UUID; an iPhone's is 8-16 hex (or 40 hex on old hardware).
50
+ export const isSimulatorUdid = (s) => typeof s === "string" && /^[0-9A-Fa-f]{8}(-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$/.test(s);
51
+
52
+ const oneLine = (s, n = 300) => String(s ?? "").replace(/\s+/g, " ").trim().slice(0, n);
53
+
54
+ // ---------- subprocesses ----------
55
+
56
+ const pending = new Set(); // the devicectl / simctl calls still running
57
+
58
+ // run(file, argv, { timeoutMs, env }) → { code, stdout, stderr, timedOut }. Injectable for tests.
59
+ export function defaultRun(file, argv, { timeoutMs = 30000, env } = {}) {
60
+ return new Promise((resolve) => {
61
+ const c = execFile(file, argv, { timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 4 * 1024 * 1024, env }, (err, stdout, stderr) => {
62
+ pending.delete(c);
63
+ resolve({ code: err ? (typeof err.code === "number" ? err.code : null) : 0, stdout: String(stdout || ""), stderr: String(stderr || ""), timedOut: !!(err && err.killed) });
64
+ });
65
+ pending.add(c);
66
+ });
67
+ }
68
+
69
+ // the devicectl / simctl calls still running: ended when the server goes away
70
+ export function killPending() { for (const c of pending) { try { c.kill("SIGKILL"); } catch { /* already gone */ } } pending.clear(); }
71
+
72
+ // One devicectl call. Returns { ok: true, result } or { ok: false, error, message }.
73
+ export async function devicectl(args, { run = defaultRun, timeoutMs = 30000 } = {}) {
74
+ let dir;
75
+ try {
76
+ dir = await mkdtemp(join(tmpdir(), "noracu-dc-")); // 0700, ours alone
77
+ const out = join(dir, "out.json");
78
+ const r = await run(XCRUN, ["devicectl", ...args, "--quiet", "--json-output", out], { timeoutMs });
79
+ if (r.timedOut) return { ok: false, error: "devicectl_timeout", message: `devicectl ${args.slice(0, 3).join(" ")} gave no answer in ${timeoutMs} ms` };
80
+ let doc = null;
81
+ try { doc = JSON.parse(await readFile(out, "utf8")); } catch { /* no file or not JSON: reported below */ }
82
+ if (doc && doc.info && doc.info.outcome === "success" && doc.result && typeof doc.result === "object") return { ok: true, result: doc.result };
83
+ const why = doc?.error?.userInfo?.NSLocalizedDescription?.string || doc?.error?.localizedDescription || r.stderr || r.stdout || `exit ${r.code}`;
84
+ return { ok: false, error: "devicectl_failed", message: oneLine(why) };
85
+ } catch (e) {
86
+ return { ok: false, error: "devicectl_failed", message: oneLine(e && e.message) };
87
+ } finally {
88
+ if (dir) await rm(dir, { recursive: true, force: true }).catch(() => {});
89
+ }
90
+ }
91
+
92
+ // ---------- devices ----------
93
+
94
+ // One entry of `devicectl list devices` (or the result of `device info details`) → the fields we use.
95
+ export function parseDevice(d) {
96
+ const c = d?.connectionProperties || {}, p = d?.deviceProperties || {}, h = d?.hardwareProperties || {};
97
+ return {
98
+ udid: typeof h.udid === "string" ? h.udid : null,
99
+ name: typeof p.name === "string" ? p.name : null,
100
+ model: h.marketingName ?? null,
101
+ os: p.osVersionNumber ?? null,
102
+ platform: h.platform ?? null,
103
+ simulated: h.reality === "simulated",
104
+ transport: c.transportType ?? null, // wired | localNetwork | sameMachine
105
+ paired: c.pairingState === "paired",
106
+ tunnel: c.tunnelState === "connected",
107
+ tunnelIP: typeof c.tunnelIPAddress === "string" ? c.tunnelIPAddress : null,
108
+ developerMode: p.developerModeStatus === "enabled",
109
+ booted: p.bootState === "booted",
110
+ };
111
+ }
112
+
113
+ export async function listDevices(opts = {}) {
114
+ const r = await devicectl(["list", "devices"], opts);
115
+ if (!r.ok) return r;
116
+ const devices = (Array.isArray(r.result.devices) ? r.result.devices : []).map(parseDevice).filter((d) => d.platform === "iOS" && d.udid);
117
+ return { ok: true, devices };
118
+ }
119
+
120
+ export async function deviceDetails(udid, opts = {}) {
121
+ if (!validUdid(udid)) return { ok: false, error: "invalid_args", message: "udid is not a device identifier" };
122
+ const r = await devicectl(["device", "info", "details", "--device", udid], opts);
123
+ return r.ok ? { ok: true, device: parseDevice(r.result) } : r;
124
+ }
125
+
126
+ // Which address the runner must listen on, or why the device cannot be used yet.
127
+ export function bindAddressFor(device) {
128
+ if (!device || !device.udid) return { ok: false, error: "device_not_found", message: "no such device" };
129
+ if (device.simulated) return device.booted ? { ok: true, bind: "127.0.0.1" } : { ok: false, error: "device_not_ready", message: "the simulator is not booted" };
130
+ if (!device.paired) return { ok: false, error: "device_not_ready", message: "the iPhone is not paired with this Mac" };
131
+ if (!device.developerMode) return { ok: false, error: "device_not_ready", message: "Developer Mode is off on the iPhone" };
132
+ if (!device.tunnel || !device.tunnelIP) return { ok: false, error: "device_not_ready", message: "no CoreDevice tunnel to the iPhone (unlock it and check the cable or network)" };
133
+ if (!net.isIPv6(device.tunnelIP)) return { ok: false, error: "device_not_ready", message: "the tunnel address is not an IPv6 address" };
134
+ // the CoreDevice tunnel's address is unique-local (fc00::/7); anything else would listen beyond it (review S4A-s7-grok-3)
135
+ if (device.tunnelIP !== "::1" && !/^f[cd][0-9a-f]{0,2}:/i.test(device.tunnelIP)) return { ok: false, error: "device_not_ready", message: "the tunnel address is not a unique-local (fc00::/7) address" };
136
+ return { ok: true, bind: device.tunnelIP };
137
+ }
138
+
139
+ // { ok, locked } — locked means the phone asks for its passcode; input must be refused then.
140
+ export async function lockState(udid, opts = {}) {
141
+ if (!validUdid(udid)) return { ok: false, error: "invalid_args", message: "udid is not a device identifier" };
142
+ const r = await devicectl(["device", "info", "lockState", "--device", udid], opts);
143
+ if (!r.ok) return r;
144
+ if (typeof r.result.passcodeRequired !== "boolean") return { ok: false, error: "devicectl_failed", message: "lockState answer has no passcodeRequired" };
145
+ return { ok: true, locked: r.result.passcodeRequired, unlockedSinceBoot: r.result.unlockedSinceBoot === true };
146
+ }
147
+
148
+ // Bring an app to the front (starting it if needed). Never terminates a running instance unless asked.
149
+ export async function launchApp(udid, bundleId, { terminateExisting = false, ...opts } = {}) {
150
+ if (!validUdid(udid)) return { ok: false, error: "invalid_args", message: "udid is not a device identifier" };
151
+ if (!validBundleId(bundleId)) return { ok: false, error: "invalid_args", message: "bundle_id is not a bundle identifier" };
152
+ const r = await devicectl(["device", "process", "launch", "--device", udid, ...(terminateExisting ? ["--terminate-existing"] : []), bundleId], opts);
153
+ if (!r.ok) return r;
154
+ return { ok: true, pid: r.result.process?.processIdentifier ?? null, activated: r.result.launchOptions?.activatedWhenStarted === true }; // never assumed (review S4A-s7-A-1)
155
+ }
156
+
157
+ // The same for a simulator, which devicectl does not launch apps on: simctl, by exit code.
158
+ export async function simLaunch(udid, bundleId, { terminateExisting = false, run = defaultRun, timeoutMs = 30000 } = {}) {
159
+ if (!isSimulatorUdid(udid)) return { ok: false, error: "invalid_args", message: "udid is not a simulator identifier" };
160
+ if (!validBundleId(bundleId)) return { ok: false, error: "invalid_args", message: "bundle_id is not a bundle identifier" };
161
+ const r = await run(XCRUN, ["simctl", "launch", ...(terminateExisting ? ["--terminate-running-process"] : []), udid, bundleId], { timeoutMs });
162
+ if (r.timedOut) return { ok: false, error: "simctl_timeout", message: `simctl launch gave no answer in ${timeoutMs} ms` };
163
+ if (r.code !== 0) return { ok: false, error: "simctl_failed", message: oneLine(r.stderr || r.stdout || `exit ${r.code}`) };
164
+ return { ok: true, pid: Number(/:\s*(\d+)\s*$/.exec(r.stdout.trim())?.[1]) || null, activated: null }; // simctl's exit 0 says the command ran, not that the app came to the front
165
+ }
166
+
167
+ // The runner build `noracu ios-setup` left for one device: <dir>/Build/Products/*.xctestrun (the newest).
168
+ // The runner bundle ids an .xctestrun names (TestHostBundleIdentifier, an XML plist as xcodebuild writes it) —
169
+ // [] when it names none that can be read this way, null when the file cannot be read.
170
+ export async function xctestrunHostIds(path) {
171
+ try {
172
+ const t = await readFile(path, "utf8");
173
+ return [...t.matchAll(/<key>TestHostBundleIdentifier<\/key>\s*<string>([^<]*)<\/string>/g)].map((m) => m[1]);
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
178
+
179
+ export async function findXctestrun(dir) {
180
+ try {
181
+ const products = join(dir, "Build", "Products");
182
+ const names = (await readdir(products)).filter((n) => n.endsWith(".xctestrun"));
183
+ let best = null;
184
+ for (const n of names) {
185
+ const st = await stat(join(products, n));
186
+ if (st.isFile() && (!best || st.mtimeMs > best.mtimeMs)) best = { path: join(products, n), mtimeMs: st.mtimeMs };
187
+ }
188
+ return best ? best.path : null;
189
+ } catch {
190
+ return null;
191
+ }
192
+ }
193
+
194
+ // ---------- runner start-up ----------
195
+
196
+ export const newToken = () => randomBytes(16).toString("hex");
197
+ export const pickPort = () => randomInt(49152, 65536);
198
+
199
+ export function runnerEnv({ token, bind, port }) {
200
+ if (!TOKEN_RE.test(String(token))) throw new Error("token must be 32 lowercase hex characters");
201
+ if (!net.isIP(String(bind))) throw new Error("bind must be an IP literal");
202
+ if (!Number.isInteger(port) || port < 49152 || port > 65535) throw new Error("port must be 49152-65535");
203
+ return { TEST_RUNNER_NORACU_TOKEN: token, TEST_RUNNER_NORACU_BIND: bind, TEST_RUNNER_NORACU_PORT: String(port) };
204
+ }
205
+
206
+ export function xcodebuildArgv({ xctestrun, udid }) {
207
+ if (typeof xctestrun !== "string" || !xctestrun.startsWith("/") || !xctestrun.endsWith(".xctestrun")) throw new Error("xctestrun must be an absolute path to an .xctestrun file");
208
+ if (!validUdid(udid)) throw new Error("udid is not a device identifier");
209
+ return ["test-without-building", "-xctestrun", xctestrun, "-destination", `id=${udid}`, `-only-testing:${RUNNER_TEST_ID}`];
210
+ }
211
+
212
+ const READY_RE = /^NORACU_RUNNER ready v=(\d+) port=(\d+)(?: build=(\S{1,64}))?[ \t]*\r?\n/m; // the whole line, so a half-received port is never read
213
+
214
+ // ---- what the runner was built from ----
215
+ // The build on the phone outlives a noracu upgrade, and the first start after a rebuild has been seen running the
216
+ // previous build (simulator, 2026-11-11). So the runner names its build on the ready line — a hash of its own
217
+ // sources, written into NoracuRunner.swift by scripts/gen-runner-build.mjs — and a runner that names another one
218
+ // is not used.
219
+ export const RUNNER_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "ios-runner");
220
+ const BUILD_LINE_RE = /^let noracuRunnerBuild = "([0-9a-f]*)"$/m;
221
+ // the hash of the runner's sources (every Swift file and the project file), the build line itself left out
222
+ export function runnerSourceHash(dir = RUNNER_DIR) {
223
+ const swift = readdirSync(join(dir, "NoracuRunnerUITests")).filter((f) => f.endsWith(".swift")).sort().map((f) => join("NoracuRunnerUITests", f));
224
+ const h = createHash("sha256");
225
+ for (const rel of [join("NoracuRunner.xcodeproj", "project.pbxproj"), ...swift]) {
226
+ h.update(rel.split("\\").join("/") + "\0");
227
+ h.update(readFileSync(join(dir, rel), "utf8").replace(BUILD_LINE_RE, 'let noracuRunnerBuild = ""') + "\0");
228
+ }
229
+ return h.digest("hex").slice(0, 12);
230
+ }
231
+ // What a runner must name to be used: the hash of this copy of its sources. The build line in them must say the
232
+ // same — a change under ios-runner/ without scripts/gen-runner-build.mjs would otherwise build a runner that
233
+ // passes for the one before it (pre-review P4).
234
+ export function expectedRunnerBuild(dir = RUNNER_DIR) {
235
+ let hash;
236
+ try { hash = runnerSourceHash(dir); } catch { return { ok: false, message: "this noracu's runner sources (ios-runner/) could not be read, so a runner cannot be checked against them" }; }
237
+ const named = runnerBuild(dir);
238
+ if (named !== hash) return { ok: false, message: `this noracu's runner sources were changed without their build line: they hash to ${hash}, the line says ${named || "nothing"} — run node scripts/gen-runner-build.mjs, then the iOS set-up again` };
239
+ return { ok: true, build: hash };
240
+ }
241
+ // the build the sources name; null when they cannot be read
242
+ export function runnerBuild(dir = RUNNER_DIR) {
243
+ try { return BUILD_LINE_RE.exec(readFileSync(join(dir, "NoracuRunnerUITests", "NoracuRunner.swift"), "utf8"))?.[1] || null; } catch { return null; }
244
+ }
245
+ const ERROR_RE = /^NORACU_RUNNER error ([a-z_]{1,40})[ \t]*\r?\n/m;
246
+
247
+ // Start the runner and wait for its ready line. Returns
248
+ // { ok: true, client, port, child, stop() } or { ok: false, error, message }.
249
+ // On every failure the xcodebuild process is stopped before returning.
250
+ export function startRunner({ udid, xctestrun, bind, token = newToken(), port = pickPort(), readyTimeoutMs = 120000, spawnImpl = spawn, env = process.env, connectHost, expected = expectedRunnerBuild() } = {}) {
251
+ if (!expected.ok) return Promise.resolve({ ok: false, error: "runner_start_failed", message: expected.message });
252
+ const build = expected.build;
253
+ let argv, extra;
254
+ try { argv = xcodebuildArgv({ xctestrun, udid }); extra = runnerEnv({ token, bind, port }); }
255
+ catch (e) { return Promise.resolve({ ok: false, error: "invalid_args", message: e.message }); }
256
+ return new Promise((resolve) => {
257
+ let child, seen = "", settled = false, timer = null, exited = null;
258
+ // xcodebuild and what it started get a process group of their own (detached), so the whole group is
259
+ // signalled; a child without one (a test's stand-in) is signalled alone
260
+ const signal = (sig) => { if (!child) return; try { process.kill(-child.pid, sig); } catch { try { child.kill(sig); } catch { /* already gone */ } } };
261
+ const kill = () => { signal("SIGTERM"); const k = setTimeout(() => signal("SIGKILL"), 3000); k.unref?.(); };
262
+ const finish = (v) => { if (settled) return; settled = true; clearTimeout(timer); if (!v.ok) kill(); resolve(v.ok || !exited ? v : { ...v, exited }); };
263
+ try { child = spawnImpl(XCODEBUILD, argv, { env: { ...env, ...extra }, stdio: ["ignore", "pipe", "pipe"], detached: true }); }
264
+ catch (e) { return finish({ ok: false, error: "runner_start_failed", message: oneLine(e && e.message) }); }
265
+ exited = new Promise((res) => { child.once?.("exit", res); child.once?.("error", res); });
266
+ const onData = (chunk) => {
267
+ if (settled) return;
268
+ seen = (seen + String(chunk)).slice(-65536);
269
+ const bad = ERROR_RE.exec(seen);
270
+ if (bad) return finish({ ok: false, error: "runner_start_failed", message: `the runner refused to start: ${bad[1]}` });
271
+ const m = READY_RE.exec(seen);
272
+ if (!m) return;
273
+ if (Number(m[1]) !== PROTOCOL_VERSION) return finish({ ok: false, error: "runner_version_mismatch", message: `the runner speaks protocol ${m[1]}, this noracu speaks ${PROTOCOL_VERSION} — run the iOS set-up again` });
274
+ if (Number(m[2]) !== port) return finish({ ok: false, error: "runner_start_failed", message: "the runner reported a different port than it was given" });
275
+ // built from other sources than this noracu's: an old build still on the phone, or the previous one run once more after a rebuild
276
+ if (m[3] !== build) return finish({ ok: false, error: "runner_version_mismatch", stale: true, message: `the runner on the device is ${m[3] ? `build ${m[3]}` : "a build that names no version"}, this noracu's is ${build} — run the iOS set-up again (npx noracu ios-setup), then call again` });
277
+ const client = new RunnerClient({ host: connectHost || bind, port, token });
278
+ finish({ ok: true, client, port, child, exited, stop: () => { client.close(); kill(); } });
279
+ };
280
+ child.stdout?.on("data", onData);
281
+ child.stderr?.on("data", onData);
282
+ child.on("error", (e) => finish({ ok: false, error: "runner_start_failed", message: oneLine(e && e.message) }));
283
+ child.on("exit", (code) => finish({ ok: false, error: "runner_start_failed", message: startFailureText(code, seen) }));
284
+ timer = setTimeout(() => finish({ ok: false, error: "runner_start_timeout", message: `the runner was not ready in ${readyTimeoutMs} ms` }), readyTimeoutMs);
285
+ });
286
+ }
287
+
288
+ // What xcodebuild said when it ended before the runner was ready, in words a person can act on. Right after an iOS
289
+ // update the first start ended with "Timed out while enabling automation mode" and the next one worked (device run
290
+ // 2026-11-14, iPhone 16 Pro, iOS 27.2.1). Otherwise XCTest's own "Underlying Error", else the end of the log.
291
+ export function startFailureText(code, seen) {
292
+ const log = String(seen || "");
293
+ if (/enabling automation mode/i.test(log)) {
294
+ return `xcodebuild ended (exit ${code}): the iPhone did not turn on UI automation in time — this happens after an iOS update or a restart. Unlock the iPhone, check that Settings › Developer › Enable UI Automation is on (enter the passcode if the iPhone asks for it), then call again`;
295
+ }
296
+ const under = /Underlying Error: ([^\n]*?)\)?\s*$/m.exec(log);
297
+ if (under) return `xcodebuild ended (exit ${code}) before the runner was ready: ${oneLine(under[1], 240)}`;
298
+ return `xcodebuild ended (exit ${code}) before the runner was ready: ${oneLine(log.slice(-600), 240)}`;
299
+ }
300
+
301
+ // ---------- the line protocol ----------
302
+
303
+ // One connection to the runner. Calls go one at a time; a second call while one is in flight is refused.
304
+ export class RunnerClient {
305
+ constructor({ host, port, token, connectTimeoutMs = 5000, maxAnswerBytes = MAX_ANSWER_BYTES }) {
306
+ this.host = host; this.port = port; this.token = token;
307
+ this.connectTimeoutMs = connectTimeoutMs; this.maxAnswerBytes = maxAnswerBytes;
308
+ this.sock = null; this.nextId = 1; this.pending = null; this.chunks = []; this.size = 0;
309
+ }
310
+
311
+ close() { const s = this.sock; this.sock = null; this.chunks = []; this.size = 0; if (s) s.destroy(); }
312
+
313
+ _connect() {
314
+ return new Promise((resolve) => {
315
+ const s = net.createConnection({ host: this.host, port: this.port });
316
+ const t = setTimeout(() => { s.destroy(); resolve(false); }, this.connectTimeoutMs);
317
+ s.once("connect", () => { clearTimeout(t); s.setNoDelay(true); this.sock = s; this.chunks = []; this.size = 0; s.on("data", (d) => this._onData(d)); s.on("close", () => this._onClose(s)); resolve(true); });
318
+ s.once("error", () => { clearTimeout(t); resolve(false); });
319
+ s.on("error", () => {}); // later errors arrive as "close"
320
+ });
321
+ }
322
+
323
+ _fail(error, message) { const p = this.pending; this.close(); if (p) p.settle({ ok: false, error, message, delivery: p.sentBytes ? (INPUT_OPS.has(p.op) ? "unknown" : "not_applicable") : "not_delivered" }); }
324
+ _onClose(s) { if (s !== this.sock) return; this._fail("runner_unreachable", "the connection to the runner closed before it answered"); }
325
+
326
+ _onData(d) {
327
+ let from = 0, nl;
328
+ while ((nl = d.indexOf(10, from)) !== -1) {
329
+ this.chunks.push(d.subarray(from, nl));
330
+ const line = Buffer.concat(this.chunks).toString("utf8");
331
+ this.chunks = []; this.size = 0; from = nl + 1;
332
+ this._onLine(line);
333
+ if (!this.sock) return; // the line ended the connection
334
+ }
335
+ if (from < d.length) { this.chunks.push(d.subarray(from)); this.size += d.length - from; }
336
+ if (this.size > this.maxAnswerBytes) this._fail("runner_protocol", "the runner sent a line longer than the limit");
337
+ }
338
+
339
+ _onLine(line) {
340
+ const p = this.pending;
341
+ let msg = null;
342
+ try { msg = JSON.parse(line); } catch { /* handled below */ }
343
+ if (!msg || typeof msg !== "object" || typeof msg.ok !== "boolean") return this._fail("runner_protocol", "the runner sent a line that is not a protocol answer");
344
+ if (!p || (msg.id !== p.id && !(msg.error === "auth" && msg.id === 0))) return this._fail("runner_protocol", "the runner answered a request that is not the current one");
345
+ if (msg.ok) return p.settle({ ok: true, result: msg.result && typeof msg.result === "object" ? msg.result : {} });
346
+ const code = typeof msg.error === "string" && /^[a-z_]{1,40}$/.test(msg.error) ? msg.error : "runner_error";
347
+ const input = INPUT_OPS.has(p.op);
348
+ const delivery = !input ? "not_applicable" : (msg.sent === false || NOTHING_SENT.has(code)) ? "not_delivered" : "unknown";
349
+ if (code === "auth") this.close();
350
+ p.settle({ ok: false, error: code, message: oneLine(msg.message), delivery });
351
+ }
352
+
353
+ // → { ok: true, result } | { ok: false, error, message, delivery: "not_delivered" | "unknown" | "not_applicable" }
354
+ async call(op, args = {}, { timeoutMs = 15000 } = {}) {
355
+ if (this.pending) return { ok: false, error: "runner_busy", message: "another runner call is in flight", delivery: "not_delivered" };
356
+ const id = this.nextId++;
357
+ const line = JSON.stringify({ id, token: this.token, op, args }) + "\n";
358
+ if (Buffer.byteLength(line) > MAX_REQUEST_BYTES) return { ok: false, error: "invalid_args", message: "the request is larger than 64 KiB", delivery: "not_delivered" };
359
+ let settle;
360
+ const done = new Promise((resolve) => { settle = resolve; });
361
+ const p = this.pending = { id, op, sentBytes: 0, settle: (v) => { if (this.pending === p) this.pending = null; clearTimeout(p.timer); settle(v); } };
362
+ p.timer = setTimeout(() => {
363
+ const delivery = p.sentBytes ? (INPUT_OPS.has(op) ? "unknown" : "not_applicable") : "not_delivered";
364
+ this.close(); // a late answer must not be read as the next call's
365
+ p.settle({ ok: false, error: "ios_timeout", message: `the runner did not answer ${op} in ${timeoutMs} ms`, delivery });
366
+ }, timeoutMs);
367
+ if (!this.sock && !(await this._connect())) { if (this.pending === p) p.settle({ ok: false, error: "runner_unreachable", message: "could not connect to the runner", delivery: "not_delivered" }); return done; }
368
+ if (this.pending !== p) return done; // timed out while connecting
369
+ p.sentBytes = Buffer.byteLength(line);
370
+ this.sock.write(line);
371
+ return done;
372
+ }
373
+ }
package/src/mac-ax.js CHANGED
@@ -1135,6 +1135,9 @@ function observeState(el, appEl) {
1135
1135
  const o = { gone: true };
1136
1136
  if (el) {
1137
1137
  const v = readNode(el);
1138
+ // 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)
1140
+ if (v.__err && v.__err !== -25202) o.gone = null;
1138
1141
  if (!v.__err) {
1139
1142
  o.gone = false;
1140
1143
  o.value = v.AXValue === undefined ? null : typeof v.AXValue === 'string' ? vhash(v.AXValue) : v.AXValue;
@@ -1167,7 +1170,9 @@ const WEAK_STATE_KEYS = new Set(['frontmost', 'focusedWindow', 'focus']);
1167
1170
  function diffState(a, b, keys) {
1168
1171
  const changed = STATE_KEYS.filter(k => JSON.stringify(a[k] === undefined ? null : a[k]) !== JSON.stringify(b[k] === undefined ? null : b[k]));
1169
1172
  const allowed = Array.isArray(keys) ? new Set(keys) : null;
1170
- const verified = changed.some(k => !WEAK_STATE_KEYS.has(k) && (!allowed || allowed.has(k)) && !(b.gone === true && k !== 'gone' && b[k] === undefined));
1173
+ // a key not read on either side (the element gone or unreadable there) proves nothing; neither does an unknown gone
1174
+ 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));
1171
1176
  const surfaces = [];
1172
1177
  if ((b.sheets || 0) > (a.sheets || 0)) surfaces.push('sheet');
1173
1178
  if (b.menu && !a.menu) surfaces.push('menu');
@@ -1491,6 +1496,11 @@ function opInsertText(req) {
1491
1496
  if (!req.replace && !canSel && typeof before !== 'string' && !secure) {
1492
1497
  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' } }));
1493
1498
  }
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)
1501
+ if (!req.replace && !canSel && secure && beforeLen !== 0) {
1502
+ 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
+ }
1494
1504
  let err, via;
1495
1505
  if (req.replace) { err = setAttr(el, 'AXValue', $(text)); via = 'AXValue'; }
1496
1506
  else if (canSel) { err = setAttr(el, 'AXSelectedText', $(text)); via = 'AXSelectedText'; }
@@ -1635,13 +1645,20 @@ function setValueCore(req, r) {
1635
1645
  if (acts.indexOf('AXPress') < 0) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: 'the control cannot be pressed', details: { actions: acts } }));
1636
1646
  const e = perform(r.el, 'AXPress');
1637
1647
  if (e !== 0) return fail(axCallError(e, 'AXPress'));
1638
- sleep(200);
1639
- let afterState = toggleState(readNode(r.el));
1648
+ // 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)
1650
+ let afterState = cur;
1651
+ for (let i = 0; i < 5 && (afterState === cur || afterState === null); i++) { sleep(200); afterState = toggleState(readNode(r.el)); }
1652
+ if (afterState === cur || afterState === null) {
1653
+ return fail({ code: 'NOT_CONFIRMED', message: `pressed once, but the control still reads ${toggleLabel(afterState)} after 1 s — not pressed again, which could undo a late first press`, delivery: 'unknown', retry: 'unsafe' });
1654
+ }
1655
+ // a third state (mixed → on, wanted off): one more press moves it on
1640
1656
  if (afterState !== want) {
1641
1657
  const e2 = perform(r.el, 'AXPress');
1642
1658
  if (e2 !== 0) return fail({ code: 'NOT_CONFIRMED', message: `pressed once, then second AXPress failed (${axCallError(e2, 'AXPress').message})`, delivery: 'unknown', retry: 'unsafe' });
1643
- sleep(200);
1644
- afterState = toggleState(readNode(r.el));
1659
+ // the same wait for the second press (review S5C-G-1: a control slow the first time is slow the second time)
1660
+ const mid = afterState;
1661
+ for (let i = 0; i < 5 && (afterState === mid || afterState === null); i++) { sleep(200); afterState = toggleState(readNode(r.el)); }
1645
1662
  }
1646
1663
  if (afterState === want) return done('delivered_verified', { value: want, via: 'AXPress' });
1647
1664
  return fail({ code: 'NOT_CONFIRMED', message: `pressed, but the control still reads ${toggleLabel(afterState)}`, delivery: 'unknown', retry: 'unsafe' });