noracu 0.2.6 → 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,650 @@
1
+ // ios-session — the ios_* tools of the experimental XCUITest iPhone backend (0.3.0).
2
+ //
3
+ // One session per server: it picks the device, starts the on-device runner on the first call that needs
4
+ // it (src/ios-xcuitest.js), and turns runner answers into tool results. What it keeps to:
5
+ // • An input is sent only after: the app rule (deny list / approval file, judged on the iOS bundle id),
6
+ // a running runner, and a lock check through devicectl — a phone that asks for its passcode, or whose
7
+ // lock state cannot be read, gets nothing.
8
+ // • element_index is unique across snapshots and lasts 30 s. Before it is used the app is read again:
9
+ // the element must still be there with the same type, label, identifier and frame, and the app must
10
+ // still be in front — otherwise element_no_longer_valid and nothing is sent. ios_home and ios_launch
11
+ // change what is in front, so they end every earlier index.
12
+ // • Nothing is re-sent. A runner call that timed out is reported with delivery=unknown; the next call
13
+ // first asks the runner for a sign of life and restarts it when there is none.
14
+ // • ios_type reports delivered_verified only when the one field that took the text shows it afterwards
15
+ // (four characters or more; the same text in some other field proves nothing).
16
+ // • Results never contain the typed text. Screenshots are returned, never written to disk.
17
+
18
+ import { homedir } from "node:os";
19
+ import { join } from "node:path";
20
+ import * as iosApi from "./ios-xcuitest.js";
21
+
22
+ export const SPRINGBOARD = "com.apple.springboard";
23
+ export const IOS_TTL_MS = 30000;
24
+ const ITEMS_KEPT = 5000;
25
+ const STATE_NAMES = ["unknown", "notRunning", "runningBackgroundSuspended", "runningBackground", "runningForeground"];
26
+ const FOREGROUND = 4;
27
+ const INTERACTIVE = new Set(["button", "cell", "textField", "secureTextField", "searchField", "textView", "switch", "slider", "link", "tab", "key", "menuItem", "segmentedControl", "pickerWheel", "stepper", "toggle"]);
28
+ const TEXTY = new Set(["textField", "searchField", "textView"]);
29
+ const NOT_SENT = "(delivery=not_delivered, retry=safe)";
30
+ const UNKNOWN = "(delivery=unknown, retry=unsafe)";
31
+ const UNVERIFIED = "(delivery=delivered_unverified, retry=unsafe)";
32
+
33
+ const stateName = (n) => STATE_NAMES[n] ?? "unknown";
34
+
35
+ // What the two reads of an app's text fields say about text that was typed. `before` is null when the fields could
36
+ // not be read before the text went in. A field "of mine" is one like the tapped field when one was tapped (same
37
+ // type, identifier and label), any field otherwise. A field "gained" the text when its new value is its old value
38
+ // with the text put in at one place ("hell" turning into "hello" is one letter arriving, not "hello": pre-review
39
+ // P3) and neither value came back cut.
40
+ // "shown" one field was singled out and gained the text: the tapped one, when it is the only one of its
41
+ // kind in both reads and its value changed; otherwise, when both reads list the same fields, the
42
+ // only field of mine whose value changed. What other fields did does not matter then.
43
+ // "cut" that one field did not gain the text as far as its value was read, but the value came back
44
+ // cut and was not cut before: the text could not be looked for in all of it (pre-review P15).
45
+ // A field whose value reads the same but came back cut, when it was not before, has changed
46
+ // too: what was added is past where the read stops (pre-review P16). The other way round — cut
47
+ // before, whole now, the same value — is no change: nothing was added (pre-review P17-Grok-1).
48
+ // "placeholder" no field at all changed — or the fields were not read before, and none of mine holds the text —
49
+ // and a field of mine reads empty with the text as its own placeholder: such a field reads the
50
+ // same whether or not it took the text. Only a field that did not change can be that field: one
51
+ // that had a value and reads empty now did not gain the text (pre-review P13).
52
+ // "unread" not read before, and a field of mine has the text in its value or came back cut (any field, when
53
+ // none of mine is listed): there is nothing to compare it with.
54
+ // "moved" the two reads do not list the same fields (one appeared, went away, or changed its label), and
55
+ // the text is new among the fields of mine — more of them have it in their value than had it
56
+ // before, or more of them came back cut. All fields count when fewer of mine are listed than
57
+ // before.
58
+ // "several" the same fields, more than one of mine changed, and one of those gained the text, or came back
59
+ // cut and was not cut before: it arrived, or may have, and was not tied to one field. A field
60
+ // that is cut in both reads says nothing new (pre-review P14).
61
+ // "mismatch" everything else: the reads were compared and do not show the text arriving.
62
+ // The text in a field that did not change proves nothing, wherever it is (pre-reviews P12, P13), and neither does
63
+ // a field that is not mine.
64
+ export function fieldShows(before, after, text, key) {
65
+ const mine = (f) => !key || f.key === key;
66
+ const has = (f) => f.value.includes(text);
67
+ const like = (f) => f.value === "" && Boolean(f.ph) && f.ph === text;
68
+ const gained = (was, is) => {
69
+ if (was.cut || is.cut) return false;
70
+ for (let i = is.value.indexOf(text); i !== -1; i = is.value.indexOf(text, i + 1)) if (is.value.slice(0, i) + is.value.slice(i + text.length) === was.value) return true;
71
+ return false;
72
+ };
73
+ const judged = (was, is) => (gained(was, is) ? "shown" : is.cut && !was.cut ? "cut" : "mismatch");
74
+ const differs = (was, is) => was.value !== is.value || (!was.cut && is.cut);
75
+ if (before === null) {
76
+ if (after.some((f) => mine(f) && (f.cut || has(f))) || (!after.some(mine) && after.some((f) => f.cut || has(f)))) return "unread";
77
+ return after.some((f) => mine(f) && like(f)) ? "placeholder" : "mismatch";
78
+ }
79
+ const of = (list, k) => list.filter((f) => f.key === k);
80
+ if (key && of(before, key).length === 1 && of(after, key).length === 1 && differs(of(before, key)[0], of(after, key)[0])) return judged(of(before, key)[0], of(after, key)[0]);
81
+ const tally = (list) => { const m = new Map(); for (const f of list) m.set(f.key, (m.get(f.key) ?? 0) + 1); return m; };
82
+ const tb = tally(before), ta = tally(after);
83
+ if (tb.size !== ta.size || [...tb].some(([k, n]) => ta.get(k) !== n)) {
84
+ // the fields cannot be paired, so the text counts only where it is new
85
+ const among = Boolean(key) && of(after, key).length < of(before, key).length ? () => true : mine;
86
+ const n = (list, hit) => list.filter((f) => among(f) && hit(f)).length;
87
+ const cut = (f) => f.cut;
88
+ return n(after, has) > n(before, has) || n(after, cut) > n(before, cut) ? "moved" : "mismatch";
89
+ }
90
+ // the same fields: paired in order, kind by kind
91
+ const changed = [], seen = new Map();
92
+ for (const f of after) {
93
+ const i = seen.get(f.key) ?? 0; seen.set(f.key, i + 1);
94
+ const b = of(before, f.key)[i];
95
+ if (differs(b, f)) changed.push([b, f]);
96
+ }
97
+ const ofMine = changed.filter(([, f]) => mine(f));
98
+ if (ofMine.length === 1) return judged(...ofMine[0]);
99
+ if (ofMine.length > 1) return ofMine.some(([b, f]) => (f.cut && !b.cut) || gained(b, f)) ? "several" : "mismatch";
100
+ return changed.length === 0 && after.some((f) => mine(f) && like(f)) ? "placeholder" : "mismatch";
101
+ }
102
+
103
+ export function createIosSession({
104
+ env = process.env, api = iosApi, approve = () => null, springboardDenied = () => false, spawnImpl, onChild = () => {},
105
+ now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), runnerDir,
106
+ } = {}) {
107
+ const dir = runnerDir || env.NORACU_IOS_RUNNER_DIR || join(homedir(), ".noracu", "ios-runner");
108
+ const readOnly = env.NORACU_READ_ONLY === "1";
109
+ let runner = null; // { client, child, stop, device, startedAt }
110
+ let stopping = null; // the exit of a runner that was stopped and may still be there; cleared once it has exited
111
+ let heldIssue = null; // an xctest_issue an internal read was answered with: the next input reports it instead of going out
112
+ let gen = 0; // goes up at shutdown: a start that was in flight does not hand over its runner afterwards
113
+ let starting = null; // the start in flight, shared by calls that arrive meanwhile
114
+ let suspect = false; // the last call got no answer: ask for a sign of life before the next one
115
+ let current = null; // the app the last call named
116
+ let epoch = 0; // goes up when a call changes what is in front; indexes of an older epoch are dead
117
+ let nextIndex = 1, snapSeq = 0;
118
+ const items = new Map(); // element_index → { snapshot_id, bundle, type, label, id, frame, ts, epoch }
119
+
120
+ // ---------- device ----------
121
+ async function resolveDevice() {
122
+ const want = String(env.NORACU_IOS_UDID || "").trim();
123
+ if (want && !api.validUdid(want)) return { ok: false, error: "ios_config", message: "NORACU_IOS_UDID is not a device identifier" };
124
+ const list = await api.listDevices();
125
+ if (!list.ok) return list;
126
+ let d;
127
+ if (want) {
128
+ d = list.devices.find((x) => x.udid.toLowerCase() === want.toLowerCase());
129
+ if (!d) return { ok: false, error: "device_not_found", message: "this Mac does not list the device named in NORACU_IOS_UDID" };
130
+ } else {
131
+ const usable = list.devices.filter((x) => !x.simulated && x.paired && x.tunnel);
132
+ if (usable.length > 1) return { ok: false, error: "device_ambiguous", message: `${usable.length} iPhones are connected — set NORACU_IOS_UDID to one of: ${usable.map((x) => `${x.udid} (${x.name})`).join(", ")}` };
133
+ if (!usable.length) return { ok: false, error: "device_not_found", message: "no paired iPhone with a live connection — unlock it and connect it (cable or the same network), or name a booted simulator in NORACU_IOS_UDID" };
134
+ d = usable[0];
135
+ }
136
+ if (d.simulated || d.tunnelIP) return { ok: true, device: d };
137
+ const det = await api.deviceDetails(d.udid); // the list can lack the tunnel address
138
+ return det.ok ? { ok: true, device: { ...d, ...det.device, udid: d.udid, name: det.device.name ?? d.name } } : det;
139
+ }
140
+
141
+ // ---------- runner ----------
142
+ function stopRunner() {
143
+ const r = runner; runner = null; suspect = false;
144
+ if (!r) return;
145
+ try { r.stop(); } catch { /* already gone */ }
146
+ trackExit(r.exited);
147
+ }
148
+ // A runner that was stopped (or a start that failed) is remembered until its xcodebuild has really exited, not
149
+ // for a fixed time: each start waits up to STOP_WAIT_MS for it and is refused while it is still there. (Pre-review
150
+ // P3: the first refusal used to forget it, so the start after that ran a second test session on the device; and
151
+ // an exit that came late was still held against a start made minutes afterwards.)
152
+ function trackExit(exited) {
153
+ if (!exited) return;
154
+ const p = Promise.all([stopping, exited]).then(() => { if (stopping === p) stopping = null; });
155
+ stopping = p;
156
+ }
157
+
158
+ // The lock (pre-review P1). gate() reads it before every input, as before. On top of that no runner op that
159
+ // touches or shows the screen goes out on an "unlocked" answer older than a second: typing after the tap that
160
+ // focuses the field reads it again, and so does a snapshot or screenshot on its own — a locked phone's screen
161
+ // shows its notifications, so it is not read either. A tap right after its gate costs no second read.
162
+ const LOCK_FRESH_MS = 1000;
163
+ const STOP_WAIT_MS = 4000;
164
+ // app_state too: a locked phone's answer to "is it in front" is not read as one (review S4A-s6-grok-2)
165
+ const NEEDS_UNLOCKED = new Set(["snapshot", "screenshot", "app_state", "tap", "press", "drag", "type", "keys", "home"]);
166
+ const INPUT_OPS = new Set(["tap", "press", "drag", "type", "keys", "home"]);
167
+ let lockOkAt = -Infinity;
168
+ async function lockRefusal(force) {
169
+ const d = runner?.device;
170
+ if (!d || d.simulated || (!force && now() - lockOkAt <= LOCK_FRESH_MS)) return null;
171
+ const lock = await api.lockState(d.udid);
172
+ if (!lock.ok) return { error: "lock_unknown", message: `could not read the iPhone's lock state (${lock.message}) — refused (fail closed)` };
173
+ if (lock.locked) return { error: "device_locked", message: "the iPhone is locked — unlock it" };
174
+ lockOkAt = now();
175
+ return null;
176
+ }
177
+
178
+ async function startOnce() {
179
+ // observation-only mode never starts the runner: a starting runner puts its own app in front of whatever the iPhone shows
180
+ 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" };
181
+ const g = gen; // read before anything is waited for: a shutdown during any wait below stops this start
182
+ const shut = { ok: false, error: "runner_start_failed", message: "the session was shut down while the runner was starting" };
183
+ // two test sessions on one device at once do not work: a runner that was stopped must be gone first
184
+ if (stopping) {
185
+ const gone = await Promise.race([stopping.then(() => true), sleep(STOP_WAIT_MS).then(() => false)]);
186
+ if (!gone) return { ok: false, error: "runner_start_failed", message: "the runner that was stopped has not exited yet — try again in a moment" };
187
+ }
188
+ if (g !== gen) return shut; // shut down while a stopped runner was waited for
189
+ const dev = await resolveDevice();
190
+ if (!dev.ok) return dev;
191
+ const device = dev.device;
192
+ const bind = api.bindAddressFor(device);
193
+ if (!bind.ok) return bind;
194
+ if (!device.simulated) {
195
+ const lock = await api.lockState(device.udid);
196
+ if (!lock.ok) return { ok: false, error: "lock_unknown", message: `could not read the iPhone's lock state (${lock.message})` };
197
+ if (lock.locked) return { ok: false, error: "device_locked", message: "the iPhone is locked — unlock it" };
198
+ lockOkAt = now();
199
+ }
200
+ const xctestrun = await api.findXctestrun(join(dir, device.udid));
201
+ 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}` };
202
+ if (g !== gen) return shut; // shut down while the device, the lock or the build was looked up: nothing is started
203
+ const start = () => api.startRunner({ udid: device.udid, xctestrun, bind: bind.bind, spawnImpl, env });
204
+ let r = await start();
205
+ // The first start after a rebuild has been seen running the previous build: one more start, once that one is
206
+ // gone. A second runner of another build is an old build on the phone: the answer says to run the set-up again.
207
+ if (!r.ok && r.stale && r.exited && g === gen) {
208
+ const gone = await Promise.race([r.exited.then(() => true), sleep(STOP_WAIT_MS).then(() => false)]);
209
+ if (gone && g === gen) r = await start();
210
+ }
211
+ if (!r.ok) { trackExit(r.exited); return { ok: false, error: r.error, message: r.message }; }
212
+ if (g !== gen) { try { r.stop(); } catch { /* already gone */ } trackExit(r.exited); return shut; }
213
+ runner = { ...r, device, startedAt: now() };
214
+ suspect = false;
215
+ epoch++; // a starting runner puts its own app in front: whatever was read before is no longer what is on screen
216
+ onChild(r.child);
217
+ r.child?.once?.("exit", () => { if (runner && runner.child === r.child) { try { runner.client.close(); } catch { /* closed */ } runner = null; } });
218
+ return { ok: true };
219
+ }
220
+
221
+ async function ensureRunner() {
222
+ if (runner && suspect) {
223
+ const p = await runner.client.call("ping", {}, { timeoutMs: 5000 });
224
+ if (p.ok) suspect = false; else stopRunner(); // a stuck action ends with the test session
225
+ }
226
+ if (runner) return { ok: true };
227
+ if (!starting) starting = startOnce().finally(() => { starting = null; });
228
+ return starting;
229
+ }
230
+
231
+ // the runner that is up, asked for a sign of life when in doubt — never a new one
232
+ async function liveRunner() {
233
+ if (runner && suspect) {
234
+ const p = await runner.client.call("ping", {}, { timeoutMs: 5000 });
235
+ if (p.ok) suspect = false; else stopRunner();
236
+ }
237
+ return runner ? { ok: true } : { ok: false, error: "runner_unreachable", message: "the runner stopped before the input went out (input never starts one)" };
238
+ }
239
+
240
+ // an xctest_issue that an internal read met and the tool has not reported yet
241
+ const takeHeld = () => { const h = heldIssue; heldIssue = null; return h; };
242
+
243
+ async function rcall(op, args, timeoutMs) {
244
+ // Safety net: a failure XCTest recorded that an internal read was answered with, and that the tool which made
245
+ // the read did not report itself, is not lost — the next input is not sent, and reports it. No runner is
246
+ // started for that.
247
+ if (heldIssue && INPUT_OPS.has(op)) { const h = takeHeld(); return { ok: false, error: "xctest_issue", message: h.message, delivery: "not_delivered" }; }
248
+ // input never starts a runner: a runner that starts puts its own app in front, under the points and the focus the
249
+ // input was made for — only the gate (before anything is read for the call) may start one (review S4A-s6-gemini-1)
250
+ const up = INPUT_OPS.has(op) ? await liveRunner() : await ensureRunner();
251
+ const cur = runner;
252
+ if (!up.ok || !cur) return { ok: false, error: up.ok ? "runner_unreachable" : (up.error || "runner_unreachable"), message: up.ok ? "the runner stopped" : (up.message || "the runner stopped"), delivery: "not_delivered" };
253
+ if (NEEDS_UNLOCKED.has(op)) {
254
+ const l = await lockRefusal(false);
255
+ if (l) return { ok: false, error: l.error, message: l.message, delivery: "not_delivered" };
256
+ }
257
+ const r = await cur.client.call(op, args, { timeoutMs });
258
+ // An input that got no answer may still be waiting inside the test session: the session ends now, so the
259
+ // gesture cannot go out later (pre-review P1; the protocol always said so). Any failure XCTest recorded ends it
260
+ // as well, whichever command was answered with it — an input, a read, or the next command after a late one:
261
+ // what state the test session is in is then not known, and a ping answers from the socket alone (pre-review
262
+ // P3 and P4). A read that got no answer only makes the next call ask for a sign of life first.
263
+ const ends = !r.ok && (r.error === "xctest_issue" || (r.error === "ios_timeout" && INPUT_OPS.has(op)));
264
+ if (ends) { if (runner === cur) stopRunner(); }
265
+ else if (!r.ok && ["ios_timeout", "runner_unreachable", "runner_protocol"].includes(r.error)) suspect = true;
266
+ return r;
267
+ }
268
+
269
+ // ---------- gates ----------
270
+ // Before any input: the app rule, a running runner, then the lock. Returns an error result or null.
271
+ async function gate(bundle, op = "input") {
272
+ const denied = approve(bundle, op);
273
+ if (denied) return { error: denied };
274
+ const up = await ensureRunner();
275
+ if (!up.ok || !runner) return { error: `${up.ok ? "runner_unreachable" : up.error}: ${up.ok ? "the runner stopped" : up.message} ${NOT_SENT}` };
276
+ const l = await lockRefusal(true);
277
+ if (l) return { error: `${l.error}: ${l.message} ${NOT_SENT}` };
278
+ // the runner can exit while the lock is read (review S4A-s6-gemini-1)
279
+ if (!runner) return { error: `runner_unreachable: the runner stopped ${NOT_SENT}` };
280
+ return null;
281
+ }
282
+ // a runner started during this call: it put its own app in front, so the points and the focus the call was made for
283
+ // are gone (review S4A-s6-grok-3). Input given as points or as the focus (no element_index) is refused whenever the
284
+ // gate or a read started a runner during the call, whatever app it names — the runner's own "not in front" check
285
+ // depends on how fast the app comes back, so it is not relied on. An element_index of an older epoch is stale.
286
+ const restarted = () => ({ error: `runner_restarted: the runner started during this call, which puts its own app in front — the screen the points or the focus were meant for is gone; look again (ios_snapshot) ${NOT_SENT}` });
287
+ const HINTS = {
288
+ app_not_foreground: " — the app is not in front; call ios_launch first",
289
+ app_not_running: " — the app is not running; call ios_launch first",
290
+ system_alert: " — a system prompt is up on the iPhone; the person answers it there (noracu does not send input while one is up)",
291
+ no_keyboard: " — no keyboard is up; tap a text field first (ios_type with element_index does that)",
292
+ ios_timeout: " — look before acting again (ios_snapshot)",
293
+ xctest_issue: " — XCTest reported a failure while the command ran; look before acting again (ios_snapshot)",
294
+ };
295
+ // While app rules are in force, no input that names com.apple.springboard is sent — not even one tap on a
296
+ // button of a system prompt (next-steps R4, 2026-11-12). SpringBoard reads "in front" under every app, so a
297
+ // point named for it lands on whatever app is in front (one the rules may not allow), a tap on a Home Screen
298
+ // icon opens an app no rule was asked about (ios_launch is the way that asks), and text goes wherever the
299
+ // keyboard focus is. ios_home is not input named for SpringBoard and still goes out.
300
+ // The refusal comes before the gate (pre-review P5): the gate can start a runner, and a starting runner puts
301
+ // its own app in front of what the iPhone was showing — a refusal that says nothing was sent must change
302
+ // nothing either. The app rule is asked first and answers in its own words.
303
+ const sbNever = (bundle) => {
304
+ if (bundle !== SPRINGBOARD || !springboardDenied()) return null;
305
+ const denied = approve(bundle, "input");
306
+ 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}` };
307
+ };
308
+ // system_alert comes with two messages: an alert is up, or SpringBoard could not be read so one could not be ruled
309
+ // out — only the first is told "a system prompt is up" (review S4B-s8-new-1, S4D)
310
+ const hint = (r) => (r.error === "system_alert" && /could not be (read|ruled out)/.test(r.message || "")
311
+ ? " — noracu could not tell whether a system prompt is up on the iPhone; look at it (ios_screenshot) before acting again"
312
+ : HINTS[r.error] || "");
313
+ const inputError = (r) => ({ error: `${r.error}: ${r.message || "the runner refused"}${hint(r)} ${r.delivery === "not_delivered" ? NOT_SENT : UNKNOWN}` });
314
+ const readError = (r) => ({ error: `${r.error}: ${r.message || "the runner refused"}${r.error === "app_not_running" ? HINTS.app_not_running : ""}` });
315
+ function pickBundle(a, input) {
316
+ const b = a.bundle_id ?? current;
317
+ return b ? { bundle: b } : { error: `bundle_id required: name the app (ios_launch sets it for later calls)${input ? ` ${NOT_SENT}` : ""}` };
318
+ }
319
+
320
+ // ---------- elements ----------
321
+ function lookup(idx, snapshotId) {
322
+ const it = items.get(idx);
323
+ if (!it || it.epoch !== epoch || now() - it.ts > IOS_TTL_MS || (snapshotId !== undefined && it.snapshot_id !== snapshotId)) return null;
324
+ return it;
325
+ }
326
+ const label = (idx, it) => `element_index ${idx} (${it.type}${it.label ? ` "${it.label.slice(0, 40)}"` : ""})`;
327
+ const stale = (idx, why = "it is older than 30 s, from before the app in front changed, or unknown") =>
328
+ ({ error: `element_no_longer_valid: element_index ${idx} — ${why}; take a new ios_snapshot ${NOT_SENT}` });
329
+ // Read the app again and find the very element: same type, label, identifier and frame (2 pt), app in front.
330
+ async function recheck(idx, it) {
331
+ const r = await rcall("snapshot", { bundle_id: it.bundle, max_nodes: 1000 }, 30000);
332
+ if (!r.ok) return { error: inputError({ ...r, delivery: "not_delivered" }).error };
333
+ const res = r.result;
334
+ if (it.bundle !== SPRINGBOARD && res.state !== FOREGROUND) return stale(idx, `${it.bundle} is no longer in front`);
335
+ const same = (Array.isArray(res.nodes) ? res.nodes : []).filter((n) => n.type === it.type && (n.label || "") === it.label && (n.id || "") === it.id && Array.isArray(n.frame));
336
+ const node = same.find((n) => n.frame.every((v, k) => Math.abs(v - it.frame[k]) <= 2));
337
+ if (!node) return stale(idx, same.length ? `${label(idx, it)} moved` : `${label(idx, it)} is gone or changed`);
338
+ // the centre of the part that is on screen
339
+ const w = res.screen?.w || 0, h = res.screen?.h || 0, [fx, fy, fw, fh] = node.frame;
340
+ const x0 = Math.max(0, fx), y0 = Math.max(0, fy), x1 = Math.min(w, fx + fw), y1 = Math.min(h, fy + fh);
341
+ if (!(x1 > x0 && y1 > y0)) return stale(idx, `${label(idx, it)} is off screen`);
342
+ return { x: Math.round((x0 + x1) / 2 * 10) / 10, y: Math.round((y0 + y1) / 2 * 10) / 10 };
343
+ }
344
+ // the app's text inputs, for the read-back after typing: [{ key, value, cut }]; null when the app cannot be read
345
+ async function textFields(bundle) {
346
+ const r = await rcall("snapshot", { bundle_id: bundle, max_nodes: 1000 }, 30000);
347
+ if (!r.ok) { if (r.error === "xctest_issue") heldIssue = r; return null; }
348
+ if (r.result.truncated === true) return null; // fields past the limit were not read: nothing can be paired
349
+ return (r.result.nodes || []).filter((n) => TEXTY.has(n.type) && typeof n.value === "string")
350
+ .map((n) => ({ key: `${n.type}|${n.id || ""}|${n.label || ""}`, value: n.value, cut: n.value_truncated === true, ph: typeof n.placeholder === "string" ? n.placeholder : "" }));
351
+ }
352
+ // → { ok, st }: st is the last state read (null: none was); failed: a read failed, which ended the wait early
353
+ async function waitState(bundle, want, ms) {
354
+ const end = now() + ms;
355
+ let st = null;
356
+ for (;;) {
357
+ const r = await rcall("app_state", { bundle_id: bundle }, 10000);
358
+ if (!r.ok) { if (r.error === "xctest_issue") heldIssue = r; return { ok: false, st, failed: true }; }
359
+ st = r.result.state;
360
+ // "left the front" is a state seen as not running, suspended or in the background — never unknown (0) or no
361
+ // state at all (review S4A-s6-grok-1)
362
+ if (want ? st === FOREGROUND : [1, 2, 3].includes(st)) return { ok: true, st };
363
+ if (now() >= end) return { ok: false, st };
364
+ await sleep(300);
365
+ }
366
+ }
367
+
368
+ // ---------- tools ----------
369
+ return {
370
+ async status() {
371
+ const out = { backend: "xcuitest", experimental: true, device: null };
372
+ const dev = await resolveDevice();
373
+ if (!dev.ok) out.problem = `${dev.error}: ${dev.message}`;
374
+ else {
375
+ const d = dev.device;
376
+ out.device = { name: d.name, model: d.model, os: d.os, udid: d.udid, simulated: d.simulated, transport: d.transport, paired: d.paired, tunnel: d.tunnel, developer_mode: d.developerMode, booted: d.booted };
377
+ const bind = api.bindAddressFor(d);
378
+ if (!bind.ok) out.problem = `${bind.error}: ${bind.message}`;
379
+ if (!d.simulated) {
380
+ const lock = await api.lockState(d.udid);
381
+ out.locked = lock.ok ? lock.locked : null;
382
+ if (!lock.ok) out.lock_problem = lock.message;
383
+ }
384
+ out.setup = (await api.findXctestrun(join(dir, d.udid))) ? "built" : `missing — run: npx noracu ios-setup ${d.simulated ? "" : "--team <TeamID> "}--udid ${d.udid}`;
385
+ }
386
+ out.runner = runner ? { state: "running", protocol: api.PROTOCOL_VERSION, up_s: Math.round((now() - runner.startedAt) / 1000) } : { state: starting ? "starting" : "not_started" };
387
+ out.current_app = current;
388
+ return { text: JSON.stringify(out) };
389
+ },
390
+
391
+ async launch(a) {
392
+ const bundle = a.bundle_id;
393
+ // the runner first: starting it puts its own app in front, which would cover an app launched before it
394
+ const g = await gate(bundle, "launch");
395
+ if (g) return g;
396
+ const d = runner.device, opts = { terminateExisting: a.terminate_existing === true };
397
+ const r = d.simulated ? await api.simLaunch(d.udid, bundle, opts) : await api.launchApp(d.udid, bundle, opts);
398
+ if (!r.ok) {
399
+ const late = /timeout/.test(r.error);
400
+ // with terminate_existing the running app may already have been stopped when the launch failed
401
+ return { error: `${late ? r.error : "launch_failed"}: ${r.message} ${opts.terminateExisting ? "— the running app may already have been stopped (delivery=unknown, retry=unsafe)" : late ? "(delivery=unknown, retry=safe)" : NOT_SENT}` };
402
+ }
403
+ epoch++; current = bundle;
404
+ // the launch went out: asking again with terminate_existing would stop the app that was just started
405
+ const again = opts.terminateExisting ? "unsafe" : "safe";
406
+ const w = await waitState(bundle, true, 10000);
407
+ if (heldIssue) { const h = takeHeld(); return { error: `xctest_issue: ${h.message || "XCTest recorded a failure"}${HINTS.xctest_issue} — ${bundle} was started; whether it is in front was not read (delivery=delivered_unverified, retry=${again})` }; }
408
+ if (w.ok) return { text: `launched ${bundle} — it is in front (delivery=delivered_verified, retry=${again})` };
409
+ // a read of the app's state failed (with no failure of XCTest's behind it), so the 10 s were not waited
410
+ // out: the result says what was read, not "not in front after 10 s" (pre-review P8)
411
+ if (w.failed) return { error: `launch_not_confirmed: ${bundle} was started; ${w.st === null ? "whether it is in front could not be read" : `it was not in front when its state was last read (state ${stateName(w.st)}), and the read after that failed`} — look with ios_screenshot (delivery=delivered_unverified, retry=${again})` };
412
+ return { error: `launch_not_confirmed: ${bundle} was started but is not in front after 10 s (state ${stateName(w.st)}) — a system prompt may be covering it; look with ios_screenshot (delivery=delivered_unverified, retry=${again})` };
413
+ },
414
+
415
+ async snapshot(a = {}) {
416
+ const p = pickBundle(a, false);
417
+ if (p.error) return p;
418
+ const max = a.max_nodes ?? 300;
419
+ const r = await rcall("snapshot", { bundle_id: p.bundle, max_nodes: a.interactive ? 1000 : max }, 30000);
420
+ if (!r.ok) return readError(r);
421
+ const res = r.result, snapshot_id = `ios-${++snapSeq}`, ts = now();
422
+ let nodes = Array.isArray(res.nodes) ? res.nodes.filter((n) => n && typeof n.type === "string" && Array.isArray(n.frame) && n.frame.length === 4) : [];
423
+ if (a.interactive) nodes = nodes.filter((n) => INTERACTIVE.has(n.type));
424
+ const cut = nodes.length > max;
425
+ const elements = nodes.slice(0, max).map((n) => {
426
+ const i = nextIndex++;
427
+ items.set(i, { snapshot_id, bundle: p.bundle, type: n.type, label: n.label || "", id: n.id || "", frame: n.frame, ts, epoch });
428
+ const e = { i, type: n.type, label: n.label || "" };
429
+ if (n.id) e.id = n.id;
430
+ if (typeof n.value === "string" && n.type !== "secureTextField") e.value = n.value;
431
+ if (typeof n.placeholder === "string" && n.placeholder && n.type !== "secureTextField") e.placeholder = n.placeholder;
432
+ if (n.value_truncated === true) e.value_truncated = true;
433
+ e.frame = n.frame;
434
+ if (n.enabled === false) e.disabled = true;
435
+ if (n.selected === true) e.selected = true;
436
+ return e;
437
+ });
438
+ while (items.size > ITEMS_KEPT) items.delete(items.keys().next().value);
439
+ current = p.bundle;
440
+ const out = { bundle_id: p.bundle, snapshot_id, state: stateName(res.state), screen: res.screen, count: elements.length, truncated: Boolean(res.truncated) || cut, elements };
441
+ if (p.bundle !== SPRINGBOARD && res.state !== FOREGROUND) out.note = "this app is not in front: its elements cannot be acted on until ios_launch brings it forward";
442
+ return { text: JSON.stringify(out) };
443
+ },
444
+
445
+ async tap(a) {
446
+ let bundle, x, y, what;
447
+ const press = a.duration_ms !== undefined;
448
+ let e1;
449
+ if (a.element_index !== undefined) {
450
+ const it = lookup(a.element_index, a.snapshot_id);
451
+ if (!it) return stale(a.element_index);
452
+ const n = sbNever(it.bundle);
453
+ if (n) return n;
454
+ const g = await gate(it.bundle);
455
+ if (g) return g;
456
+ if (it.epoch !== epoch) return stale(a.element_index); // the gate started a runner: what was read is gone
457
+ e1 = epoch;
458
+ const c = await recheck(a.element_index, it);
459
+ if (c.error) return c;
460
+ ({ x, y } = c); bundle = it.bundle; what = label(a.element_index, it);
461
+ } else {
462
+ const p = pickBundle(a, true);
463
+ if (p.error) return p;
464
+ const n = sbNever(p.bundle);
465
+ if (n) return n;
466
+ const e0 = epoch;
467
+ const g = await gate(p.bundle);
468
+ if (g) return g;
469
+ if (epoch !== e0) return restarted();
470
+ e1 = epoch;
471
+ bundle = p.bundle; x = a.x; y = a.y; what = "the point";
472
+ }
473
+ if (epoch !== e1) return restarted();
474
+ const r = press
475
+ ? await rcall("press", { bundle_id: bundle, x, y, duration_ms: a.duration_ms }, 20000 + a.duration_ms)
476
+ : await rcall("tap", { bundle_id: bundle, x, y, ...(a.count > 1 ? { count: a.count } : {}) }, 20000);
477
+ if (!r.ok) return inputError(r);
478
+ current = bundle;
479
+ return { text: `${press ? `pressed ${a.duration_ms} ms on` : a.count > 1 ? `tapped ×${a.count}` : "tapped"} ${what} at (${x}, ${y}) in ${bundle} — sent; the screen is not checked ${UNVERIFIED}` };
480
+ },
481
+
482
+ async type(a) {
483
+ let bundle, secure = false, tapped = false, key = null, e1;
484
+ if (a.element_index !== undefined) {
485
+ const it = lookup(a.element_index, a.snapshot_id);
486
+ if (!it) return stale(a.element_index);
487
+ const n = sbNever(it.bundle); // before the gate, and before the tap that would focus: nothing is sent, no runner is started
488
+ if (n) return n;
489
+ const g = await gate(it.bundle);
490
+ if (g) return g;
491
+ if (it.epoch !== epoch) return stale(a.element_index); // the gate started a runner: what was read is gone
492
+ e1 = epoch;
493
+ const c = await recheck(a.element_index, it);
494
+ if (c.error) return c;
495
+ if (epoch !== e1) return restarted();
496
+ const t = await rcall("tap", { bundle_id: it.bundle, x: c.x, y: c.y }, 20000);
497
+ if (!t.ok) return inputError(t);
498
+ bundle = it.bundle; secure = it.type === "secureTextField"; tapped = true; key = `${it.type}|${it.id}|${it.label}`;
499
+ } else {
500
+ const p = pickBundle(a, true);
501
+ if (p.error) return p;
502
+ const n = sbNever(p.bundle);
503
+ if (n) return n;
504
+ const e0 = epoch;
505
+ const g = await gate(p.bundle);
506
+ if (g) return g;
507
+ if (epoch !== e0) return restarted();
508
+ e1 = epoch;
509
+ bundle = p.bundle;
510
+ }
511
+ current = bundle;
512
+ // a failure XCTest recorded that one of the reads around the typing was answered with (the session has ended)
513
+ const issueAt = (h, typed) => (typed ? inputError({ ...h, delivery: "unknown" })
514
+ : tapped ? { error: `xctest_issue: ${h.message || "XCTest recorded a failure"}${HINTS.xctest_issue} — the field was tapped, no text was typed (delivery=delivered_unverified, retry=unsafe)` }
515
+ : inputError({ ...h, delivery: "not_delivered" }));
516
+ let before = secure ? null : await textFields(bundle);
517
+ if (heldIssue) return issueAt(takeHeld(), false);
518
+ // after the tap the keyboard takes a moment; no_keyboard sent nothing, so asking again is safe
519
+ let r;
520
+ for (let i = 0; i < (tapped ? 8 : 1); i++) {
521
+ // a read before the text (textFields) can have started a runner: the focus is gone then
522
+ if (epoch !== e1) return tapped ? { error: `runner_restarted: the runner started again after the field was tapped — no text was typed; look again (ios_snapshot) (delivery=delivered_unverified, retry=unsafe)` } : restarted();
523
+ r = await rcall("type", { bundle_id: bundle, text: a.text }, 30000 + 80 * a.text.length);
524
+ if (r.ok || r.error !== "no_keyboard") break;
525
+ await sleep(350);
526
+ if (!secure) before = await textFields(bundle); // the keyboard coming up can move or hide fields: read again what is there before the text goes in
527
+ if (heldIssue) return issueAt(takeHeld(), false);
528
+ }
529
+ const n = [...a.text].length;
530
+ if (!r.ok) return tapped && r.delivery === "not_delivered" ? { error: `${r.error}: ${r.message || "the runner refused"}${hint(r)} — the field was tapped, no text was typed (delivery=delivered_unverified, retry=unsafe)` } : inputError(r);
531
+ if (secure) return { text: `typed ${n} characters into a secure field in ${bundle} — it never shows its value, so nothing was read back ${UNVERIFIED}` };
532
+ if (a.text.includes("\n")) return { text: `typed ${n} characters in ${bundle} — the text contains a return, which can submit or clear the field, so nothing was read back ${UNVERIFIED}` };
533
+ if (n < 4) return { text: `typed ${n} character${n === 1 ? "" : "s"} in ${bundle} — too short to tell from what was already there, so nothing was read back ${UNVERIFIED}` };
534
+ const after = await textFields(bundle);
535
+ // a failure XCTest recorded once the text had gone out: the "ok" the runner gave for it is in doubt
536
+ if (heldIssue) return issueAt(takeHeld(), true);
537
+ 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}` };
538
+ // The fields could not be read afterwards (the read failed, or the app has more elements than are read): the
539
+ // text was not seen to be missing, which type_not_confirmed would say — unverified, and the result names the
540
+ // side that could not be read (reviews P5, P6)
541
+ if (after === null) return { text: `typed ${n} characters in ${bundle} — the text fields ${before !== null ? "could not be read afterwards" : "could not be read before the text went in or afterwards"}, so nothing was read back ${UNVERIFIED}` };
542
+ // What the two reads say is decided in one place (fieldShows); each of its answers has one sentence here
543
+ const shown = fieldShows(before, after, a.text, key);
544
+ if (shown === "shown") return { text: `typed ${n} characters in ${bundle} — a text field shows them (delivery=delivered_verified, retry=unsafe)` };
545
+ const unverified = {
546
+ placeholder: "the text is the same as a field's placeholder, which cannot be told from an empty field, so nothing was read back",
547
+ unread: "the text fields could not be read before the text went in, so what they show now has nothing to be compared with",
548
+ moved: "the text fields listed before the text went in and afterwards are not the same ones, so the text could not be tied to one of them",
549
+ cut: "the field's value came back cut short, so the text could not be looked for in all of it",
550
+ several: "more than one text field changed while the text went in, so it was not tied to one of them",
551
+ }[shown];
552
+ return unverified ? { text: `typed ${n} characters in ${bundle} — ${unverified} ${UNVERIFIED}` } : notConfirmed;
553
+ },
554
+
555
+ async key(a) {
556
+ const p = pickBundle(a, true);
557
+ if (p.error) return p;
558
+ const never = sbNever(p.bundle);
559
+ if (never) return never;
560
+ const e0 = epoch;
561
+ const g = await gate(p.bundle);
562
+ if (g) return g;
563
+ if (epoch !== e0) return restarted();
564
+ const n = a.count ?? 1;
565
+ const r = await rcall("keys", { bundle_id: p.bundle, key: a.key, count: n }, 20000 + 100 * n);
566
+ if (!r.ok) return inputError(r);
567
+ current = p.bundle;
568
+ return { text: `pressed ${a.key}${n > 1 ? ` ×${n}` : ""} in ${p.bundle} — sent; the screen is not checked ${UNVERIFIED}` };
569
+ },
570
+
571
+ async swipe(a) {
572
+ const p = pickBundle(a, true);
573
+ if (p.error) return p;
574
+ const never = sbNever(p.bundle);
575
+ if (never) return never;
576
+ const e0 = epoch;
577
+ const g = await gate(p.bundle);
578
+ if (g) return g;
579
+ if (epoch !== e0) return restarted();
580
+ const args = { bundle_id: p.bundle, from: a.from, to: a.to };
581
+ for (const k of ["hold_ms", "end_hold_ms", "velocity"]) if (a[k] !== undefined) args[k] = a[k];
582
+ const r = await rcall("drag", args, 25000 + (a.hold_ms ?? 0) + (a.end_hold_ms ?? 0));
583
+ if (!r.ok) return inputError(r);
584
+ current = p.bundle;
585
+ return { text: `swiped (${a.from[0]}, ${a.from[1]}) → (${a.to[0]}, ${a.to[1]}) in ${p.bundle} — sent; the screen is not checked ${UNVERIFIED}` };
586
+ },
587
+
588
+ async home() {
589
+ const g = await gate(SPRINGBOARD, "home");
590
+ if (g) return g;
591
+ const prev = current;
592
+ // whether prev was in front before the press: only then can "left the front" be seen (review S4A-s6-D-1)
593
+ let wasFront = null;
594
+ if (prev && prev !== SPRINGBOARD) {
595
+ const pre = await rcall("app_state", { bundle_id: prev }, 10000);
596
+ if (!pre.ok && pre.error === "xctest_issue") return inputError({ ...pre, delivery: "not_delivered" });
597
+ // tri-state (review S4B-s6-1): in front, seen elsewhere (1/2/3), or not known (0, no state, a failed read)
598
+ const st = pre.ok ? pre.result?.state : undefined;
599
+ wasFront = st === FOREGROUND ? true : [1, 2, 3].includes(st) ? false : null;
600
+ }
601
+ const r = await rcall("home", {}, 15000);
602
+ if (!r.ok) return inputError(r);
603
+ epoch++;
604
+ if (prev && prev !== SPRINGBOARD && wasFront !== true) {
605
+ // not read: it stays the app later calls default to, as when its state cannot be read after the press
606
+ if (wasFront === false) current = SPRINGBOARD;
607
+ return { text: wasFront === false
608
+ ? `home pressed — ${prev} was not in front before the press, so it was not seen to leave the front (delivery=delivered_unverified, retry=safe)`
609
+ : `home pressed — whether ${prev} left the front could not be read (delivery=delivered_unverified, retry=safe)` };
610
+ }
611
+ if (prev && prev !== SPRINGBOARD) {
612
+ const w = await waitState(prev, false, 3000);
613
+ // home was pressed; XCTest then recorded a failure while the app's state was read
614
+ if (heldIssue) { const h = takeHeld(); return { error: `xctest_issue: ${h.message || "XCTest recorded a failure"}${HINTS.xctest_issue} — home was pressed; whether ${prev} left the front was not read (delivery=delivered_unverified, retry=safe)` }; }
615
+ if (w.ok) { current = SPRINGBOARD; return { text: `home pressed — ${prev} left the front (delivery=delivered_verified, retry=safe)` }; }
616
+ // seen to stay in front: say so, and keep it as the app later calls default to
617
+ // … or it was in front each time it was read and a later read failed, which ended the wait early (pre-review P8)
618
+ if (w.st === FOREGROUND) return { error: w.failed
619
+ ? `home_not_confirmed: home was pressed and ${prev} was still in front when its state was last read; the read after that failed — look with ios_screenshot (delivery=delivered_unverified, retry=safe)`
620
+ : `home_not_confirmed: home was pressed but ${prev} is still in front after 3 s — look with ios_screenshot (delivery=delivered_unverified, retry=safe)` };
621
+ // no state was read at all — any state but foreground ends the wait with ok, so what is left here is a
622
+ // first read that failed (with no failure of XCTest's behind it): pressed and not seen — and, as when the
623
+ // app is seen to stay, it remains the app later calls default to
624
+ return { text: `home pressed — whether ${prev} left the front could not be read (delivery=delivered_unverified, retry=safe)` };
625
+ }
626
+ current = SPRINGBOARD;
627
+ return { text: `home pressed — sent; the screen is not checked ${UNVERIFIED}` };
628
+ },
629
+
630
+ async screenshot() {
631
+ const r = await rcall("screenshot", {}, 30000);
632
+ if (!r.ok) return readError(r);
633
+ const png = r.result.png_base64;
634
+ if (typeof png !== "string" || png.length < 50) return { error: "capture_failed: the runner returned no image" };
635
+ return { image: png, mime: "image/png", meta: { w: r.result.w, h: r.result.h, unit: "points (ios_tap x,y and ios_snapshot frames use the same)" } };
636
+ },
637
+
638
+ // best effort, bounded by the caller: tell the runner to end its test, then stop xcodebuild
639
+ async shutdown() {
640
+ gen++;
641
+ try { api.killPending?.(); } catch { /* nothing to stop */ }
642
+ const r = runner;
643
+ if (r) {
644
+ try { await r.client.call("quit", {}, { timeoutMs: 1000 }); } catch { /* going away anyway */ }
645
+ stopRunner();
646
+ }
647
+ },
648
+ _state: () => ({ running: Boolean(runner), suspect, current, epoch, items: items.size }),
649
+ };
650
+ }