import { readFileSync, readdirSync, statSync } from "node:fs"; import { join, relative } from "node:path"; import { describe, expect, it } from "vitest"; /** * `startRunning()` is never called inside a capture session's configuration * window. * * THE CRASH THIS EXISTS FOR. TestFlight build 1.0.0 (129) died on every real * phone the instant the Join screen's camera prompt appeared — SIGABRT, from an * uncaught Objective-C `NSGenericException` thrown by * `-[AVCaptureSession startRunning]`: * * startRunning may not be called between calls to beginConfiguration and * commitConfiguration * * `PairingScanner.Coordinator.configure()` opened the window with * `session.beginConfiguration()`, closed it with a * `defer { session.commitConfiguration() }` — which holds it open to the END of * the function — and then called `session.startRunning()` under that defer. An * ObjC exception raised out of a `DispatchQueue.async` block is an abort: no * Swift error, nothing to catch, no error boundary, no Bugsink event. * * WHY A SOURCE GUARD AND NOT AN XCTEST. The simulator has no camera: * `AVCaptureDevice.default(for: .video)` answers nil, the coordinator's guard * returns before the start, and the crashing line is never reached. The entire * class of bug is invisible to every test that can run on this Mac, and only a * device build can execute it. So the assertion is over the SOURCE — the one * form that runs on the Linux `checks` job and cannot go quiet. * * It runs in `pnpm test:scripts`, which turbo never sees. It reads Swift text * and needs no Mac, no Xcode and no simulator. */ const ROOT = join(__dirname, "..", ".."); const IOS_SOURCES = join(ROOT, "apps", "cotton", "Sources"); /** The app target's own sources: the Camera tool's and the safety scan's sessions live here (ITMS-90683, 22 Nov 2026). */ const IOS_APP = join(ROOT, "apps", "cotton", "App"); /** Every `.swift` file under a directory, recursively. */ function swiftFiles(dir: string): string[] { const out: string[] = []; for (const entry of readdirSync(dir)) { const path = join(dir, entry); if (statSync(path).isDirectory()) { out.push(...swiftFiles(path)); continue; } if (entry.endsWith(".swift")) out.push(path); } return out; } export interface Offence { /** Repo-relative, so a failure message names something greppable. */ file: string; /** 1-based, the line calling `startRunning`. */ line: number; /** 1-based, the `beginConfiguration()` that opened the window. */ openedAt: number; /** True when the window was closed by a `defer` — build 129's shape. */ byDefer: boolean; } /** * Scan one file for a `startRunning(` that sits inside an open configuration * window. * * The window opens on `beginConfiguration()`. It closes on a * `commitConfiguration()` that is NOT inside a `defer` — a deferred commit runs * at scope exit, so everything written after it is still inside the window, and * that is precisely how build 129 read as correct. */ export function offencesIn(source: string, file: string): Offence[] { const lines = source.split("\n"); const found: Offence[] = []; let openedAt: number | null = null; let byDefer = false; for (let i = 0; i < lines.length; i += 1) { const line = lines[i] ?? ""; // Comments and doc comments describe the rule; they must not trip it. const code = line.replace(/\/\/.*$/, ""); if (code.includes("beginConfiguration()")) { openedAt = i + 1; byDefer = false; continue; } if (openedAt === null) continue; if (code.includes("commitConfiguration()")) { if (/\bdefer\b/.test(code)) { // Deferred: the window stays open to the end of the scope. byDefer = true; continue; } openedAt = null; byDefer = false; continue; } if (code.includes("startRunning(")) { found.push({ file, line: i + 1, openedAt, byDefer }); } } return found; } describe("an AVCaptureSession is never started inside its configuration window", () => { it("finds the shape build 129 shipped", () => { const build129 = [ "private func configure() {", " session.beginConfiguration()", " defer { session.commitConfiguration() }", " session.addInput(input)", " if !session.isRunning { session.startRunning() }", "}", ].join("\n"); const found = offencesIn(build129, "build-129.swift"); expect(found).toHaveLength(1); expect(found[0]?.line).toBe(5); expect(found[0]?.byDefer).toBe(true); }); it("accepts a commit that closes the window before the start", () => { const fixed = [ "private func configureAndStart() {", " session.beginConfiguration()", " let ready = addInputAndOutput()", " session.commitConfiguration()", " guard ready else { return }", " if !session.isRunning { session.startRunning() }", "}", ].join("\n"); expect(offencesIn(fixed, "fixed.swift")).toEqual([]); }); it("says nothing about a start with no configuration window at all", () => { expect(offencesIn("if !session.isRunning { session.startRunning() }", "bare.swift")).toEqual([]); }); it("holds over every Swift file the phone ships", () => { const files = [...swiftFiles(IOS_SOURCES), ...swiftFiles(IOS_APP)]; expect(files.some((path) => path.endsWith("Camera+AVFoundation.swift")), "the app's camera file is read").toBe(true); // A guard that reads a tree by path goes QUIET, not red, when the tree // moves. So the read is asserted before anything is compared. expect(files.length, `no Swift files under ${IOS_SOURCES} — has the tree moved?`).toBeGreaterThan(0); const offences = files.flatMap((path) => offencesIn(readFileSync(path, "utf8"), relative(ROOT, path)), ); expect( offences.map( (o) => `${o.file}:${o.line} starts the session inside the window opened at line ${o.openedAt}` + `${o.byDefer ? " by a DEFERRED commit, which stays open to the end of the scope" : ""}`, ), "AVFoundation throws NSGenericException — an uncaught ObjC exception, i.e. SIGABRT at launch. " + "Commit the configuration before starting the session.", ).toEqual([]); }); });