From 7558e7865bce85174c13823a17415a6bdb54e007 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 09:17:53 -0800 Subject: [PATCH 01/13] fix(hid): report input as undelivered once the simulator leaves Booted After `simctl shutdown`, SimDeviceLegacyHIDClient keeps accepting fire-and-forget sends (the completion we never asked for reports "Mach port invalid, device disconnected"), so rawSend returned true and `serve-sim tap/button/gesture` acked success for 5-15s until the detached server's --exit-on-simulator-shutdown watcher exited. Gate every HID send on SimDevice.state (HIDDeliveryGate): once it is not Booted the injector frees the message, returns false, and logs one "[hid] Dropping input: simulator is Shutting Down" line per state. Home (SpringBoard relaunch) and Duo-helper buttons bypass rawSend, so sendButton/sendButtonHID check the gate up front too. An unreadable state keeps the old behaviour. On an iPhone 18 Pro / iOS 27.0 sim the CLI now exits 1 from ~0.55s after `simctl shutdown` is issued (previously 0 until ~7s). The state read is in-process KVC; WS tap ack p50 is unchanged (<1ms). --- .../Sources/SimNative/HIDInjector.swift | 29 +++++++++- .../SimNativeSupport/HIDDeliveryGate.swift | 51 +++++++++++++++++ .../HIDDeliveryGateTests.swift | 57 +++++++++++++++++++ .../__tests__/native-hid-undelivered.test.ts | 41 +++++++++++++ 4 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift create mode 100644 packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift create mode 100644 packages/serve-sim/src/__tests__/native-hid-undelivered.test.ts diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index 360b9ee9b..d0804c762 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -47,6 +47,8 @@ actor HIDInjector { private var hidClient: NSObject? private var sendSel: Selector? private var simDevice: NSObject? + /// Drops input once the device leaves Booted; see `HIDDeliveryGate`. + private var deliveryGate = HIDDeliveryGate { nil } private let springBoardLauncher = SpringBoardLauncher() private var deviceHubKeyboardBridge: DeviceHubKeyboardBridge? @@ -94,6 +96,11 @@ actor HIDInjector { userInfo: [NSLocalizedDescriptionKey: "Device \(deviceUDID) not found"]) } self.simDevice = device + if device.responds(to: NSSelectorFromString("state")) { + deliveryGate = HIDDeliveryGate { [weak device] in + (device?.value(forKey: "state") as? NSNumber)?.intValue + } + } if let type = device.value(forKey: "deviceType") as? NSObject, let identifier = type.value(forKey: "identifier") as? String, identifier == "com.apple.CoreSimulator.SimDeviceType.iPhone-Duo" { @@ -181,11 +188,27 @@ actor HIDInjector { static let edgeLeft: UInt32 = 1 // Left edge static let edgeRight: UInt32 = 4 // Right edge + /// False when the device has left Booted (e.g. `simctl shutdown`): the HID + /// client still accepts sends then, so this is the only drop signal. + private func deviceAcceptsInput() -> Bool { + switch deliveryGate.admit() { + case .deliver: return true + case .drop(let log): + if let log { print(log); fflush(stdout) } + return false + } + } + /// Synchronously hand an already-built Indigo message to the guest, freeing it. /// Must run on `inputQueue`. Returns false when there is no HID client to - /// send through (setup never completed), so callers can report the drop. + /// send through (setup never completed) or the device is no longer booted, + /// so callers can report the drop. @discardableResult private func rawSend(_ msg: UnsafeMutableRawPointer) -> Bool { + guard deviceAcceptsInput() else { + free(msg) + return false + } guard let client = hidClient, let sendSel = sendSel else { print("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") free(msg) @@ -446,6 +469,7 @@ actor HIDInjector { /// Returns whether the press was handed to the guest. @discardableResult func sendButtonHID(page: UInt32, usage: UInt32, phase: String) async -> Bool { + guard deviceAcceptsInput() else { return false } if let duoBridge { switch phase { case "down": return duoBridge.send("key \(page) \(usage) 1") @@ -484,6 +508,9 @@ actor HIDInjector { /// unknown button or when the HID client / message builder is missing). func sendButton(button: String, deviceUDID: String) async -> Bool { hidLog("[hid] Sending button: \(button)") + // Home relaunches SpringBoard and Duo buttons go through the guest + // helper, neither via `rawSend`, so check the device here too. + guard deviceAcceptsInput() else { return false } switch button { case "home": diff --git a/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift new file mode 100644 index 000000000..7ab6e6aec --- /dev/null +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift @@ -0,0 +1,51 @@ +import Foundation + +/// Decides whether an HID event may be handed to the guest, based on the +/// target `SimDevice`'s state. +/// +/// `SimDeviceLegacyHIDClient` keeps accepting fire-and-forget sends after +/// `simctl shutdown` (its completion only reports "Mach port invalid, device +/// disconnected"), so without this check `serve-sim tap/button/gesture` acked +/// success until the detached server's shutdown watcher exited 5–15s later. +/// `SimDevice.state` leaves Booted within ~100ms of the shutdown starting and +/// is a cheap in-process read, so gating on it adds no measurable latency. +public final class HIDDeliveryGate { + public enum Decision: Equatable { + case deliver + /// `log` is set only for the first drop in a given state, so a drag + /// against a dead device doesn't flood the server log. + case drop(log: String?) + } + + /// CoreSimulator's `SimDeviceState` raw value for a booted device. + public static let bootedState = 3 + + private let readState: () -> Int? + private var lastLoggedState: Int? + + /// `readState` returns the raw `SimDeviceState`, or nil when it can't be + /// read (then input is delivered as before). + public init(readState: @escaping () -> Int?) { + self.readState = readState + } + + public func admit() -> Decision { + guard let state = readState(), state != Self.bootedState else { + lastLoggedState = nil + return .deliver + } + guard state != lastLoggedState else { return .drop(log: nil) } + lastLoggedState = state + return .drop(log: "[hid] Dropping input: simulator is \(Self.describe(state)), not Booted") + } + + static func describe(_ state: Int) -> String { + switch state { + case 0: return "Creating (state 0)" + case 1: return "Shutdown (state 1)" + case 2: return "Booting (state 2)" + case 4: return "Shutting Down (state 4)" + default: return "state \(state)" + } + } +} diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift new file mode 100644 index 000000000..85c6f2e5d --- /dev/null +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift @@ -0,0 +1,57 @@ +import XCTest +@testable import SimNativeSupport + +final class HIDDeliveryGateTests: XCTestCase { + // SimDeviceState raw values from CoreSimulator. + private let shutdown = 1, booting = 2, booted = 3, shuttingDown = 4 + + func testDeliversWhileBooted() { + let gate = HIDDeliveryGate { 3 } + XCTAssertEqual(gate.admit(), .deliver) + XCTAssertEqual(gate.admit(), .deliver) + } + + func testDeliversWhenStateIsUnreadable() { + // A CoreSimulator without a readable `state` keeps the old behaviour. + let gate = HIDDeliveryGate { nil } + XCTAssertEqual(gate.admit(), .deliver) + } + + func testDropsOnceTheDeviceStartsShuttingDown() { + // `simctl shutdown` flips SimDevice.state to Shutting Down within + // ~100ms, while SimDeviceLegacyHIDClient keeps accepting sends. + var state = booted + let gate = HIDDeliveryGate { state } + XCTAssertEqual(gate.admit(), .deliver) + state = shuttingDown + XCTAssertEqual(gate.admit(), .drop(log: "[hid] Dropping input: simulator is Shutting Down (state 4), not Booted")) + state = shutdown + XCTAssertEqual(gate.admit(), .drop(log: "[hid] Dropping input: simulator is Shutdown (state 1), not Booted")) + } + + func testLogsOnlyTheFirstDropPerState() { + let gate = HIDDeliveryGate { 1 } + guard case .drop(let first) = gate.admit() else { return XCTFail("expected drop") } + XCTAssertNotNil(first) + XCTAssertEqual(gate.admit(), .drop(log: nil)) + XCTAssertEqual(gate.admit(), .drop(log: nil)) + } + + func testLogsAgainAfterTheDeviceRecovers() { + var state = shutdown + let gate = HIDDeliveryGate { state } + _ = gate.admit() + state = booted + XCTAssertEqual(gate.admit(), .deliver) + state = shutdown + guard case .drop(let log) = gate.admit() else { return XCTFail("expected drop") } + XCTAssertNotNil(log) + } + + func testBootingAndUnknownStatesAreNotBooted() { + let booting = self.booting + XCTAssertNotEqual(HIDDeliveryGate { booting }.admit(), .deliver) + guard case .drop(let log) = HIDDeliveryGate(readState: { 99 }).admit() else { return XCTFail("expected drop") } + XCTAssertEqual(log, "[hid] Dropping input: simulator is state 99, not Booted") + } +} diff --git a/packages/serve-sim/src/__tests__/native-hid-undelivered.test.ts b/packages/serve-sim/src/__tests__/native-hid-undelivered.test.ts new file mode 100644 index 000000000..7dc1a617c --- /dev/null +++ b/packages/serve-sim/src/__tests__/native-hid-undelivered.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from "bun:test"; +import { NativeHid, type NativeHidDeps } from "../native"; + +// After `simctl shutdown` the native injector reports each send as not +// delivered (it gates on SimDevice.state; see HIDDeliveryGate.swift). That +// `false` must reach the {ack, ok:false} reply untouched, so +// `serve-sim tap/button/gesture` exit non-zero right away instead of acking +// success until the detached server's shutdown watcher exits. + +function fakeHid() { + const device = { booted: true }; + class FakeSimHID { + constructor(_udid: string, _duoHelper: string) {} + isFoldable = async () => false; + touch = async () => device.booted; + multiTouch = async () => device.booted; + button = async () => device.booted; + buttonHid = async () => device.booted; + } + const deps: NativeHidDeps = { + SimHID: FakeSimHID as unknown as NativeHidDeps["SimHID"], + bundledDuoHelper: () => "/nonexistent/serve-sim-duo-hid", + duoHelper: () => "/nonexistent/serve-sim-duo-hid", + }; + return { hid: new NativeHid("UDID", deps), device }; +} + +describe("NativeHid reports undelivered input after the simulator shuts down", () => { + test("touch, multi-touch, and buttons follow the native delivery result", async () => { + const { hid, device } = fakeHid(); + const sends = () => Promise.all([ + hid.touch("begin", 0.5, 0.5, 100, 200), + hid.multiTouch("begin", 0.4, 0.4, 0.6, 0.6, 100, 200), + hid.button("home"), + hid.buttonHid(12, 233), + ]); + expect(await sends()).toEqual([true, true, true, true]); + device.booted = false; + expect(await sends()).toEqual([false, false, false, false]); + }); +}); From cd2c398a2c255d3e94121141c5bf40f2756caa4f Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 09:17:53 -0800 Subject: [PATCH 02/13] test(hid): opt-in e2e that tap fails within 2s of simctl shutdown Shuts down the simulator named by SERVE_SIM_E2E_SHUTDOWN_UDID (skipped otherwise, so CI and shared sims are untouched) and asserts `serve-sim tap` exits non-zero with the undelivered error while the server is still up. Fails on the pre-fix native addon, passes with it. Registered as a Darwin e2e file to satisfy the CI test-plan invariants. --- .github/workflows/sim-test.yml | 1 + .../__tests__/hid-after-shutdown.e2e.test.ts | 60 +++++++++++++++++++ packages/serve-sim/src/ci-test-plan.ts | 2 + 3 files changed, 63 insertions(+) create mode 100644 packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts diff --git a/.github/workflows/sim-test.yml b/.github/workflows/sim-test.yml index 50ae64809..718e3b154 100644 --- a/.github/workflows/sim-test.yml +++ b/.github/workflows/sim-test.yml @@ -21,6 +21,7 @@ on: - "packages/serve-sim/src/__tests__/accessibility-endpoint.test.ts" - "packages/serve-sim/src/__tests__/avcc-stream-endpoint.test.ts" - "packages/serve-sim/src/__tests__/camera-connections.e2e.test.ts" + - "packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts" - "packages/serve-sim/src/__tests__/hid-malformed-input.test.ts" - "packages/serve-sim/src/__tests__/idle-floor.test.ts" - "packages/serve-sim/src/__tests__/permissions.e2e.test.ts" diff --git a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts new file mode 100644 index 000000000..72252e1e4 --- /dev/null +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -0,0 +1,60 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { execFileSync, spawn, spawnSync } from "child_process"; +import { existsSync } from "fs"; +import { join } from "path"; + +/** + * After `simctl shutdown`, SimDeviceLegacyHIDClient keeps accepting sends, so + * `serve-sim tap` exited 0 for ~5-15s — until the detached server's + * --exit-on-simulator-shutdown watcher exited. The injector now drops input once + * SimDevice.state leaves Booted, so the CLI fails within ~1s while the server is + * still up. + * + * Opt-in because it shuts the simulator down: set SERVE_SIM_E2E_SHUTDOWN_UDID to + * a booted (or bootable) iOS simulator this test may shut down — never a shared one. + */ + +const CLI = join(import.meta.dir, "../../dist/serve-sim.js"); +const udid = process.env.SERVE_SIM_E2E_SHUTDOWN_UDID; +const describeIfOptedIn = udid && existsSync(CLI) ? describe : describe.skip; + +function tap(): { status: number | null; stderr: string } { + const r = spawnSync("node", [CLI, "tap", "0.97", "0.03", "-d", udid!], { encoding: "utf-8", timeout: 15_000 }); + return { status: r.status, stderr: r.stderr ?? "" }; +} + +describeIfOptedIn(`HID input after simctl shutdown (${udid ?? ""})`, () => { + beforeAll(async () => { + spawnSync("xcrun", ["simctl", "boot", udid!], { stdio: "ignore" }); + execFileSync("xcrun", ["simctl", "bootstatus", udid!, "-b"], { stdio: "ignore", timeout: 120_000 }); + try { execFileSync("node", [CLI, "--kill", udid!], { stdio: "pipe" }); } catch {} + const port = 40_000 + Math.floor(Math.random() * 20_000); + const detach = spawnSync("node", [CLI, "--detach", "-p", String(port), udid!], { + encoding: "utf-8", stdio: ["ignore", "pipe", "inherit"], timeout: 45_000, + }); + if (detach.status !== 0) throw new Error(`serve-sim --detach failed: ${detach.stdout}`); + }, 180_000); + + afterAll(() => { + try { execFileSync("node", [CLI, "--kill", udid!], { stdio: "pipe" }); } catch {} + }, 30_000); + + test("tap fails with an undelivered error within ~1s of shutdown", async () => { + expect(tap().status).toBe(0); + + const shutdown = spawn("xcrun", ["simctl", "shutdown", udid!], { stdio: "ignore" }); + const issued = Date.now(); + let failure: { afterMs: number; stderr: string } | undefined; + while (Date.now() - issued < 2_000) { + const r = tap(); + if (r.status !== 0) { failure = { afterMs: Date.now() - issued, stderr: r.stderr }; break; } + } + await new Promise((r) => shutdown.on("exit", r)); + + // The server must still be answering — a "No serve-sim server" failure + // would only mean the shutdown watcher already exited. + if (!failure) throw new Error("every tap in the 2s after `simctl shutdown` exited 0"); + expect(failure.stderr).toContain("could not deliver the tap"); + expect(failure.afterMs).toBeLessThan(2_000); + }, 60_000); +}); diff --git a/packages/serve-sim/src/ci-test-plan.ts b/packages/serve-sim/src/ci-test-plan.ts index 61b88fdcd..9a0d2e14a 100644 --- a/packages/serve-sim/src/ci-test-plan.ts +++ b/packages/serve-sim/src/ci-test-plan.ts @@ -9,6 +9,8 @@ export const SIM_E2E_TEST_FILES = [ "packages/serve-sim/src/__tests__/accessibility-endpoint.test.ts", "packages/serve-sim/src/__tests__/avcc-stream-endpoint.test.ts", "packages/serve-sim/src/__tests__/camera-connections.e2e.test.ts", + // Opt-in (SERVE_SIM_E2E_SHUTDOWN_UDID): it shuts its simulator down. + "packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts", "packages/serve-sim/src/__tests__/hid-malformed-input.test.ts", "packages/serve-sim/src/__tests__/idle-floor.test.ts", "packages/serve-sim/src/__tests__/permissions.e2e.test.ts", From a6bee544f0dc05c0f6f0795f84f3dd0c2c6985fe Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 09:42:48 -0800 Subject: [PATCH 03/13] fix(hid): rebuild the HID client when the simulator boots again SimDeviceLegacyHIDClient never recovers from a shutdown: after the same device boots again under a server that stayed up (foreground, not --detach), every send still fails with HIDError 3 "Mach port invalid, device disconnected" while SimDevice.state reads Booted. The gate let those sends through, so `serve-sim tap` exited 0 and nothing reached the guest until the server was restarted. HIDClientChannel (SimNativeSupport) now owns the client and is the only way input reaches it. Any trip out of Booted (seen on admit, from the device's `device_state` notification when no input arrives in between, or a HIDError 3 send completion) makes the next admitted input rebuild the client once, respawn the Duo guest helper, and log "[hid] Simulator Booted again, reconnected HID client". A failed rebuild reports the input as undelivered and retries on the next one. The completion block is built once per client and runs on the injector's own queue. The send that hits HIDError 3 is still acked: waiting for the completion would add its round trip to every send. Buttons that bypass the client (Home's SpringBoard relaunch, Duo keys) run inside channel.gated. Rotate, pose and hinge are gated too, so they fail fast on a dead device instead of in a later port lookup or helper spawn. The Device Hub keyboard bridge holds no device port, so it needs no reconnect. On an iPhone 18 Pro / iOS 27.0 sim, a tap on Settings > General after shutdown + boot now opens General without restarting the server. CLI tap p50/p95 is unchanged (116/118-123 ms vs 118/124 ms). --- .../references/expected-behavior.md | 5 + .../Sources/SimNative/DuoHIDBridge.swift | 4 + .../Sources/SimNative/HIDInjector.swift | 176 +++++++++++++----- .../SimNativeSupport/HIDClientChannel.swift | 105 +++++++++++ .../SimNativeSupport/HIDDeliveryGate.swift | 52 +++++- .../HIDClientChannelTests.swift | 159 ++++++++++++++++ .../HIDDeliveryGateTests.swift | 75 +++++++- 7 files changed, 510 insertions(+), 66 deletions(-) create mode 100644 packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift create mode 100644 packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift diff --git a/.agents/skills/serve-sim-duo-verification/references/expected-behavior.md b/.agents/skills/serve-sim-duo-verification/references/expected-behavior.md index 78ae6d676..8b8e2388d 100644 --- a/.agents/skills/serve-sim-duo-verification/references/expected-behavior.md +++ b/.agents/skills/serve-sim-duo-verification/references/expected-behavior.md @@ -39,6 +39,11 @@ Use [verification.md](verification.md) for historical validation; its earlier pose list; no tent/tabletop or other hinge presets appear as buttons. - [ ] Pinch must not change the hinge angle. Folding is controlled by pose buttons or the Alt slider; two-finger screen input remains available to apps. +- [ ] While the Duo is shut down, touch, buttons, pose, hinge, and rotate + report failure instead of acking. After the same Duo boots again under a + server that stayed up, touch and pose work again without a restart: the + server logs `[hid] Simulator Booted again, reconnected HID client` once, + and the guest helper is respawned. - [ ] Named fold transitions render continuously between hinge-monitor samples. Start the visual clock only after confirmed guest movement; use the same 800 ms cubic easing as the native sweep. Sparse or delayed samples must not diff --git a/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift b/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift index e76ba09b4..108b79ccb 100644 --- a/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift +++ b/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift @@ -20,6 +20,10 @@ final class DuoHIDBridge { deinit { stop() } + /// Drop the guest helper so the next command spawns a fresh one, e.g. + /// after the device rebooted under a running server. + func reset() { stop() } + private func stop() { try? input?.close() try? output?.close() diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index d0804c762..a8e5d45d2 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -44,11 +44,19 @@ actor HIDInjector { let queue = DispatchSerialQueue(label: "hid-injector", qos: .userInteractive) nonisolated var unownedExecutor: UnownedSerialExecutor { queue.asUnownedSerialExecutor() } - private var hidClient: NSObject? - private var sendSel: Selector? + /// The SimDeviceLegacyHIDClient, behind the device-state gate. It drops + /// input once the device leaves Booted and rebuilds the client when the same + /// device boots again; see `HIDClientChannel`. + private var channel = HIDClientChannel( + gate: HIDDeliveryGate { nil }, connect: { nil }, log: HIDInjector.logLine + ) + private static let sendSel = NSSelectorFromString("sendWithMessage:freeWhenDone:completionQueue:completion:") + /// Send completion for `completionClient`. It is built once per client, not per send, + /// and runs on `queue`, which is this actor's executor. + private var completion: AnyObject? + private weak var completionClient: NSObject? + private var notificationHandlerID: UInt? private var simDevice: NSObject? - /// Drops input once the device leaves Booted; see `HIDDeliveryGate`. - private var deliveryGate = HIDDeliveryGate { nil } private let springBoardLauncher = SpringBoardLauncher() private var deviceHubKeyboardBridge: DeviceHubKeyboardBridge? @@ -96,11 +104,6 @@ actor HIDInjector { userInfo: [NSLocalizedDescriptionKey: "Device \(deviceUDID) not found"]) } self.simDevice = device - if device.responds(to: NSSelectorFromString("state")) { - deliveryGate = HIDDeliveryGate { [weak device] in - (device?.value(forKey: "state") as? NSNumber)?.intValue - } - } if let type = device.value(forKey: "deviceType") as? NSObject, let identifier = type.value(forKey: "identifier") as? String, identifier == "com.apple.CoreSimulator.SimDeviceType.iPhone-Duo" { @@ -143,6 +146,49 @@ actor HIDInjector { } + // Read on every admit (a plain in-process KVC read). + let gate = device.responds(to: NSSelectorFromString("state")) + ? HIDDeliveryGate { (device.value(forKey: "state") as? NSNumber)?.intValue } + : HIDDeliveryGate { nil } + // Thrown errors here fail setup, as before. + let firstClient = try Self.makeHIDClient(device: device) + let duo = duoBridge + channel = HIDClientChannel( + gate: gate, + connect: { + do { return try Self.makeHIDClient(device: device) } catch { + print("[hid] Could not create SimDeviceLegacyHIDClient: \(error.localizedDescription)") + return nil + } + }, + log: Self.logLine, + // The Duo guest helper ran inside the old boot; start a new one. + // Weak so `close()` can still release the bridge (and its helper). + didReconnect: { [weak duo] in duo?.reset() } + ) + channel.adopt(firstClient) + registerStateNotifications(device: device) + // DeviceHubKeyboardBridge needs no reconnect: it holds no device port, only + // Device Hub's (host app) pid, which it re-validates on every key-down. + let deviceName = device.value(forKey: "name") as? String ?? deviceUDID + let runtimeName = (device.value(forKey: "runtime") as? NSObject)? + .value(forKey: "name") as? String + self.deviceHubKeyboardBridge = DeviceHubKeyboardBridge.makeIfSupported( + deviceUDID: deviceUDID, + deviceName: deviceName, + runtimeName: runtimeName + ) + hidLog("[hid] SimDeviceLegacyHIDClient created") + hidLog("[hid] IndigoHIDMessageForMouseNSEvent loaded (with edge gesture support)") + } + + private static func logLine(_ line: String) { + print(line) + fflush(stdout) + } + + /// A new SimDeviceLegacyHIDClient for the device's current boot. + private static func makeHIDClient(device: NSObject) throws -> NSObject { guard let hidClass = NSClassFromString("_TtC12SimulatorKit24SimDeviceLegacyHIDClient") else { throw NSError(domain: "HIDInjector", code: 2, userInfo: [NSLocalizedDescriptionKey: "SimDeviceLegacyHIDClient not found"]) @@ -163,19 +209,48 @@ actor HIDInjector { throw NSError(domain: "HIDInjector", code: 4, userInfo: [NSLocalizedDescriptionKey: "Failed to create HID client"]) } + return clientObj + } - self.hidClient = clientObj - self.sendSel = NSSelectorFromString("sendWithMessage:freeWhenDone:completionQueue:completion:") - let deviceName = device.value(forKey: "name") as? String ?? deviceUDID - let runtimeName = (device.value(forKey: "runtime") as? NSObject)? - .value(forKey: "name") as? String - self.deviceHubKeyboardBridge = DeviceHubKeyboardBridge.makeIfSupported( - deviceUDID: deviceUDID, - deviceName: deviceName, - runtimeName: runtimeName - ) - hidLog("[hid] SimDeviceLegacyHIDClient created") - hidLog("[hid] IndigoHIDMessageForMouseNSEvent loaded (with edge gesture support)") + /// Watch `device_state` so a shutdown + boot with no input in between still + /// rebuilds the client: then the gate only ever reads Booted. The handler + /// runs on `queue`, this actor's executor, so it never races the channel. + private func registerStateNotifications(device: NSObject) { + let sel = NSSelectorFromString("registerNotificationHandlerOnQueue:handler:") + guard device.responds(to: sel) else { return } + let channel = self.channel + let handler: @convention(block) (NSDictionary?) -> Void = { [weak channel] info in + guard let info = info as? [AnyHashable: Any] else { return } + channel?.noteDeviceNotification(info) + } + typealias RegisterFunc = @convention(c) (AnyObject, Selector, AnyObject, AnyObject) -> UInt + notificationHandlerID = unsafeBitCast(device.method(for: sel), to: RegisterFunc.self)( + device, sel, queue, handler as AnyObject) + } + + private func unregisterStateNotifications() { + let sel = NSSelectorFromString("unregisterNotificationHandler:error:") + guard let id = notificationHandlerID, let device = simDevice, device.responds(to: sel) else { return } + notificationHandlerID = nil + typealias UnregisterFunc = @convention(c) (AnyObject, Selector, UInt, AutoreleasingUnsafeMutablePointer) -> ObjCBool + var error: NSError? + _ = unsafeBitCast(device.method(for: sel), to: UnregisterFunc.self)(device, sel, id, &error) + } + + /// The completion block for sends through `client`. A HIDError 3 from it + /// ("Mach port invalid, device disconnected") makes the next input rebuild + /// the client. The send that hit it was already acked: waiting for the + /// completion would add its round trip to every send. + private func completion(for client: NSObject) -> AnyObject { + if let completion, completionClient === client { return completion } + let channel = self.channel + let block: @convention(block) (NSError?) -> Void = { [weak channel, weak client] error in + guard let error, let channel, let client else { return } + channel.clientReported(client, domain: error.domain, code: error.code) + } + completion = block as AnyObject + completionClient = client + return block as AnyObject } // IndigoHIDEdge values (x4 param to IndigoHIDMessageForMouseNSEvent). @@ -188,39 +263,23 @@ actor HIDInjector { static let edgeLeft: UInt32 = 1 // Left edge static let edgeRight: UInt32 = 4 // Right edge - /// False when the device has left Booted (e.g. `simctl shutdown`): the HID - /// client still accepts sends then, so this is the only drop signal. - private func deviceAcceptsInput() -> Bool { - switch deliveryGate.admit() { - case .deliver: return true - case .drop(let log): - if let log { print(log); fflush(stdout) } - return false - } - } - /// Synchronously hand an already-built Indigo message to the guest, freeing it. /// Must run on `inputQueue`. Returns false when there is no HID client to /// send through (setup never completed) or the device is no longer booted, /// so callers can report the drop. @discardableResult private func rawSend(_ msg: UnsafeMutableRawPointer) -> Bool { - guard deviceAcceptsInput() else { - free(msg) - return false - } - guard let client = hidClient, let sendSel = sendSel else { - print("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") - free(msg) - return false - } - typealias SendFunc = @convention(c) (AnyObject, Selector, UnsafeMutableRawPointer, ObjCBool, AnyObject?, AnyObject?) -> Void - guard let sendIMP = class_getMethodImplementation(object_getClass(client)!, sendSel) else { - free(msg) - return false + var handedOff = false + let sent = channel.send { client in + typealias SendFunc = @convention(c) (AnyObject, Selector, UnsafeMutableRawPointer, ObjCBool, AnyObject?, AnyObject?) -> Void + guard let sendIMP = class_getMethodImplementation(object_getClass(client)!, Self.sendSel) else { return false } + // freeWhenDone: the client owns `msg` from here. + unsafeBitCast(sendIMP, to: SendFunc.self)(client, Self.sendSel, msg, ObjCBool(true), queue, completion(for: client)) + handedOff = true + return true } - unsafeBitCast(sendIMP, to: SendFunc.self)(client, sendSel, msg, ObjCBool(true), nil, nil) - return true + if !handedOff { free(msg) } + return sent } /// Build a single-finger touch message (normalized 0..1 coords). Pure — safe @@ -469,7 +528,11 @@ actor HIDInjector { /// Returns whether the press was handed to the guest. @discardableResult func sendButtonHID(page: UInt32, usage: UInt32, phase: String) async -> Bool { - guard deviceAcceptsInput() else { return false } + // Duo keys go through the guest helper, not `rawSend`. + await channel.gated { await sendButtonHIDAdmitted(page: page, usage: usage, phase: phase) } + } + + private func sendButtonHIDAdmitted(page: UInt32, usage: UInt32, phase: String) async -> Bool { if let duoBridge { switch phase { case "down": return duoBridge.send("key \(page) \(usage) 1") @@ -509,9 +572,11 @@ actor HIDInjector { func sendButton(button: String, deviceUDID: String) async -> Bool { hidLog("[hid] Sending button: \(button)") // Home relaunches SpringBoard and Duo buttons go through the guest - // helper, neither via `rawSend`, so check the device here too. - guard deviceAcceptsInput() else { return false } + // helper, neither via `rawSend`, so gate the whole press. + return await channel.gated { await sendButtonAdmitted(button: button, deviceUDID: deviceUDID) } + } + private func sendButtonAdmitted(button: String, deviceUDID: String) async -> Bool { switch button { case "home": // Xcode 26+ silently drops the Indigo HID home-button press, so the @@ -641,7 +706,10 @@ actor HIDInjector { func setDuoHelper(_ path: String) { duoBridge?.executable = path } - func close() { duoBridge = nil } + func close() { + unregisterStateNotifications() + duoBridge = nil + } private func updateTouchTarget(width: Int, height: Int) { guard duoBridge != nil else { return } @@ -651,11 +719,14 @@ actor HIDInjector { func setPose(_ name: String, fromDegrees: Double) -> Bool { guard let pose = DevicePose.preset(named: name), fromDegrees.isFinite, (0...180).contains(fromDegrees) else { return false } + // Gated like other input: a dead device would only fail later, in the guest helper's spawn. + guard channel.admit() else { return false } return duoBridge?.send("sweep \(fromDegrees) \(pose.hingeDegrees) 800") == true } func setHingeAngle(degrees: Double) -> Bool { guard degrees.isFinite, (0...180).contains(degrees) else { return false } + guard channel.admit() else { return false } return duoBridge?.send("angle \(degrees)") == true } @@ -774,6 +845,9 @@ actor HIDInjector { /// Simulator.app itself rotates the device, and how idb's /// `FBSimulatorPurpleHID.orientationEvent:` is delivered. func sendOrientation(orientation: UInt32) -> Bool { + // A shut-down device would otherwise fail later (PurpleWorkspacePort + // lookup / the Duo helper's spawn). The gate fails fast and with the same log line. + guard channel.admit() else { return false } if let duoBridge { guard (1...4).contains(orientation) else { return false } return duoBridge.send("orientation \(orientation)") diff --git a/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift new file mode 100644 index 000000000..89827673c --- /dev/null +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift @@ -0,0 +1,105 @@ +import Foundation + +/// Owns the HID client and is the only way input reaches it, so every send +/// is gated on the device's state and runs on a client from the current boot. +/// +/// - `send` hands the client to raw Indigo sends. +/// - `gated` covers input that never touches the client (Home relaunches +/// SpringBoard; Duo buttons go through the guest helper). +/// +/// Both check `HIDDeliveryGate` on every call. On the first call after the +/// device comes back to Booted they rebuild the client (once), call +/// `didReconnect`, and log it. Not thread-safe: use it from one serial queue +/// (HIDInjector's executor, which also receives the client's completions +/// and the device's notifications). +public final class HIDClientChannel { + public static var reconnectedMessage: String { "[hid] Simulator Booted again, reconnected HID client" } + + private let gate: HIDDeliveryGate + private let makeClient: () -> Client? + private let log: (String) -> Void + private let didReconnect: () -> Void + public private(set) var client: Client? + + public init( + gate: HIDDeliveryGate, + connect: @escaping () -> Client?, + log: @escaping (String) -> Void, + didReconnect: @escaping () -> Void = {} + ) { + self.gate = gate + self.makeClient = connect + self.log = log + self.didReconnect = didReconnect + } + + /// Create (or replace) the client. Returns whether one exists now. + @discardableResult + public func connect() -> Bool { + client = makeClient() + return client != nil + } + + /// Use an already-created client (setup creates the first one itself so + /// its error can fail setup). + public func adopt(_ client: Client) { + self.client = client + } + + /// Whether input may go to the guest now. Rebuilds the client first when + /// the device has just come back. + public func admit() -> Bool { + switch gate.admit() { + case .drop(let message): + if let message { log(message) } + return false + case .deliver(reconnect: false): + return true + case .deliver(reconnect: true): + guard connect() else { + // Try again on the next input rather than sending through a dead port. + gate.noteClientDisconnected() + log("[hid] Simulator Booted again, but the HID client could not be recreated") + return false + } + log(Self.reconnectedMessage) + didReconnect() + return true + } + } + + /// Gate, then hand the current client to `transmit`. False when the + /// device isn't booted, there is no client, or `transmit` failed; + /// `transmit` isn't called in the first two cases. + public func send(_ transmit: (Client) -> Bool) -> Bool { + guard admit() else { return false } + guard let client else { + log("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") + return false + } + return transmit(client) + } + + /// Gate input that doesn't go through the client (it still triggers the + /// reconnect, so the next touch after a Home press works). + public func gated( + isolation: isolated (any Actor)? = #isolation, + _ body: () async -> Bool + ) async -> Bool { + guard admit() else { return false } + return await body() + } + + /// A send completion from `reporter`. A disconnect error from the + /// current client makes the next input rebuild it. Late errors from a + /// client that was already replaced are ignored. + public func clientReported(_ reporter: Client, domain: String, code: Int) { + guard reporter === client, HIDDeliveryGate.isClientDisconnected(domain: domain, code: code) else { return } + gate.noteClientDisconnected() + } + + /// See `HIDDeliveryGate.noteNotification`. + public func noteDeviceNotification(_ info: [AnyHashable: Any]) { + gate.noteNotification(info) + } +} diff --git a/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift index 7ab6e6aec..8e2dd484a 100644 --- a/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift @@ -1,7 +1,7 @@ import Foundation -/// Decides whether an HID event may be handed to the guest, based on the -/// target `SimDevice`'s state. +/// Decides whether an HID event may be handed to the guest, and when the HID +/// client has to be rebuilt first, based on the target `SimDevice`'s state. /// /// `SimDeviceLegacyHIDClient` keeps accepting fire-and-forget sends after /// `simctl shutdown` (its completion only reports "Mach port invalid, device @@ -9,9 +9,17 @@ import Foundation /// success until the detached server's shutdown watcher exited 5–15s later. /// `SimDevice.state` leaves Booted within ~100ms of the shutdown starting and /// is a cheap in-process read, so gating on it adds no measurable latency. +/// +/// The client also never recovers: once the device has left Booted, every +/// later send fails with HIDError 3, even after the same device boots again. +/// So any trip out of Booted (seen by `admit`, a `device_state` notification, +/// or a disconnect error from the client) makes the next delivery ask for a +/// reconnect. Not thread-safe: use it from one serial queue. public final class HIDDeliveryGate { public enum Decision: Equatable { - case deliver + /// `reconnect` is true for the first delivery after the device (or + /// the client) went away: rebuild the HID client before sending. + case deliver(reconnect: Bool) /// `log` is set only for the first drop in a given state, so a drag /// against a dead device doesn't flood the server log. case drop(log: String?) @@ -22,6 +30,7 @@ public final class HIDDeliveryGate { private let readState: () -> Int? private var lastLoggedState: Int? + private var needsReconnect = false /// `readState` returns the raw `SimDeviceState`, or nil when it can't be /// read (then input is delivered as before). @@ -30,13 +39,38 @@ public final class HIDDeliveryGate { } public func admit() -> Decision { - guard let state = readState(), state != Self.bootedState else { - lastLoggedState = nil - return .deliver + if let state = readState(), state != Self.bootedState { + needsReconnect = true + guard state != lastLoggedState else { return .drop(log: nil) } + lastLoggedState = state + return .drop(log: "[hid] Dropping input: simulator is \(Self.describe(state)), not Booted") } - guard state != lastLoggedState else { return .drop(log: nil) } - lastLoggedState = state - return .drop(log: "[hid] Dropping input: simulator is \(Self.describe(state)), not Booted") + lastLoggedState = nil + let reconnect = needsReconnect + needsReconnect = false + return .deliver(reconnect: reconnect) + } + + /// The HID client reported it can no longer reach the device. + public func noteClientDisconnected() { + needsReconnect = true + } + + /// Feed a `-[SimDevice registerNotificationHandlerOnQueue:handler:]` + /// payload. Catches a shutdown + boot that happens with no input in + /// between, which `admit` alone would only ever see as Booted. + public func noteNotification(_ info: [AnyHashable: Any]) { + guard info["notification"] as? String == "device_state", + let state = (info["new_state"] as? NSNumber)?.intValue, + state != Self.bootedState else { return } + needsReconnect = true + } + + /// SimulatorKit's `SimDeviceLegacyHIDClient.HIDError` 3 ("Mach port + /// invalid, device disconnected"). Error 2 is not included: a new client + /// reports it while the guest is still finishing boot and then works. + public static func isClientDisconnected(domain: String, code: Int) -> Bool { + code == 3 && domain.hasSuffix("SimDeviceLegacyHIDClient.HIDError") } static func describe(_ state: Int) -> String { diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift new file mode 100644 index 000000000..89d8fc6ef --- /dev/null +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift @@ -0,0 +1,159 @@ +import XCTest +@testable import SimNativeSupport + +/// HIDInjector routes every input through `HIDClientChannel`: raw Indigo sends +/// get the client only via `send`, and buttons that never reach the client +/// (Home's SpringBoard relaunch, Duo-helper keys) run inside `gated`. +final class HIDClientChannelTests: XCTestCase { + private final class FakeClient {} + private let shutdown = 1, booting = 2, booted = 3, shuttingDown = 4 + + private final class Harness { + var state: Int? = 3 + var stateReads = 0 + var connects = 0 + var connectSucceeds = true + var logs: [String] = [] + var reconnectHooks = 0 + lazy var channel: HIDClientChannel = { + let gate = HIDDeliveryGate { [unowned self] in + self.stateReads += 1 + return self.state + } + return HIDClientChannel( + gate: gate, + connect: { [unowned self] in + self.connects += 1 + return self.connectSucceeds ? FakeClient() : nil + }, + log: { [unowned self] in self.logs.append($0) }, + didReconnect: { [unowned self] in self.reconnectHooks += 1 } + ) + }() + + init() {} + /// Mirrors HIDInjector.setup: the first client is created up front. + func setup() { XCTAssertTrue(channel.connect()) } + } + + func testStateIsReadOnEverySend() { + let h = Harness(); h.setup() + var sends = 0 + XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) + XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(h.stateReads, 2) + h.state = shuttingDown + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(h.stateReads, 3) + XCTAssertEqual(sends, 2) + } + + func testSendNeverReachesTheClientOnceTheDeviceLeavesBooted() { + let h = Harness(); h.setup() + var sends = 0 + h.state = shutdown + for _ in 0..<5 { XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) } + XCTAssertEqual(sends, 0) + XCTAssertEqual(h.logs, ["[hid] Dropping input: simulator is Shutdown (state 1), not Booted"]) + } + + func testGatedButtonsDoNotRunWhileShutDown() async { + // Home relaunches SpringBoard and Duo buttons talk to the guest helper; + // neither goes through `send`, so `gated` is their only check. + let h = Harness(); h.setup() + var homeLaunches = 0 + var ok = await h.channel.gated { homeLaunches += 1; return true } + XCTAssertTrue(ok) + h.state = shutdown + ok = await h.channel.gated { homeLaunches += 1; return true } + XCTAssertFalse(ok) + XCTAssertEqual(homeLaunches, 1) + } + + func testReturnToBootedReconnectsOnceBeforeTheNextSend() { + let h = Harness(); h.setup() + let first = h.channel.client + h.state = shutdown + XCTAssertFalse(h.channel.send { _ in true }) + h.state = booted + var sentTo: [ObjectIdentifier] = [] + for _ in 0..<3 { XCTAssertTrue(h.channel.send { sentTo.append(ObjectIdentifier($0)); return true }) } + XCTAssertEqual(h.connects, 2) // setup + exactly one reconnect + XCTAssertEqual(h.reconnectHooks, 1) + XCTAssertFalse(h.channel.client === first) + XCTAssertEqual(Set(sentTo), [ObjectIdentifier(h.channel.client!)]) + XCTAssertEqual(h.logs.filter { $0 == "[hid] Simulator Booted again, reconnected HID client" }.count, 1) + } + + func testRebootWithNoInputInBetweenReconnectsFromTheStateNotification() { + let h = Harness(); h.setup() + h.channel.noteDeviceNotification(["notification": "device_state", "new_state": NSNumber(value: shuttingDown)]) + h.channel.noteDeviceNotification(["notification": "device_state", "new_state": NSNumber(value: booted)]) + XCTAssertTrue(h.channel.send { _ in true }) + XCTAssertEqual(h.connects, 2) + } + + func testGatedButtonAfterRebootAlsoReconnects() async { + let h = Harness(); h.setup() + h.state = shutdown + _ = await h.channel.gated { true } + h.state = booted + let ok = await h.channel.gated { true } + XCTAssertTrue(ok) + XCTAssertEqual(h.connects, 2) + } + + func testDisconnectErrorFromTheCurrentClientRebuildsOnTheNextSend() { + let h = Harness(); h.setup() + let first = h.channel.client! + h.channel.clientReported(first, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 3) + XCTAssertTrue(h.channel.send { _ in true }) + XCTAssertEqual(h.connects, 2) + XCTAssertFalse(h.channel.client === first) + } + + func testLateErrorsFromAReplacedClientAreIgnored() { + let h = Harness(); h.setup() + let first = h.channel.client! + h.channel.clientReported(first, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 3) + XCTAssertTrue(h.channel.send { _ in true }) // rebuilt + // Completions for sends queued on the old client arrive afterwards. + h.channel.clientReported(first, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 3) + XCTAssertTrue(h.channel.send { _ in true }) + XCTAssertEqual(h.connects, 2) + } + + func testBootErrorsDoNotRebuild() { + let h = Harness(); h.setup() + h.channel.clientReported(h.channel.client!, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) + XCTAssertTrue(h.channel.send { _ in true }) + XCTAssertEqual(h.connects, 1) + } + + func testFailedReconnectReportsUndeliveredAndRetries() { + let h = Harness(); h.setup() + h.state = shutdown + _ = h.channel.send { _ in true } + h.state = booted + h.connectSucceeds = false + var sends = 0 + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 0) + h.connectSucceeds = true + XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 1) + XCTAssertEqual(h.connects, 3) + } + + func testNoClientReportsUndelivered() { + let h = Harness() // setup never connected + var sends = 0 + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 0) + } + + func testTransmitFailureIsReported() { + let h = Harness(); h.setup() + XCTAssertFalse(h.channel.send { _ in false }) + } +} diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift index 85c6f2e5d..3beee90fa 100644 --- a/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift @@ -7,14 +7,14 @@ final class HIDDeliveryGateTests: XCTestCase { func testDeliversWhileBooted() { let gate = HIDDeliveryGate { 3 } - XCTAssertEqual(gate.admit(), .deliver) - XCTAssertEqual(gate.admit(), .deliver) + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) } func testDeliversWhenStateIsUnreadable() { // A CoreSimulator without a readable `state` keeps the old behaviour. let gate = HIDDeliveryGate { nil } - XCTAssertEqual(gate.admit(), .deliver) + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) } func testDropsOnceTheDeviceStartsShuttingDown() { @@ -22,7 +22,7 @@ final class HIDDeliveryGateTests: XCTestCase { // ~100ms, while SimDeviceLegacyHIDClient keeps accepting sends. var state = booted let gate = HIDDeliveryGate { state } - XCTAssertEqual(gate.admit(), .deliver) + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) state = shuttingDown XCTAssertEqual(gate.admit(), .drop(log: "[hid] Dropping input: simulator is Shutting Down (state 4), not Booted")) state = shutdown @@ -42,7 +42,7 @@ final class HIDDeliveryGateTests: XCTestCase { let gate = HIDDeliveryGate { state } _ = gate.admit() state = booted - XCTAssertEqual(gate.admit(), .deliver) + XCTAssertEqual(gate.admit(), .deliver(reconnect: true)) state = shutdown guard case .drop(let log) = gate.admit() else { return XCTFail("expected drop") } XCTAssertNotNil(log) @@ -50,8 +50,71 @@ final class HIDDeliveryGateTests: XCTestCase { func testBootingAndUnknownStatesAreNotBooted() { let booting = self.booting - XCTAssertNotEqual(HIDDeliveryGate { booting }.admit(), .deliver) + XCTAssertNotEqual(HIDDeliveryGate { booting }.admit(), .deliver(reconnect: false)) guard case .drop(let log) = HIDDeliveryGate(readState: { 99 }).admit() else { return XCTFail("expected drop") } XCTAssertEqual(log, "[hid] Dropping input: simulator is state 99, not Booted") } + + // MARK: - Reconnect after the device comes back + + func testReturnToBootedAfterADropAsksForOneReconnect() { + // The cached SimDeviceLegacyHIDClient's port died with the old boot; + // it keeps failing with HIDError 3 even once the device reads Booted. + var state = booted + let gate = HIDDeliveryGate { state } + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) + state = shuttingDown + _ = gate.admit() + state = shutdown + _ = gate.admit() + state = booting + _ = gate.admit() + state = booted + XCTAssertEqual(gate.admit(), .deliver(reconnect: true)) + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) + } + + func testStateNotificationWithoutAnyInputStillAsksForReconnect() { + // Shutdown + boot with no input in between: admit() only ever sees + // Booted, so the device_state notification is the signal. + let gate = HIDDeliveryGate { 3 } + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) + gate.noteNotification(["notification": "device_state", "new_state": NSNumber(value: shuttingDown), "prev_state": NSNumber(value: booted)]) + gate.noteNotification(["notification": "device_state", "new_state": NSNumber(value: booted), "prev_state": NSNumber(value: booting)]) + XCTAssertEqual(gate.admit(), .deliver(reconnect: true)) + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) + } + + func testUnrelatedNotificationsDoNotReconnect() { + let gate = HIDDeliveryGate { 3 } + gate.noteNotification(["notification": "availableDevices_changed"]) + gate.noteNotification(["notification": "device_state", "new_state": NSNumber(value: booted)]) + gate.noteNotification(["notification": "SimDeviceNotificationType_BootStatus", "new_state": NSNumber(value: shutdown)]) + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) + } + + func testClientDisconnectAsksForReconnectEvenWithUnreadableState() { + let gate = HIDDeliveryGate { nil } + gate.noteClientDisconnected() + XCTAssertEqual(gate.admit(), .deliver(reconnect: true)) + XCTAssertEqual(gate.admit(), .deliver(reconnect: false)) + } + + func testReconnectIsHeldUntilTheDeviceIsBooted() { + var state = shutdown + let gate = HIDDeliveryGate { state } + gate.noteClientDisconnected() + guard case .drop = gate.admit() else { return XCTFail("expected drop") } + state = booted + XCTAssertEqual(gate.admit(), .deliver(reconnect: true)) + } + + func testOnlyHIDError3CountsAsDisconnected() { + let domain = "SimulatorKit.SimDeviceLegacyHIDClient.HIDError" + XCTAssertTrue(HIDDeliveryGate.isClientDisconnected(domain: domain, code: 3)) + // HIDError 2 shows up for a fresh client while the guest is still + // finishing boot; the same client works seconds later. + XCTAssertFalse(HIDDeliveryGate.isClientDisconnected(domain: domain, code: 2)) + XCTAssertFalse(HIDDeliveryGate.isClientDisconnected(domain: NSPOSIXErrorDomain, code: 3)) + } } From c57dfde9dcc420264f8b4cce3c343094ca4c4989 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 09:42:48 -0800 Subject: [PATCH 04/13] test(hid): cover reboot in the shutdown e2e and run it last in CI The e2e now drives a foreground server, which stays up across the shutdown. It asserts that the tap fails while the server still answers (no "No serve-sim server running", process alive). Then it boots the same simulator and requires a successful tap plus exactly one reconnect line in the server log. It was listed for CI but always skipped there. It is now SIM_SHUTDOWN_E2E_TEST_FILE, outside SIM_E2E_TEST_FILES, and run-sim-e2e.ts runs it after every other Darwin test with SERVE_SIM_E2E_SHUTDOWN_UDID set to the CI-owned simulator. The workflow shuts that simulator down afterwards anyway. ci-test-plan.test pins the ordering and the opt-in. --- packages/serve-sim/scripts/run-sim-e2e.ts | 24 ++++- .../src/__tests__/ci-test-plan.test.ts | 20 +++- .../__tests__/hid-after-shutdown.e2e.test.ts | 95 +++++++++++++++---- packages/serve-sim/src/ci-test-plan.ts | 12 ++- 4 files changed, 124 insertions(+), 27 deletions(-) diff --git a/packages/serve-sim/scripts/run-sim-e2e.ts b/packages/serve-sim/scripts/run-sim-e2e.ts index 234904de1..48f702d76 100755 --- a/packages/serve-sim/scripts/run-sim-e2e.ts +++ b/packages/serve-sim/scripts/run-sim-e2e.ts @@ -6,12 +6,15 @@ * stays serial (`--max-concurrency=1`) just like sim-backed e2e. E2e files * run one at a time; a failure reboots the shared simulator and retries that * file once so a wedged finger / native crash does not force a full-tree rerun. + * The shutdown e2e goes last because it shuts the simulator down and boots it + * again; it is opted in here on the CI-owned simulator only. */ import { spawnSync } from "child_process"; import { resolve } from "path"; import { DARWIN_INTEGRATION_TEST_FILES, SIM_E2E_TEST_FILES, + SIM_SHUTDOWN_E2E_TEST_FILE, } from "../src/ci-test-plan"; const repoRoot = resolve(import.meta.dir, "../../.."); @@ -19,11 +22,15 @@ const udid = process.env.UDID ?? ""; const serialArgs = ["--max-concurrency=1"]; const failed: string[] = []; -function runBunTest(files: readonly string[], extraArgs: string[] = []): number { +function runBunTest( + files: readonly string[], + extraArgs: string[] = [], + env: NodeJS.ProcessEnv = process.env, +): number { const result = spawnSync("bun", ["test", ...extraArgs, ...files], { cwd: repoRoot, stdio: "inherit", - env: process.env, + env, }); return result.status ?? 1; } @@ -85,6 +92,19 @@ for (const file of SIM_E2E_TEST_FILES) { failed.push(file); } +// Last: it shuts the simulator down. A failure gets the same reboot + one retry. +if (udid) { + const file = SIM_SHUTDOWN_E2E_TEST_FILE; + const env = { ...process.env, SERVE_SIM_E2E_SHUTDOWN_UDID: udid }; + console.log(`\n=== sim e2e ${file} (shuts down ${udid}) ===`); + if (runBunTest([file], serialArgs, env) !== 0) { + console.warn(`::warning title=sim e2e retry::${file} failed; rebooting and retrying once`); + if (!rebootSimulator() || runBunTest([file], serialArgs, env) !== 0) failed.push(file); + } +} else { + console.warn(`UDID unset; skipping ${SIM_SHUTDOWN_E2E_TEST_FILE}`); +} + if (failed.length > 0) { console.error(`Darwin tests failed after retry:\n${failed.map((f) => ` ${f}`).join("\n")}`); process.exit(1); diff --git a/packages/serve-sim/src/__tests__/ci-test-plan.test.ts b/packages/serve-sim/src/__tests__/ci-test-plan.test.ts index eacab3000..51675f413 100644 --- a/packages/serve-sim/src/__tests__/ci-test-plan.test.ts +++ b/packages/serve-sim/src/__tests__/ci-test-plan.test.ts @@ -6,6 +6,7 @@ import { join } from "path"; import { DARWIN_INTEGRATION_TEST_FILES, SIM_E2E_TEST_FILES, + SIM_SHUTDOWN_E2E_TEST_FILE, isDarwinSkipPath, isDarwinTestFile, needsDarwinE2E, @@ -23,7 +24,7 @@ function actionYml(): string { describe("Darwin vs unit test plan", () => { test("every listed Darwin file exists", () => { - for (const file of [...SIM_E2E_TEST_FILES, ...DARWIN_INTEGRATION_TEST_FILES]) { + for (const file of [...SIM_E2E_TEST_FILES, ...DARWIN_INTEGRATION_TEST_FILES, SIM_SHUTDOWN_E2E_TEST_FILE]) { expect(existsSync(join(REPO, file))).toBe(true); } }); @@ -31,6 +32,7 @@ describe("Darwin vs unit test plan", () => { test("listed files are classified as Darwin tests", () => { for (const file of SIM_E2E_TEST_FILES) expect(isDarwinTestFile(file)).toBe(true); expect(isDarwinTestFile(DARWIN_INTEGRATION_TEST_FILES[0]!)).toBe(true); + expect(isDarwinTestFile(SIM_SHUTDOWN_E2E_TEST_FILE)).toBe(true); expect(isDarwinTestFile("packages/serve-sim/src/__tests__/ports.test.ts")).toBe(false); }); @@ -73,9 +75,23 @@ describe("CI workflow factory invariants", () => { expect(runner).toContain("Simulator reboot failed; not retrying"); }); + test("the shutdown e2e runs last, opted in on the CI-owned simulator", () => { + // It shuts down and reboots its simulator, so nothing may run after it, and + // without SERVE_SIM_E2E_SHUTDOWN_UDID it would only ever skip. + expect(SIM_E2E_TEST_FILES as readonly string[]).not.toContain(SIM_SHUTDOWN_E2E_TEST_FILE); + const runner = readFileSync(join(REPO, "packages/serve-sim/scripts/run-sim-e2e.ts"), "utf-8"); + const optIn = runner.indexOf("SERVE_SIM_E2E_SHUTDOWN_UDID: udid"); + expect(optIn).toBeGreaterThan(runner.indexOf("for (const file of SIM_E2E_TEST_FILES)")); + expect(optIn).toBeGreaterThan(runner.indexOf("for (const file of DARWIN_INTEGRATION_TEST_FILES)")); + expect(runner.indexOf("SIM_SHUTDOWN_E2E_TEST_FILE", optIn - 400)).toBeGreaterThan(-1); + // The workflow shuts that simulator down afterwards regardless. + const sim = workflow("sim-test.yml"); + expect(sim).toMatch(/if: always\(\) && steps\.ci-build\.outputs\.udid != ''\s*\n\s*run: xcrun simctl shutdown "\$\{\{ steps\.ci-build\.outputs\.udid \}\}"/); + }); + test("sim-test.yml path filters include every Darwin test file and exclude client-only", () => { const sim = workflow("sim-test.yml"); - for (const file of [...SIM_E2E_TEST_FILES, ...DARWIN_INTEGRATION_TEST_FILES]) { + for (const file of [...SIM_E2E_TEST_FILES, ...DARWIN_INTEGRATION_TEST_FILES, SIM_SHUTDOWN_E2E_TEST_FILE]) { expect(sim).toContain(file); } expect(sim).toContain("packages/serve-sim/src/*.ts"); diff --git a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts index 72252e1e4..ae0c07e40 100644 --- a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -1,45 +1,79 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; -import { execFileSync, spawn, spawnSync } from "child_process"; +import { type ChildProcess, execFileSync, spawn, spawnSync } from "child_process"; import { existsSync } from "fs"; import { join } from "path"; /** * After `simctl shutdown`, SimDeviceLegacyHIDClient keeps accepting sends, so - * `serve-sim tap` exited 0 for ~5-15s — until the detached server's - * --exit-on-simulator-shutdown watcher exited. The injector now drops input once - * SimDevice.state leaves Booted, so the CLI fails within ~1s while the server is - * still up. + * `serve-sim tap` exited 0 until the server went away. Its port also stays dead + * after the same device boots again, so a server that stayed up (foreground, + * not --detach) acked taps that never reached the guest. The injector now + * drops input while the device isn't Booted and rebuilds the client when it + * comes back. * - * Opt-in because it shuts the simulator down: set SERVE_SIM_E2E_SHUTDOWN_UDID to - * a booted (or bootable) iOS simulator this test may shut down — never a shared one. + * Opt-in because it shuts the simulator down and boots it again: set + * SERVE_SIM_E2E_SHUTDOWN_UDID to an iOS simulator this test may restart, never a + * shared one. CI runs it last on its own simulator (scripts/run-sim-e2e.ts). */ const CLI = join(import.meta.dir, "../../dist/serve-sim.js"); const udid = process.env.SERVE_SIM_E2E_SHUTDOWN_UDID; const describeIfOptedIn = udid && existsSync(CLI) ? describe : describe.skip; +const RECONNECTED = "[hid] Simulator Booted again, reconnected HID client"; +const NO_SERVER = "No serve-sim server running"; function tap(): { status: number | null; stderr: string } { const r = spawnSync("node", [CLI, "tap", "0.97", "0.03", "-d", udid!], { encoding: "utf-8", timeout: 15_000 }); return { status: r.status, stderr: r.stderr ?? "" }; } -describeIfOptedIn(`HID input after simctl shutdown (${udid ?? ""})`, () => { +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** Boot and wait. No `bootstatus -b`: on Xcode 27 it can stay blocked once Booted. */ +function bootAndWait(): void { + spawnSync("xcrun", ["simctl", "boot", udid!], { stdio: "ignore" }); + execFileSync("xcrun", ["simctl", "bootstatus", udid!], { stdio: "ignore", timeout: 120_000 }); +} + +async function tapUntilOk(timeoutMs: number): Promise<{ status: number | null; stderr: string }> { + const deadline = Date.now() + timeoutMs; + let last = tap(); + while (last.status !== 0 && Date.now() < deadline) { + await sleep(500); + last = tap(); + } + return last; +} + +describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? ""})`, () => { + let server: ChildProcess | undefined; + let serverLog = ""; + beforeAll(async () => { - spawnSync("xcrun", ["simctl", "boot", udid!], { stdio: "ignore" }); - execFileSync("xcrun", ["simctl", "bootstatus", udid!, "-b"], { stdio: "ignore", timeout: 120_000 }); + bootAndWait(); try { execFileSync("node", [CLI, "--kill", udid!], { stdio: "pipe" }); } catch {} const port = 40_000 + Math.floor(Math.random() * 20_000); - const detach = spawnSync("node", [CLI, "--detach", "-p", String(port), udid!], { - encoding: "utf-8", stdio: ["ignore", "pipe", "inherit"], timeout: 45_000, - }); - if (detach.status !== 0) throw new Error(`serve-sim --detach failed: ${detach.stdout}`); - }, 180_000); + // Foreground (no --detach): unlike a detached helper it has no + // --exit-on-simulator-shutdown watcher, so it stays up across the reboot. + server = spawn("node", [CLI, udid!, "--port", String(port)], { stdio: ["ignore", "pipe", "pipe"] }); + server.stdout!.on("data", (d) => { serverLog += d; }); + server.stderr!.on("data", (d) => { serverLog += d; }); + const ready = await tapUntilOk(45_000); + if (ready.status !== 0) throw new Error(`serve-sim server never accepted a tap: ${ready.stderr}\n${serverLog}`); + }, 240_000); - afterAll(() => { + afterAll(async () => { + if (server && server.exitCode === null) { + server.kill("SIGTERM"); + await Promise.race([new Promise((r) => server!.once("exit", r)), sleep(5_000)]); + if (server.exitCode === null) server.kill("SIGKILL"); + } try { execFileSync("node", [CLI, "--kill", udid!], { stdio: "pipe" }); } catch {} - }, 30_000); + // Leave the simulator booted, as the test found it. + bootAndWait(); + }, 180_000); - test("tap fails with an undelivered error within ~1s of shutdown", async () => { + test("tap fails with an undelivered error within 2s of shutdown, while the server is up", async () => { expect(tap().status).toBe(0); const shutdown = spawn("xcrun", ["simctl", "shutdown", udid!], { stdio: "ignore" }); @@ -51,10 +85,29 @@ describeIfOptedIn(`HID input after simctl shutdown (${udid ?? ""})`, () } await new Promise((r) => shutdown.on("exit", r)); - // The server must still be answering — a "No serve-sim server" failure - // would only mean the shutdown watcher already exited. if (!failure) throw new Error("every tap in the 2s after `simctl shutdown` exited 0"); - expect(failure.stderr).toContain("could not deliver the tap"); expect(failure.afterMs).toBeLessThan(2_000); + // The injector refused the tap, so the server was answering. + expect(failure.stderr).toContain("could not deliver the tap"); + expect(failure.stderr).not.toContain(NO_SERVER); + expect(server!.exitCode).toBeNull(); + // It still answers once the device is fully down. + const down = tap(); + expect(down.status).not.toBe(0); + expect(down.stderr).toContain("could not deliver the tap"); + expect(down.stderr).not.toContain(NO_SERVER); }, 60_000); + + test("after the same simulator boots again, the server rebuilds its HID client", async () => { + bootAndWait(); + const r = await tapUntilOk(30_000); + expect(r.stderr).not.toContain(NO_SERVER); + expect(r.status).toBe(0); + expect(server!.exitCode).toBeNull(); + // Without the rebuild the tap above also exits 0 but never reaches the guest. + const deadline = Date.now() + 5_000; + while (!serverLog.includes(RECONNECTED) && Date.now() < deadline) await sleep(100); + expect(serverLog).toContain(RECONNECTED); + expect(serverLog.split(RECONNECTED).length - 1).toBe(1); + }, 180_000); }); diff --git a/packages/serve-sim/src/ci-test-plan.ts b/packages/serve-sim/src/ci-test-plan.ts index 9a0d2e14a..3f3f7c71f 100644 --- a/packages/serve-sim/src/ci-test-plan.ts +++ b/packages/serve-sim/src/ci-test-plan.ts @@ -9,8 +9,6 @@ export const SIM_E2E_TEST_FILES = [ "packages/serve-sim/src/__tests__/accessibility-endpoint.test.ts", "packages/serve-sim/src/__tests__/avcc-stream-endpoint.test.ts", "packages/serve-sim/src/__tests__/camera-connections.e2e.test.ts", - // Opt-in (SERVE_SIM_E2E_SHUTDOWN_UDID): it shuts its simulator down. - "packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts", "packages/serve-sim/src/__tests__/hid-malformed-input.test.ts", "packages/serve-sim/src/__tests__/idle-floor.test.ts", "packages/serve-sim/src/__tests__/permissions.e2e.test.ts", @@ -18,6 +16,15 @@ export const SIM_E2E_TEST_FILES = [ "packages/serve-sim/src/__tests__/ui-settings.e2e.test.ts", ] as const; +/** + * Shuts its simulator down and boots it again, so it is opt-in + * (SERVE_SIM_E2E_SHUTDOWN_UDID). The runner runs it after every other Darwin + * test, opted in on the CI-owned simulator, which the workflow shuts down + * afterwards anyway. + */ +export const SIM_SHUTDOWN_E2E_TEST_FILE = + "packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts"; + export const DARWIN_INTEGRATION_TEST_FILES = [ "packages/serve-sim/src/__tests__/shm-probe.integration.test.ts", "packages/serve-sim/src/__tests__/duo-renderer.integration.test.ts", @@ -27,6 +34,7 @@ export const DARWIN_INTEGRATION_TEST_FILES = [ const DARWIN_TEST_FILE_SET = new Set([ ...SIM_E2E_TEST_FILES, ...DARWIN_INTEGRATION_TEST_FILES, + SIM_SHUTDOWN_E2E_TEST_FILE, ]); export function isDarwinTestFile(file: string): boolean { From 1a9d4745d9f2a4cef8f5c46ea350f885fd81d0a0 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 15:33:34 -0800 Subject: [PATCH 05/13] fix(hid): cap blocked SimDevice.state reads and close review gaps simctl shutdown can hold a CoreSimulator lock so a synchronous SimDevice.state read stalls the first post-shutdown tap (6312ms on a macos-26 CI runner). The pre-fix send path was fire-and-forget and returned immediately, so the hang is the new KVC read on the injector queue, not a slow send. BoundedStateReader now probes state off that queue, waits at most 100ms, coalesces overlapping probes, and the gate drops the input on timeout. The e2e bound stays at 2s. Also, from review-hid-b: - HIDError 2 (guest still starting) sets a not-ready flag on the current client. Later input is dropped until a send completes without error or 30s pass, instead of being acked as delivered. - The device notification handler is unregistered if close() is never called, when the JS handle is released. - After reboot the e2e launches Settings, taps General, and asserts the About row appears, so a rebuilt-but-dead client would fail the test. Swift HID/gate/reader tests 33/0; typecheck and lint clean. The 2s shutdown e2e bound is unchanged. --- .../Sources/SimNative/HIDInjector.swift | 64 +++++++++++--- .../SimNativeSupport/BoundedStateReader.swift | 71 +++++++++++++++ .../SimNativeSupport/HIDClientChannel.swift | 72 ++++++++++++++-- .../SimNativeSupport/HIDDeliveryGate.swift | 72 +++++++++++++--- .../BoundedStateReaderTests.swift | 86 +++++++++++++++++++ .../HIDClientChannelTests.swift | 48 ++++++++++- .../HIDDeliveryGateTests.swift | 37 ++++++++ .../__tests__/hid-after-shutdown.e2e.test.ts | 39 ++++++++- 8 files changed, 452 insertions(+), 37 deletions(-) create mode 100644 packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift create mode 100644 packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index a8e5d45d2..8cfd61bd6 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -55,7 +55,6 @@ actor HIDInjector { /// and runs on `queue`, which is this actor's executor. private var completion: AnyObject? private weak var completionClient: NSObject? - private var notificationHandlerID: UInt? private var simDevice: NSObject? private let springBoardLauncher = SpringBoardLauncher() private var deviceHubKeyboardBridge: DeviceHubKeyboardBridge? @@ -146,10 +145,14 @@ actor HIDInjector { } - // Read on every admit (a plain in-process KVC read). - let gate = device.responds(to: NSSelectorFromString("state")) - ? HIDDeliveryGate { (device.value(forKey: "state") as? NSNumber)?.intValue } - : HIDDeliveryGate { nil } + // Read on every admit, with a 100ms cap. The KVC read is usually + // cheap, but `simctl shutdown` can hold a CoreSimulator lock for + // several seconds (6.3s on macos-26 CI); a synchronous read on this + // actor would hang the tap ack that long. + let readState: () -> Int? = device.responds(to: NSSelectorFromString("state")) + ? { (device.value(forKey: "state") as? NSNumber)?.intValue } + : { nil } + let gate = HIDDeliveryGate(readState: readState, timeout: HIDDeliveryGate.stateReadTimeout) // Thrown errors here fail setup, as before. let firstClient = try Self.makeHIDClient(device: device) let duo = duoBridge @@ -212,10 +215,37 @@ actor HIDInjector { return clientObj } + /// Holds a `SimDevice` notification registration so it is released even + /// if `close()` is never called (the JS `SimHID` handle can be dropped + /// by GC). The actor stores this object; `deinit` unregisters. + private final class NotificationSubscription { + private let device: NSObject + private var id: UInt? + + init(device: NSObject) { self.device = device } + + func setID(_ id: UInt) { self.id = id } + + func unregister() { + let sel = NSSelectorFromString("unregisterNotificationHandler:error:") + guard let id, device.responds(to: sel) else { return } + self.id = nil + typealias UnregisterFunc = @convention(c) (AnyObject, Selector, UInt, AutoreleasingUnsafeMutablePointer) -> ObjCBool + var error: NSError? + _ = unsafeBitCast(device.method(for: sel), to: UnregisterFunc.self)(device, sel, id, &error) + } + + deinit { unregister() } + } + + private var notifications: NotificationSubscription? + /// Watch `device_state` so a shutdown + boot with no input in between still /// rebuilds the client: then the gate only ever reads Booted. The handler /// runs on `queue`, this actor's executor, so it never races the channel. private func registerStateNotifications(device: NSObject) { + notifications?.unregister() + notifications = nil let sel = NSSelectorFromString("registerNotificationHandlerOnQueue:handler:") guard device.responds(to: sel) else { return } let channel = self.channel @@ -223,18 +253,17 @@ actor HIDInjector { guard let info = info as? [AnyHashable: Any] else { return } channel?.noteDeviceNotification(info) } + let sub = NotificationSubscription(device: device) typealias RegisterFunc = @convention(c) (AnyObject, Selector, AnyObject, AnyObject) -> UInt - notificationHandlerID = unsafeBitCast(device.method(for: sel), to: RegisterFunc.self)( + let id = unsafeBitCast(device.method(for: sel), to: RegisterFunc.self)( device, sel, queue, handler as AnyObject) + sub.setID(id) + notifications = sub } private func unregisterStateNotifications() { - let sel = NSSelectorFromString("unregisterNotificationHandler:error:") - guard let id = notificationHandlerID, let device = simDevice, device.responds(to: sel) else { return } - notificationHandlerID = nil - typealias UnregisterFunc = @convention(c) (AnyObject, Selector, UInt, AutoreleasingUnsafeMutablePointer) -> ObjCBool - var error: NSError? - _ = unsafeBitCast(device.method(for: sel), to: UnregisterFunc.self)(device, sel, id, &error) + notifications?.unregister() + notifications = nil } /// The completion block for sends through `client`. A HIDError 3 from it @@ -244,9 +273,16 @@ actor HIDInjector { private func completion(for client: NSObject) -> AnyObject { if let completion, completionClient === client { return completion } let channel = self.channel + // Completions run on `queue` (this actor's executor). They are not + // awaited: waiting would add the HID round trip to every send (measured + // as no extra cost with a nil completion vs this fire-and-forget block). let block: @convention(block) (NSError?) -> Void = { [weak channel, weak client] error in - guard let error, let channel, let client else { return } - channel.clientReported(client, domain: error.domain, code: error.code) + guard let channel, let client else { return } + if let error { + channel.clientReported(client, domain: error.domain, code: error.code) + } else { + channel.clientReportedSuccess(client) + } } completion = block as AnyObject completionClient = client diff --git a/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift new file mode 100644 index 000000000..e2d73ece0 --- /dev/null +++ b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift @@ -0,0 +1,71 @@ +import Foundation + +/// Runs a `SimDevice.state` probe (or a test double) without stalling the HID +/// input path. +/// +/// `-[SimDevice state]` is usually a cheap in-process KVC read, and locally it +/// leaves Booted within ~100ms of `simctl shutdown`. On some hosts the same +/// read blocks for several seconds because shutdown holds a CoreSimulator +/// lock — CI on macos-26 recorded the first post-shutdown `tap` returning +/// only after 6.3s. A synchronous read on the injector's actor queue would +/// hang the ack that long. This reader runs the probe on a private queue, +/// waits up to `timeout`, coalesces overlapping probes onto one in-flight +/// read, and reports `.timedOut` so the gate can drop the input instead. +public final class BoundedStateReader: @unchecked Sendable { + public enum Probe: Equatable, Sendable { + case ready(Int?) + case timedOut + } + + public static let defaultTimeout: TimeInterval = 0.1 + + private let read: () -> Int? + private let timeout: TimeInterval + private let queue: DispatchQueue + private let lock = NSCondition() + private var inFlight = false + private var finished = false + private var value: Int? + private var timedOutThisFlight = false + + public init(timeout: TimeInterval = BoundedStateReader.defaultTimeout, read: @escaping () -> Int?) { + self.timeout = timeout + self.read = read + self.queue = DispatchQueue(label: "hid-delivery-gate.state", qos: .userInteractive) + } + + public func probe() -> Probe { + lock.lock() + defer { lock.unlock() } + + if !inFlight { + inFlight = true + finished = false + timedOutThisFlight = false + value = nil + let read = self.read + queue.async { [self] in + let result = read() + self.lock.lock() + self.value = result + self.finished = true + self.inFlight = false + self.lock.broadcast() + self.lock.unlock() + } + } else if timedOutThisFlight && !finished { + // A earlier caller already waited out this flight; don't pile + // another `timeout` onto every subsequent tap. + return .timedOut + } + + let deadline = Date().addingTimeInterval(timeout) + while !finished { + if !lock.wait(until: deadline) { + timedOutThisFlight = true + return .timedOut + } + } + return .ready(value) + } +} diff --git a/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift index 89827673c..55d3ffe2b 100644 --- a/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift @@ -14,29 +14,43 @@ import Foundation /// and the device's notifications). public final class HIDClientChannel { public static var reconnectedMessage: String { "[hid] Simulator Booted again, reconnected HID client" } + public static var notReadyMessage: String { "[hid] Dropping input: HID client is not ready (HIDError 2, guest still starting)" } + public static var notReadyLimit: TimeInterval { 30 } private let gate: HIDDeliveryGate private let makeClient: () -> Client? private let log: (String) -> Void private let didReconnect: () -> Void + private let now: () -> TimeInterval + private let notReadyLimit: TimeInterval + private var notReady = false + private var notReadySince: TimeInterval? + private var loggedNotReady = false public private(set) var client: Client? public init( gate: HIDDeliveryGate, connect: @escaping () -> Client?, log: @escaping (String) -> Void, - didReconnect: @escaping () -> Void = {} + didReconnect: @escaping () -> Void = {}, + now: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }, + notReadyLimit: TimeInterval = HIDClientChannel.notReadyLimit ) { self.gate = gate self.makeClient = connect self.log = log self.didReconnect = didReconnect + self.now = now + self.notReadyLimit = notReadyLimit } /// Create (or replace) the client. Returns whether one exists now. @discardableResult public func connect() -> Bool { client = makeClient() + notReady = false + notReadySince = nil + loggedNotReady = false return client != nil } @@ -44,6 +58,9 @@ public final class HIDClientChannel { /// its error can fail setup). public func adopt(_ client: Client) { self.client = client + notReady = false + notReadySince = nil + loggedNotReady = false } /// Whether input may go to the guest now. Rebuilds the client first when @@ -54,7 +71,7 @@ public final class HIDClientChannel { if let message { log(message) } return false case .deliver(reconnect: false): - return true + return admitReady() case .deliver(reconnect: true): guard connect() else { // Try again on the next input rather than sending through a dead port. @@ -64,7 +81,7 @@ public final class HIDClientChannel { } log(Self.reconnectedMessage) didReconnect() - return true + return admitReady() } } @@ -91,15 +108,56 @@ public final class HIDClientChannel { } /// A send completion from `reporter`. A disconnect error from the - /// current client makes the next input rebuild it. Late errors from a - /// client that was already replaced are ignored. + /// current client makes the next input rebuild it. A not-ready error + /// (HIDError 2) drops later input until a send completes without error + /// or `notReadyLimit` has passed. Late errors from a client that was + /// already replaced are ignored. public func clientReported(_ reporter: Client, domain: String, code: Int) { - guard reporter === client, HIDDeliveryGate.isClientDisconnected(domain: domain, code: code) else { return } - gate.noteClientDisconnected() + guard reporter === client else { return } + if HIDDeliveryGate.isClientDisconnected(domain: domain, code: code) { + gate.noteClientDisconnected() + notReady = false + notReadySince = nil + loggedNotReady = false + return + } + guard HIDDeliveryGate.isClientNotReady(domain: domain, code: code) else { return } + if !notReady { + notReady = true + notReadySince = now() + loggedNotReady = false + } + } + + /// A successful send completion from `reporter` clears the not-ready + /// flag: the guest accepted input, so later sends can be acked again. + public func clientReportedSuccess(_ reporter: Client) { + guard reporter === client else { return } + notReady = false + notReadySince = nil + loggedNotReady = false } /// See `HIDDeliveryGate.noteNotification`. public func noteDeviceNotification(_ info: [AnyHashable: Any]) { gate.noteNotification(info) } + + /// After the gate has admitted the device as Booted, drop input while + /// the current client is still reporting HIDError 2 (iOS starting up). + private func admitReady() -> Bool { + guard notReady else { return true } + let started = notReadySince ?? now() + if now() - started >= notReadyLimit { + notReady = false + notReadySince = nil + loggedNotReady = false + return true + } + if !loggedNotReady { + log(Self.notReadyMessage) + loggedNotReady = true + } + return false + } } diff --git a/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift index 8e2dd484a..2c441a362 100644 --- a/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift @@ -7,8 +7,14 @@ import Foundation /// `simctl shutdown` (its completion only reports "Mach port invalid, device /// disconnected"), so without this check `serve-sim tap/button/gesture` acked /// success until the detached server's shutdown watcher exited 5–15s later. -/// `SimDevice.state` leaves Booted within ~100ms of the shutdown starting and -/// is a cheap in-process read, so gating on it adds no measurable latency. +/// +/// `SimDevice.state` usually leaves Booted within ~100ms of shutdown starting +/// and is a cheap in-process read. On some hosts, though, the same read blocks +/// for several seconds because `simctl shutdown` holds a CoreSimulator lock +/// (6.3s for the first post-shutdown `tap` on a macos-26 CI runner). When a +/// timeout is set, `admit` uses `BoundedStateReader` so that stall becomes a +/// drop instead of a hung ack. Notifications still catch a shutdown + boot +/// with no input in between. /// /// The client also never recovers: once the device has left Booted, every /// later send fails with HIDError 3, even after the same device boots again. @@ -28,27 +34,54 @@ public final class HIDDeliveryGate { /// CoreSimulator's `SimDeviceState` raw value for a booted device. public static let bootedState = 3 + /// How long `admit` will wait for `SimDevice.state` when constructed + /// with a timeout. Kept short so a stuck read cannot miss the 2s e2e bound. + public static let stateReadTimeout: TimeInterval = BoundedStateReader.defaultTimeout + private let readState: () -> Int? + private let reader: BoundedStateReader? private var lastLoggedState: Int? + private var loggedTimeout = false private var needsReconnect = false /// `readState` returns the raw `SimDeviceState`, or nil when it can't be - /// read (then input is delivered as before). + /// read (then input is delivered as before). The probe runs synchronously + /// on the caller's queue; tests use this form. public init(readState: @escaping () -> Int?) { self.readState = readState + self.reader = nil + } + + /// Like `init(readState:)`, but each `admit` runs the probe on a private + /// queue and drops the input if it does not finish within `timeout`. + public init(readState: @escaping () -> Int?, timeout: TimeInterval) { + self.readState = readState + self.reader = BoundedStateReader(timeout: timeout, read: readState) } public func admit() -> Decision { - if let state = readState(), state != Self.bootedState { + switch currentState() { + case .timedOut: needsReconnect = true - guard state != lastLoggedState else { return .drop(log: nil) } - lastLoggedState = state - return .drop(log: "[hid] Dropping input: simulator is \(Self.describe(state)), not Booted") + if loggedTimeout { return .drop(log: nil) } + loggedTimeout = true + return .drop(log: "[hid] Dropping input: simulator state could not be read in time") + case .ready(let state?): + if state != Self.bootedState { + needsReconnect = true + loggedTimeout = false + guard state != lastLoggedState else { return .drop(log: nil) } + lastLoggedState = state + return .drop(log: "[hid] Dropping input: simulator is \(Self.describe(state)), not Booted") + } + fallthrough + case .ready(nil): + lastLoggedState = nil + loggedTimeout = false + let reconnect = needsReconnect + needsReconnect = false + return .deliver(reconnect: reconnect) } - lastLoggedState = nil - let reconnect = needsReconnect - needsReconnect = false - return .deliver(reconnect: reconnect) } /// The HID client reported it can no longer reach the device. @@ -67,12 +100,20 @@ public final class HIDDeliveryGate { } /// SimulatorKit's `SimDeviceLegacyHIDClient.HIDError` 3 ("Mach port - /// invalid, device disconnected"). Error 2 is not included: a new client - /// reports it while the guest is still finishing boot and then works. + /// invalid, device disconnected"). Error 2 is not a disconnect: a new + /// client reports it while the guest is still finishing boot and then + /// works. `HIDClientChannel` keeps a not-ready flag for error 2 and + /// drops input until a send completes without error, or ~30s pass, so + /// those sends are not acked as delivered. public static func isClientDisconnected(domain: String, code: Int) -> Bool { code == 3 && domain.hasSuffix("SimDeviceLegacyHIDClient.HIDError") } + /// See `isClientDisconnected`. HIDError 2 while the guest is starting. + public static func isClientNotReady(domain: String, code: Int) -> Bool { + code == 2 && domain.hasSuffix("SimDeviceLegacyHIDClient.HIDError") + } + static func describe(_ state: Int) -> String { switch state { case 0: return "Creating (state 0)" @@ -82,4 +123,9 @@ public final class HIDDeliveryGate { default: return "state \(state)" } } + + private func currentState() -> BoundedStateReader.Probe { + if let reader { return reader.probe() } + return .ready(readState()) + } } diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift new file mode 100644 index 000000000..b61b1113b --- /dev/null +++ b/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift @@ -0,0 +1,86 @@ +import XCTest +@testable import SimNativeSupport + +final class BoundedStateReaderTests: XCTestCase { + func testInstantReadIsReady() { + let reader = BoundedStateReader(timeout: 0.1) { 3 } + XCTAssertEqual(reader.probe(), .ready(3)) + XCTAssertEqual(reader.probe(), .ready(3)) + } + + func testNilStateIsReadyNil() { + let reader = BoundedStateReader { nil } + XCTAssertEqual(reader.probe(), .ready(nil)) + } + + func testStuckReadTimesOutWithoutWaitingForTheValue() { + let hold = NSCondition() + var stuck = true + let reader = BoundedStateReader(timeout: 0.05) { + hold.lock() + while stuck { hold.wait() } + hold.unlock() + return 4 + } + + let t0 = Date() + XCTAssertEqual(reader.probe(), .timedOut) + XCTAssertLessThan(Date().timeIntervalSince(t0), 0.2) + + // A second probe of the same in-flight read returns immediately. + let t1 = Date() + XCTAssertEqual(reader.probe(), .timedOut) + XCTAssertLessThan(Date().timeIntervalSince(t1), 0.03) + + hold.lock() + stuck = false + hold.broadcast() + hold.unlock() + + // Once the stuck read finishes, the next probe starts a fresh, + // unblocked read and returns the value. + let deadline = Date().addingTimeInterval(1) + var last: BoundedStateReader.Probe? + while Date() < deadline { + last = reader.probe() + if last == .ready(4) { break } + Thread.sleep(forTimeInterval: 0.01) + } + XCTAssertEqual(last, .ready(4)) + } + + func testOverlappingProbesShareOneRead() { + let started = DispatchSemaphore(value: 0) + let hold = DispatchSemaphore(value: 0) + var calls = 0 + let reader = BoundedStateReader(timeout: 1) { + calls += 1 + started.signal() + hold.wait() + return 1 + } + + let q = DispatchQueue.global(qos: .userInitiated) + var first: BoundedStateReader.Probe? + var second: BoundedStateReader.Probe? + let firstDone = DispatchSemaphore(value: 0) + let secondDone = DispatchSemaphore(value: 0) + q.async { + first = reader.probe() + firstDone.signal() + } + started.wait() + q.async { + second = reader.probe() + secondDone.signal() + } + // Let the second caller join the in-flight read. + Thread.sleep(forTimeInterval: 0.05) + hold.signal() + firstDone.wait() + secondDone.wait() + XCTAssertEqual(first, .ready(1)) + XCTAssertEqual(second, .ready(1)) + XCTAssertEqual(calls, 1) + } +} diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift index 89d8fc6ef..1d14ed716 100644 --- a/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift @@ -15,6 +15,7 @@ final class HIDClientChannelTests: XCTestCase { var connectSucceeds = true var logs: [String] = [] var reconnectHooks = 0 + var now: TimeInterval = 0 lazy var channel: HIDClientChannel = { let gate = HIDDeliveryGate { [unowned self] in self.stateReads += 1 @@ -27,7 +28,9 @@ final class HIDClientChannelTests: XCTestCase { return self.connectSucceeds ? FakeClient() : nil }, log: { [unowned self] in self.logs.append($0) }, - didReconnect: { [unowned self] in self.reconnectHooks += 1 } + didReconnect: { [unowned self] in self.reconnectHooks += 1 }, + now: { [unowned self] in self.now }, + notReadyLimit: 30 ) }() @@ -126,10 +129,51 @@ final class HIDClientChannelTests: XCTestCase { func testBootErrorsDoNotRebuild() { let h = Harness(); h.setup() h.channel.clientReported(h.channel.client!, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) - XCTAssertTrue(h.channel.send { _ in true }) + // Still the same client: error 2 means "not ready", not "disconnected". + var sends = 0 + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 0) + XCTAssertEqual(h.connects, 1) + } + + func testHIDError2DropsUntilASuccessfulSend() { + let h = Harness(); h.setup() + let client = h.channel.client! + h.channel.clientReported(client, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) + var sends = 0 + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 0) + XCTAssertEqual(h.logs, [HIDClientChannel.notReadyMessage]) + h.channel.clientReportedSuccess(client) + XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 1) + XCTAssertEqual(h.connects, 1) + } + + func testHIDError2ExpiresAfterTheLimit() { + let h = Harness(); h.setup() + h.channel.clientReported(h.channel.client!, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) + h.now = 29 + XCTAssertFalse(h.channel.send { _ in true }) + h.now = 30 + var sends = 0 + XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 1) XCTAssertEqual(h.connects, 1) } + func testLateSuccessFromAReplacedClientIsIgnored() { + let h = Harness(); h.setup() + let first = h.channel.client! + h.channel.clientReported(first, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 3) + XCTAssertTrue(h.channel.send { _ in true }) // rebuilt + h.channel.clientReported(h.channel.client!, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) + h.channel.clientReportedSuccess(first) // stale success must not clear not-ready + XCTAssertFalse(h.channel.send { _ in true }) + XCTAssertEqual(h.connects, 2) + } + func testFailedReconnectReportsUndeliveredAndRetries() { let h = Harness(); h.setup() h.state = shutdown diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift index 3beee90fa..ef2f6d41c 100644 --- a/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift @@ -117,4 +117,41 @@ final class HIDDeliveryGateTests: XCTestCase { XCTAssertFalse(HIDDeliveryGate.isClientDisconnected(domain: domain, code: 2)) XCTAssertFalse(HIDDeliveryGate.isClientDisconnected(domain: NSPOSIXErrorDomain, code: 3)) } + + + func testTimedOutStateReadDropsInput() { + let hold = NSCondition() + var stuck = true + let gate = HIDDeliveryGate(readState: { + hold.lock() + while stuck { hold.wait() } + hold.unlock() + return 3 + }, timeout: 0.05) + let t0 = Date() + guard case .drop(let log) = gate.admit() else { return XCTFail("expected drop") } + XCTAssertEqual(log, "[hid] Dropping input: simulator state could not be read in time") + XCTAssertLessThan(Date().timeIntervalSince(t0), 0.2) + // Same in-flight read: no second log, still a drop, still fast. + XCTAssertEqual(gate.admit(), .drop(log: nil)) + hold.lock(); stuck = false; hold.broadcast(); hold.unlock() + // After the stuck read finishes (Booted) the next admit delivers + // and asks for a reconnect, because the timeout was treated as a trip + // out of a known-good state. + let deadline = Date().addingTimeInterval(1) + var last: HIDDeliveryGate.Decision? + while Date() < deadline { + last = gate.admit() + if case .deliver = last { break } + Thread.sleep(forTimeInterval: 0.01) + } + XCTAssertEqual(last, .deliver(reconnect: true)) + } + + func testIsClientNotReadyIsHIDError2() { + let domain = "SimulatorKit.SimDeviceLegacyHIDClient.HIDError" + XCTAssertTrue(HIDDeliveryGate.isClientNotReady(domain: domain, code: 2)) + XCTAssertFalse(HIDDeliveryGate.isClientNotReady(domain: domain, code: 3)) + XCTAssertFalse(HIDDeliveryGate.isClientNotReady(domain: NSPOSIXErrorDomain, code: 2)) + } } diff --git a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts index ae0c07e40..71167fca1 100644 --- a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -74,6 +74,10 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " }, 180_000); test("tap fails with an undelivered error within 2s of shutdown, while the server is up", async () => { + // The bound is 2s because a correct drop is fast (locally ~0.4–1.2s, + // including CLI startup). On macos-26 CI, a synchronous SimDevice.state + // read during `simctl shutdown` blocked the first tap for 6312ms; the + // gate now times that read out at 100ms, so this bound stays at 2s. expect(tap().status).toBe(0); const shutdown = spawn("xcrun", ["simctl", "shutdown", udid!], { stdio: "ignore" }); @@ -98,7 +102,7 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " expect(down.stderr).not.toContain(NO_SERVER); }, 60_000); - test("after the same simulator boots again, the server rebuilds its HID client", async () => { + test("after the same simulator boots again, a tap on the guest lands", async () => { bootAndWait(); const r = await tapUntilOk(30_000); expect(r.stderr).not.toContain(NO_SERVER); @@ -109,5 +113,38 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " while (!serverLog.includes(RECONNECTED) && Date.now() < deadline) await sleep(100); expect(serverLog).toContain(RECONNECTED); expect(serverLog.split(RECONNECTED).length - 1).toBe(1); + + // Prove the rebuilt client actually delivers: open Settings, tap General, + // and assert the General screen (About) appears in the AX tree. + try { execFileSync("xcrun", ["simctl", "terminate", udid!, "com.apple.Preferences"], { stdio: "pipe" }); } catch {} + execFileSync("xcrun", ["simctl", "launch", udid!, "com.apple.Preferences"], { stdio: "pipe", timeout: 30_000 }); + + const axText = (): { status: number | null; stdout: string } => { + const s = spawnSync("node", [CLI, "ax", "--refs", "--text", "-d", udid!], { encoding: "utf-8", timeout: 15_000 }); + return { status: s.status, stdout: s.stdout ?? "" }; + }; + + let snapshot = ""; + const settingsDeadline = Date.now() + 20_000; + while (Date.now() < settingsDeadline) { + const s = axText(); + if (s.status === 0 && /"General"/.test(s.stdout)) { snapshot = s.stdout; break; } + await sleep(500); + } + if (!/"General"/.test(snapshot)) throw new Error(`Settings did not show a General row after launch:\n${snapshot}`); + const generalRef = snapshot.match(/(@e\d+)\s+\S+\s+"General"/)?.[1]; + if (!generalRef) throw new Error(`could not find a General ref in:\n${snapshot}`); + const tapped = spawnSync("node", [CLI, "tap", generalRef, "-d", udid!], { encoding: "utf-8", timeout: 15_000 }); + expect(tapped.status).toBe(0); + expect(tapped.stderr).not.toContain(NO_SERVER); + + let after = ""; + const generalDeadline = Date.now() + 15_000; + while (Date.now() < generalDeadline) { + const s = axText(); + if (s.status === 0 && /"About"/.test(s.stdout)) { after = s.stdout; break; } + await sleep(300); + } + if (!/"About"/.test(after)) throw new Error(`tapping General should open the General screen (About row):\n${after}`); }, 180_000); }); From ba4045257f161c91f6e9497565bbe004c5ae05db Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 18:54:52 -0800 Subject: [PATCH 06/13] fix(hid): probe while notReady so a success can clear the flag HIDError 2 set notReady, then admit() refused every send, so clientReportedSuccess never ran and input stayed blocked for 30s after boot. Allow one unacked probe send every 0.5s; a successful completion clears the flag, with the 30s limit as a backstop. A timed-out state read no longer forces a client rebuild (or Duo reset). --- .../Sources/SimNative/HIDInjector.swift | 5 + .../SimNativeSupport/BoundedStateReader.swift | 2 +- .../SimNativeSupport/HIDClientChannel.swift | 116 ++++++++++++++---- .../SimNativeSupport/HIDDeliveryGate.swift | 5 +- .../HIDClientChannelTests.swift | 29 ++++- .../HIDDeliveryGateTests.swift | 5 +- .../__tests__/hid-after-shutdown.e2e.test.ts | 20 +++ 7 files changed, 147 insertions(+), 35 deletions(-) diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index 8cfd61bd6..8622f0384 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -159,6 +159,11 @@ actor HIDInjector { channel = HIDClientChannel( gate: gate, connect: { + // makeHIDClient (initWithDevice:) is unbounded and runs on + // this actor queue. A CoreSimulator lock during shutdown can + // stall the next ack; accepted for now (the 100ms state + // probe already bounds admit). Prefer moving this off-queue + // if the hang returns. do { return try Self.makeHIDClient(device: device) } catch { print("[hid] Could not create SimDeviceLegacyHIDClient: \(error.localizedDescription)") return nil diff --git a/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift index e2d73ece0..724264d32 100644 --- a/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift +++ b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift @@ -54,7 +54,7 @@ public final class BoundedStateReader: @unchecked Sendable { self.lock.unlock() } } else if timedOutThisFlight && !finished { - // A earlier caller already waited out this flight; don't pile + // An earlier caller already waited out this flight; don't pile // another `timeout` onto every subsequent tap. return .timedOut } diff --git a/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift index 55d3ffe2b..4d2e76279 100644 --- a/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift @@ -16,6 +16,15 @@ public final class HIDClientChannel { public static var reconnectedMessage: String { "[hid] Simulator Booted again, reconnected HID client" } public static var notReadyMessage: String { "[hid] Dropping input: HID client is not ready (HIDError 2, guest still starting)" } public static var notReadyLimit: TimeInterval { 30 } + /// While not-ready, one unacked probe send is allowed this often so a + /// successful completion can clear the flag before `notReadyLimit`. + public static var notReadyProbeInterval: TimeInterval { 0.5 } + + private enum SendAdmission { + case drop + case deliver + case probe + } private let gate: HIDDeliveryGate private let makeClient: () -> Client? @@ -23,8 +32,10 @@ public final class HIDClientChannel { private let didReconnect: () -> Void private let now: () -> TimeInterval private let notReadyLimit: TimeInterval + private let notReadyProbeInterval: TimeInterval private var notReady = false private var notReadySince: TimeInterval? + private var lastNotReadyProbeAt: TimeInterval? private var loggedNotReady = false public private(set) var client: Client? @@ -34,7 +45,8 @@ public final class HIDClientChannel { log: @escaping (String) -> Void, didReconnect: @escaping () -> Void = {}, now: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }, - notReadyLimit: TimeInterval = HIDClientChannel.notReadyLimit + notReadyLimit: TimeInterval = HIDClientChannel.notReadyLimit, + notReadyProbeInterval: TimeInterval = HIDClientChannel.notReadyProbeInterval ) { self.gate = gate self.makeClient = connect @@ -42,15 +54,14 @@ public final class HIDClientChannel { self.didReconnect = didReconnect self.now = now self.notReadyLimit = notReadyLimit + self.notReadyProbeInterval = notReadyProbeInterval } /// Create (or replace) the client. Returns whether one exists now. @discardableResult public func connect() -> Bool { client = makeClient() - notReady = false - notReadySince = nil - loggedNotReady = false + clearNotReady() return client != nil } @@ -58,9 +69,7 @@ public final class HIDClientChannel { /// its error can fail setup). public func adopt(_ client: Client) { self.client = client - notReady = false - notReadySince = nil - loggedNotReady = false + clearNotReady() } /// Whether input may go to the guest now. Rebuilds the client first when @@ -86,15 +95,26 @@ public final class HIDClientChannel { } /// Gate, then hand the current client to `transmit`. False when the - /// device isn't booted, there is no client, or `transmit` failed; - /// `transmit` isn't called in the first two cases. + /// device isn't booted, there is no client, `transmit` failed, or this + /// send is a not-ready probe (never acked; its completion may clear the + /// flag). `transmit` isn't called when the device isn't booted or there + /// is no client. public func send(_ transmit: (Client) -> Bool) -> Bool { - guard admit() else { return false } + let probe: Bool + switch admitForSend() { + case .drop: + return false + case .deliver: + probe = false + case .probe: + probe = true + } guard let client else { log("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") return false } - return transmit(client) + let delivered = transmit(client) + return probe ? false : delivered } /// Gate input that doesn't go through the client (it still triggers the @@ -110,21 +130,21 @@ public final class HIDClientChannel { /// A send completion from `reporter`. A disconnect error from the /// current client makes the next input rebuild it. A not-ready error /// (HIDError 2) drops later input until a send completes without error - /// or `notReadyLimit` has passed. Late errors from a client that was - /// already replaced are ignored. + /// or `notReadyLimit` has passed, except for a periodic unacked probe + /// so that success path can actually run. Late errors from a client + /// that was already replaced are ignored. public func clientReported(_ reporter: Client, domain: String, code: Int) { guard reporter === client else { return } if HIDDeliveryGate.isClientDisconnected(domain: domain, code: code) { gate.noteClientDisconnected() - notReady = false - notReadySince = nil - loggedNotReady = false + clearNotReady() return } guard HIDDeliveryGate.isClientNotReady(domain: domain, code: code) else { return } if !notReady { notReady = true notReadySince = now() + lastNotReadyProbeAt = nil loggedNotReady = false } } @@ -133,9 +153,7 @@ public final class HIDClientChannel { /// flag: the guest accepted input, so later sends can be acked again. public func clientReportedSuccess(_ reporter: Client) { guard reporter === client else { return } - notReady = false - notReadySince = nil - loggedNotReady = false + clearNotReady() } /// See `HIDDeliveryGate.noteNotification`. @@ -143,21 +161,65 @@ public final class HIDClientChannel { gate.noteNotification(info) } - /// After the gate has admitted the device as Booted, drop input while - /// the current client is still reporting HIDError 2 (iOS starting up). + /// After the gate has admitted the device as Booted, drop (or expire) + /// the not-ready window. Used by `admit` / `gated`, which do not probe. private func admitReady() -> Bool { guard notReady else { return true } - let started = notReadySince ?? now() - if now() - started >= notReadyLimit { - notReady = false - notReadySince = nil - loggedNotReady = false + if expiredNotReady() { + clearNotReady() return true } + logNotReadyOnce() + return false + } + + /// Like `admit()`, but while not-ready lets one unacked probe send + /// through every `notReadyProbeInterval` so a success can clear the flag. + private func admitForSend() -> SendAdmission { + switch gate.admit() { + case .drop(let message): + if let message { log(message) } + return .drop + case .deliver(reconnect: false): + return admitReadyForSend() + case .deliver(reconnect: true): + guard connect() else { + gate.noteClientDisconnected() + log("[hid] Simulator Booted again, but the HID client could not be recreated") + return .drop + } + log(Self.reconnectedMessage) + didReconnect() + return admitReadyForSend() + } + } + + private func admitReadyForSend() -> SendAdmission { + if admitReady() { return .deliver } + let t = now() + if let last = lastNotReadyProbeAt, t - last < notReadyProbeInterval { + return .drop + } + lastNotReadyProbeAt = t + return .probe + } + + private func expiredNotReady() -> Bool { + let started = notReadySince ?? now() + return now() - started >= notReadyLimit + } + + private func logNotReadyOnce() { if !loggedNotReady { log(Self.notReadyMessage) loggedNotReady = true } - return false + } + + private func clearNotReady() { + notReady = false + notReadySince = nil + lastNotReadyProbeAt = nil + loggedNotReady = false } } diff --git a/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift index 2c441a362..67dbe5bda 100644 --- a/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift @@ -62,7 +62,10 @@ public final class HIDDeliveryGate { public func admit() -> Decision { switch currentState() { case .timedOut: - needsReconnect = true + // A slow read on a still-Booted device is not a trip out of Booted. + // Rebuilding the client (and resetting the Duo helper) on timeout + // is reserved for a completed non-Booted read, a state + // notification, or HIDError 3. if loggedTimeout { return .drop(log: nil) } loggedTimeout = true return .drop(log: "[hid] Dropping input: simulator state could not be read in time") diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift index 1d14ed716..2a94def6e 100644 --- a/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift @@ -30,7 +30,8 @@ final class HIDClientChannelTests: XCTestCase { log: { [unowned self] in self.logs.append($0) }, didReconnect: { [unowned self] in self.reconnectHooks += 1 }, now: { [unowned self] in self.now }, - notReadyLimit: 30 + notReadyLimit: 30, + notReadyProbeInterval: 0.5 ) }() @@ -130,9 +131,10 @@ final class HIDClientChannelTests: XCTestCase { let h = Harness(); h.setup() h.channel.clientReported(h.channel.client!, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) // Still the same client: error 2 means "not ready", not "disconnected". + // The first send is an unacked probe, not a reconnect. var sends = 0 XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) - XCTAssertEqual(sends, 0) + XCTAssertEqual(sends, 1) XCTAssertEqual(h.connects, 1) } @@ -141,13 +143,34 @@ final class HIDClientChannelTests: XCTestCase { let client = h.channel.client! h.channel.clientReported(client, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) var sends = 0 + // First send is an unacked probe; a second send in the same interval + // does not transmit. A success from the probe re-enables delivery. XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) - XCTAssertEqual(sends, 0) + XCTAssertEqual(sends, 1) XCTAssertEqual(h.logs, [HIDClientChannel.notReadyMessage]) h.channel.clientReportedSuccess(client) XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 2) + XCTAssertEqual(h.connects, 1) + } + + func testHIDError2ProbeRunsOncePerIntervalAndSuccessReenablesDelivery() { + let h = Harness(); h.setup() + let client = h.channel.client! + h.channel.clientReported(client, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) + var sends = 0 + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + h.now = 0.4 + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) XCTAssertEqual(sends, 1) + h.now = 0.5 + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 2) + // Probe completion succeeds: later input is acked. + h.channel.clientReportedSuccess(client) + XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 3) XCTAssertEqual(h.connects, 1) } diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift index ef2f6d41c..aae70e04f 100644 --- a/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift @@ -136,8 +136,7 @@ final class HIDDeliveryGateTests: XCTestCase { XCTAssertEqual(gate.admit(), .drop(log: nil)) hold.lock(); stuck = false; hold.broadcast(); hold.unlock() // After the stuck read finishes (Booted) the next admit delivers - // and asks for a reconnect, because the timeout was treated as a trip - // out of a known-good state. + // without a reconnect: a slow read is not a trip out of Booted. let deadline = Date().addingTimeInterval(1) var last: HIDDeliveryGate.Decision? while Date() < deadline { @@ -145,7 +144,7 @@ final class HIDDeliveryGateTests: XCTestCase { if case .deliver = last { break } Thread.sleep(forTimeInterval: 0.01) } - XCTAssertEqual(last, .deliver(reconnect: true)) + XCTAssertEqual(last, .deliver(reconnect: false)) } func testIsClientNotReadyIsHIDError2() { diff --git a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts index 71167fca1..a0eac4ef0 100644 --- a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -102,6 +102,26 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " expect(down.stderr).not.toContain(NO_SERVER); }, 60_000); + test("after simctl boot, input is acked again well before the 30s not-ready limit", async () => { + // Don't wait for bootstatus: the not-ready window used to refuse every + // tap for a full 30s because admit() blocked transmit, so a success + // could never clear the flag. Probes every 0.5s should get an ack + // once the guest can take input, well under the backstop. + const issued = Date.now(); + spawnSync("xcrun", ["simctl", "boot", udid!], { stdio: "ignore" }); + let firstOk: number | undefined; + const deadline = Date.now() + 25_000; + while (Date.now() < deadline) { + const r = tap(); + if (r.status === 0) { firstOk = Date.now() - issued; break; } + expect(r.stderr).not.toContain(NO_SERVER); + await sleep(400); + } + if (firstOk == null) throw new Error("no successful tap within 25s of simctl boot"); + expect(firstOk).toBeLessThan(20_000); + expect(server!.exitCode).toBeNull(); + }, 60_000); + test("after the same simulator boots again, a tap on the guest lands", async () => { bootAndWait(); const r = await tapUntilOk(30_000); From 9f6b5df64bee9ee70914f365962e6b59e0c161c1 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 19:07:42 -0800 Subject: [PATCH 07/13] fix(hid): probe readiness with a no-op, not the caller's event A not-ready probe that transmitted the caller's begin and returned false left a finger down: the CLI closed on the nack and never sent the matching end. Probe with a touch-up instead, keep the caller's event undelivered until a successful completion, and let gated Home/Duo paths run while the HID client is still starting. Also keep each BoundedStateReader flight's completion with its waiters, fail the opt-in e2e when the CLI is missing, and time the post-boot ack bound from the first not-ready log so a slow guest boot is not a flake. --- .../Sources/SimNative/HIDInjector.swift | 35 ++++-- .../SimNativeSupport/BoundedStateReader.swift | 51 ++++++--- .../SimNativeSupport/HIDClientChannel.swift | 94 ++++++++------- .../BoundedStateReaderTests.swift | 9 +- .../HIDClientChannelTests.swift | 108 ++++++++++++++---- .../__tests__/hid-after-shutdown.e2e.test.ts | 31 +++-- 6 files changed, 223 insertions(+), 105 deletions(-) diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index 8622f0384..ad53a11d1 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -304,21 +304,40 @@ actor HIDInjector { static let edgeLeft: UInt32 = 1 // Left edge static let edgeRight: UInt32 = 4 // Right edge + /// Hand `msg` to `client`. On success the client owns `msg` (`freeWhenDone`). + private func handOff(_ msg: UnsafeMutableRawPointer, to client: NSObject) -> Bool { + typealias SendFunc = @convention(c) (AnyObject, Selector, UnsafeMutableRawPointer, ObjCBool, AnyObject?, AnyObject?) -> Void + guard let sendIMP = class_getMethodImplementation(object_getClass(client)!, Self.sendSel) else { return false } + unsafeBitCast(sendIMP, to: SendFunc.self)(client, Self.sendSel, msg, ObjCBool(true), queue, completion(for: client)) + return true + } + + /// A touch-up with no preceding down is ignored by the guest; its + /// completion still reports whether the HID client can accept input. + /// Used as the not-ready probe so a caller's begin/end is never split. + private func sendReadinessProbe(through client: NSObject) -> Bool { + guard let msg = touchMessage(type: "end", x: 0.5, y: 0.5, edge: Self.edgeNone) else { return false } + guard handOff(msg, to: client) else { + free(msg) + return false + } + return true + } + /// Synchronously hand an already-built Indigo message to the guest, freeing it. /// Must run on `inputQueue`. Returns false when there is no HID client to - /// send through (setup never completed) or the device is no longer booted, - /// so callers can report the drop. + /// send through (setup never completed), the device is no longer booted, + /// or the HID client is not ready, so callers can report the drop. @discardableResult private func rawSend(_ msg: UnsafeMutableRawPointer) -> Bool { var handedOff = false - let sent = channel.send { client in - typealias SendFunc = @convention(c) (AnyObject, Selector, UnsafeMutableRawPointer, ObjCBool, AnyObject?, AnyObject?) -> Void - guard let sendIMP = class_getMethodImplementation(object_getClass(client)!, Self.sendSel) else { return false } - // freeWhenDone: the client owns `msg` from here. - unsafeBitCast(sendIMP, to: SendFunc.self)(client, Self.sendSel, msg, ObjCBool(true), queue, completion(for: client)) + let sent = channel.send({ [self] client in + guard self.handOff(msg, to: client) else { return false } handedOff = true return true - } + }, probe: { [self] client in + self.sendReadinessProbe(through: client) + }) if !handedOff { free(msg) } return sent } diff --git a/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift index 724264d32..bf016d483 100644 --- a/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift +++ b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift @@ -23,10 +23,17 @@ public final class BoundedStateReader: @unchecked Sendable { private let timeout: TimeInterval private let queue: DispatchQueue private let lock = NSCondition() - private var inFlight = false - private var finished = false - private var value: Int? - private var timedOutThisFlight = false + /// Waiters hold the `Flight` they joined, so a later probe starting a + /// new read cannot reset this flight's completion out from under them. + private final class Flight { + var finished = false + var value: Int? + var timedOut = false + } + private var inFlight: Flight? + /// Callers currently inside `probe()` for tests that need to wait until + /// an overlapping caller has joined the in-flight read. + private(set) var waiterCount = 0 public init(timeout: TimeInterval = BoundedStateReader.defaultTimeout, read: @escaping () -> Int?) { self.timeout = timeout @@ -37,35 +44,41 @@ public final class BoundedStateReader: @unchecked Sendable { public func probe() -> Probe { lock.lock() defer { lock.unlock() } + waiterCount += 1 + defer { waiterCount -= 1 } - if !inFlight { - inFlight = true - finished = false - timedOutThisFlight = false - value = nil + let flight: Flight + if let current = inFlight { + flight = current + // An earlier caller already waited out this flight; don't pile + // another `timeout` onto every subsequent tap. + if flight.timedOut { + return .timedOut + } + } else { + flight = Flight() + inFlight = flight let read = self.read queue.async { [self] in let result = read() self.lock.lock() - self.value = result - self.finished = true - self.inFlight = false + flight.value = result + flight.finished = true + if self.inFlight === flight { + self.inFlight = nil + } self.lock.broadcast() self.lock.unlock() } - } else if timedOutThisFlight && !finished { - // An earlier caller already waited out this flight; don't pile - // another `timeout` onto every subsequent tap. - return .timedOut } let deadline = Date().addingTimeInterval(timeout) - while !finished { + while !flight.finished { if !lock.wait(until: deadline) { - timedOutThisFlight = true + flight.timedOut = true return .timedOut } } - return .ready(value) + return .ready(flight.value) } } diff --git a/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift index 4d2e76279..4ff325fb3 100644 --- a/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift @@ -16,8 +16,9 @@ public final class HIDClientChannel { public static var reconnectedMessage: String { "[hid] Simulator Booted again, reconnected HID client" } public static var notReadyMessage: String { "[hid] Dropping input: HID client is not ready (HIDError 2, guest still starting)" } public static var notReadyLimit: TimeInterval { 30 } - /// While not-ready, one unacked probe send is allowed this often so a - /// successful completion can clear the flag before `notReadyLimit`. + /// While not-ready, one non-action probe is allowed this often so a + /// successful completion can clear the flag. The caller's event is never + /// used as that probe. public static var notReadyProbeInterval: TimeInterval { 0.5 } private enum SendAdmission { @@ -37,6 +38,7 @@ public final class HIDClientChannel { private var notReadySince: TimeInterval? private var lastNotReadyProbeAt: TimeInterval? private var loggedNotReady = false + private var loggedNotReadyLimit = false public private(set) var client: Client? public init( @@ -72,15 +74,17 @@ public final class HIDClientChannel { clearNotReady() } - /// Whether input may go to the guest now. Rebuilds the client first when - /// the device has just come back. + /// Whether input that does not go through the HID client may run now + /// (Home's SpringBoard relaunch, Duo-helper keys). Rebuilds the client + /// first when the device has just come back. Does not apply the + /// HIDError-2 not-ready window: that only affects Indigo sends. public func admit() -> Bool { switch gate.admit() { case .drop(let message): if let message { log(message) } return false case .deliver(reconnect: false): - return admitReady() + return true case .deliver(reconnect: true): guard connect() else { // Try again on the next input rather than sending through a dead port. @@ -90,31 +94,40 @@ public final class HIDClientChannel { } log(Self.reconnectedMessage) didReconnect() - return admitReady() + return true } } /// Gate, then hand the current client to `transmit`. False when the - /// device isn't booted, there is no client, `transmit` failed, or this - /// send is a not-ready probe (never acked; its completion may clear the - /// flag). `transmit` isn't called when the device isn't booted or there - /// is no client. - public func send(_ transmit: (Client) -> Bool) -> Bool { - let probe: Bool + /// device isn't booted, there is no client, `transmit` failed, or the + /// HID client is not ready. A successful return means the message was + /// handed to the client (the existing ready-path contract); it is not a + /// guest completion. While not-ready, `transmit` is not called — a + /// non-action `probe` is sent at most once per `notReadyProbeInterval` + /// instead, and this returns false so the caller's event is never + /// acked or left half-delivered. `probe` isn't called when the device + /// isn't booted or there is no client, and the probe slot is only + /// consumed when `probe` returns true. + public func send(_ transmit: (Client) -> Bool, probe: ((Client) -> Bool)? = nil) -> Bool { switch admitForSend() { case .drop: return false case .deliver: - probe = false + guard let client else { + log("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") + return false + } + return transmit(client) case .probe: - probe = true - } - guard let client else { - log("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") + guard let client else { + log("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") + return false + } + if probe?(client) == true { + lastNotReadyProbeAt = now() + } return false } - let delivered = transmit(client) - return probe ? false : delivered } /// Gate input that doesn't go through the client (it still triggers the @@ -129,10 +142,9 @@ public final class HIDClientChannel { /// A send completion from `reporter`. A disconnect error from the /// current client makes the next input rebuild it. A not-ready error - /// (HIDError 2) drops later input until a send completes without error - /// or `notReadyLimit` has passed, except for a periodic unacked probe - /// so that success path can actually run. Late errors from a client - /// that was already replaced are ignored. + /// (HIDError 2) drops later Indigo input until a probe or send + /// completes without error. Time passing does not clear the flag. + /// Late errors from a client that was already replaced are ignored. public func clientReported(_ reporter: Client, domain: String, code: Int) { guard reporter === client else { return } if HIDDeliveryGate.isClientDisconnected(domain: domain, code: code) { @@ -146,6 +158,7 @@ public final class HIDClientChannel { notReadySince = now() lastNotReadyProbeAt = nil loggedNotReady = false + loggedNotReadyLimit = false } } @@ -161,20 +174,8 @@ public final class HIDClientChannel { gate.noteNotification(info) } - /// After the gate has admitted the device as Booted, drop (or expire) - /// the not-ready window. Used by `admit` / `gated`, which do not probe. - private func admitReady() -> Bool { - guard notReady else { return true } - if expiredNotReady() { - clearNotReady() - return true - } - logNotReadyOnce() - return false - } - - /// Like `admit()`, but while not-ready lets one unacked probe send - /// through every `notReadyProbeInterval` so a success can clear the flag. + /// Like `admit()`, but while not-ready withholds the caller's event and + /// lets one non-action probe through every `notReadyProbeInterval`. private func admitForSend() -> SendAdmission { switch gate.admit() { case .drop(let message): @@ -195,20 +196,16 @@ public final class HIDClientChannel { } private func admitReadyForSend() -> SendAdmission { - if admitReady() { return .deliver } + guard notReady else { return .deliver } + logNotReadyOnce() + logNotReadyLimitOnce() let t = now() if let last = lastNotReadyProbeAt, t - last < notReadyProbeInterval { return .drop } - lastNotReadyProbeAt = t return .probe } - private func expiredNotReady() -> Bool { - let started = notReadySince ?? now() - return now() - started >= notReadyLimit - } - private func logNotReadyOnce() { if !loggedNotReady { log(Self.notReadyMessage) @@ -216,10 +213,19 @@ public final class HIDClientChannel { } } + private func logNotReadyLimitOnce() { + guard !loggedNotReadyLimit else { return } + let started = notReadySince ?? now() + guard now() - started >= notReadyLimit else { return } + log("[hid] HID client still not ready after \(Int(notReadyLimit))s; continuing to probe, not acking input until a send succeeds") + loggedNotReadyLimit = true + } + private func clearNotReady() { notReady = false notReadySince = nil lastNotReadyProbeAt = nil loggedNotReady = false + loggedNotReadyLimit = false } } diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift index b61b1113b..b8575a843 100644 --- a/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift +++ b/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift @@ -74,8 +74,13 @@ final class BoundedStateReaderTests: XCTestCase { second = reader.probe() secondDone.signal() } - // Let the second caller join the in-flight read. - Thread.sleep(forTimeInterval: 0.05) + // Wait until the second caller has entered probe() and joined the + // in-flight read, then release it. A fixed sleep can miss that join. + let joined = Date().addingTimeInterval(1) + while reader.waiterCount < 2 && Date() < joined { + Thread.sleep(forTimeInterval: 0.001) + } + XCTAssertGreaterThanOrEqual(reader.waiterCount, 2) hold.signal() firstDone.wait() secondDone.wait() diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift index 2a94def6e..7a2bd63e8 100644 --- a/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift @@ -131,27 +131,33 @@ final class HIDClientChannelTests: XCTestCase { let h = Harness(); h.setup() h.channel.clientReported(h.channel.client!, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) // Still the same client: error 2 means "not ready", not "disconnected". - // The first send is an unacked probe, not a reconnect. + // The caller's event is not sent; a non-action probe is. var sends = 0 - XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) - XCTAssertEqual(sends, 1) + var probes = 0 + XCTAssertFalse(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(sends, 0) + XCTAssertEqual(probes, 1) XCTAssertEqual(h.connects, 1) } - func testHIDError2DropsUntilASuccessfulSend() { + func testHIDError2DropsUntilASuccessfulProbe() { let h = Harness(); h.setup() let client = h.channel.client! h.channel.clientReported(client, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) var sends = 0 - // First send is an unacked probe; a second send in the same interval - // does not transmit. A success from the probe re-enables delivery. - XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) - XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) - XCTAssertEqual(sends, 1) + var probes = 0 + // First send fires a non-action probe and returns false. A second + // send in the same interval does not probe again. A success from + // the probe re-enables delivery of the caller's event. + XCTAssertFalse(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) + XCTAssertFalse(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(sends, 0) + XCTAssertEqual(probes, 1) XCTAssertEqual(h.logs, [HIDClientChannel.notReadyMessage]) h.channel.clientReportedSuccess(client) - XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) - XCTAssertEqual(sends, 2) + XCTAssertTrue(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(sends, 1) + XCTAssertEqual(probes, 1) XCTAssertEqual(h.connects, 1) } @@ -160,28 +166,86 @@ final class HIDClientChannelTests: XCTestCase { let client = h.channel.client! h.channel.clientReported(client, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) var sends = 0 - XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + var probes = 0 + XCTAssertFalse(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) h.now = 0.4 - XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) - XCTAssertEqual(sends, 1) + XCTAssertFalse(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(sends, 0) + XCTAssertEqual(probes, 1) h.now = 0.5 - XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) - XCTAssertEqual(sends, 2) + XCTAssertFalse(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(sends, 0) + XCTAssertEqual(probes, 2) // Probe completion succeeds: later input is acked. h.channel.clientReportedSuccess(client) - XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) - XCTAssertEqual(sends, 3) + XCTAssertTrue(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(sends, 1) + XCTAssertEqual(probes, 2) XCTAssertEqual(h.connects, 1) } - func testHIDError2ExpiresAfterTheLimit() { + func testHIDError2ProbeDoesNotTransmitTheCallerEvent() { + // A tap is begin + end. If the begin were sent as an unacked probe, + // the CLI would close on ok:false and never send the end, leaving + // a finger down. The caller's events must stay unsent until a + // non-action probe succeeds. + let h = Harness(); h.setup() + let client = h.channel.client! + h.channel.clientReported(client, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) + var events: [String] = [] + var probes = 0 + XCTAssertFalse(h.channel.send({ _ in events.append("begin"); return true }, probe: { _ in probes += 1; return true })) + XCTAssertFalse(h.channel.send({ _ in events.append("end"); return true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(events, []) + XCTAssertEqual(probes, 1) + h.channel.clientReportedSuccess(client) + XCTAssertTrue(h.channel.send({ _ in events.append("begin"); return true }, probe: { _ in probes += 1; return true })) + XCTAssertTrue(h.channel.send({ _ in events.append("end"); return true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(events, ["begin", "end"]) + XCTAssertEqual(probes, 1) + } + + func testFailedProbeDoesNotConsumeTheProbeSlot() { + let h = Harness(); h.setup() + h.channel.clientReported(h.channel.client!, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) + var probes = 0 + XCTAssertFalse(h.channel.send({ _ in true }, probe: { _ in probes += 1; return false })) + XCTAssertEqual(probes, 1) + // Same instant: the failed probe must not start the interval. + XCTAssertFalse(h.channel.send({ _ in true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(probes, 2) + } + + func testGatedButtonsStillRunWhileHIDClientIsNotReady() async { + // Home / Duo go through `gated`, not the HID client, so HIDError 2 + // must not refuse them (and a button-only flow must not wait 30s). let h = Harness(); h.setup() h.channel.clientReported(h.channel.client!, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) + var homeLaunches = 0 + let ok = await h.channel.gated { homeLaunches += 1; return true } + XCTAssertTrue(ok) + XCTAssertEqual(homeLaunches, 1) + var sends = 0 + XCTAssertFalse(h.channel.send { _ in sends += 1; return true }) + XCTAssertEqual(sends, 0) + } + + func testHIDError2KeepsDroppingAfterTheLimitUntilASuccessfulProbe() { + let h = Harness(); h.setup() + let client = h.channel.client! + h.channel.clientReported(client, domain: "SimulatorKit.SimDeviceLegacyHIDClient.HIDError", code: 2) + var sends = 0 + var probes = 0 h.now = 29 - XCTAssertFalse(h.channel.send { _ in true }) + XCTAssertFalse(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) h.now = 30 - var sends = 0 - XCTAssertTrue(h.channel.send { _ in sends += 1; return true }) + XCTAssertFalse(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(sends, 0) + XCTAssertEqual(probes, 2) + XCTAssertTrue(h.logs.contains(HIDClientChannel.notReadyMessage)) + XCTAssertTrue(h.logs.contains("[hid] HID client still not ready after 30s; continuing to probe, not acking input until a send succeeds")) + h.channel.clientReportedSuccess(client) + XCTAssertTrue(h.channel.send({ _ in sends += 1; return true }, probe: { _ in probes += 1; return true })) XCTAssertEqual(sends, 1) XCTAssertEqual(h.connects, 1) } diff --git a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts index a0eac4ef0..553c52c9b 100644 --- a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -18,7 +18,10 @@ import { join } from "path"; const CLI = join(import.meta.dir, "../../dist/serve-sim.js"); const udid = process.env.SERVE_SIM_E2E_SHUTDOWN_UDID; -const describeIfOptedIn = udid && existsSync(CLI) ? describe : describe.skip; +if (udid && !existsSync(CLI)) { + throw new Error(`SERVE_SIM_E2E_SHUTDOWN_UDID is set but ${CLI} is missing; build the CLI first`); +} +const describeIfOptedIn = udid ? describe : describe.skip; const RECONNECTED = "[hid] Simulator Booted again, reconnected HID client"; const NO_SERVER = "No serve-sim server running"; @@ -105,22 +108,30 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " test("after simctl boot, input is acked again well before the 30s not-ready limit", async () => { // Don't wait for bootstatus: the not-ready window used to refuse every // tap for a full 30s because admit() blocked transmit, so a success - // could never clear the flag. Probes every 0.5s should get an ack - // once the guest can take input, well under the backstop. - const issued = Date.now(); + // could never clear the flag. A non-action probe every 0.5s should + // clear that flag once the guest can take input. Guest boot itself + // can exceed 20s on a slow CI runner, so the 20s bound is measured + // from the first not-ready log, not from `simctl boot`. + const logAtStart = serverLog.length; spawnSync("xcrun", ["simctl", "boot", udid!], { stdio: "ignore" }); - let firstOk: number | undefined; - const deadline = Date.now() + 25_000; + let firstOkAt: number | undefined; + let notReadyAt: number | undefined; + const deadline = Date.now() + 45_000; while (Date.now() < deadline) { const r = tap(); - if (r.status === 0) { firstOk = Date.now() - issued; break; } + if (notReadyAt == null && serverLog.slice(logAtStart).includes("[hid] Dropping input: HID client is not ready")) { + notReadyAt = Date.now(); + } + if (r.status === 0) { firstOkAt = Date.now(); break; } expect(r.stderr).not.toContain(NO_SERVER); await sleep(400); } - if (firstOk == null) throw new Error("no successful tap within 25s of simctl boot"); - expect(firstOk).toBeLessThan(20_000); + if (firstOkAt == null) throw new Error("no successful tap within 45s of simctl boot"); + if (notReadyAt != null) { + expect(firstOkAt - notReadyAt).toBeLessThan(20_000); + } expect(server!.exitCode).toBeNull(); - }, 60_000); + }, 90_000); test("after the same simulator boots again, a tap on the guest lands", async () => { bootAndWait(); From 7b47111e792dd2f03f0887db3b50e7b4ec4e0296 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 19:16:35 -0800 Subject: [PATCH 08/13] test(hid): tighten not-ready probe review nits Read BoundedStateReader.waiterCount under the probe lock, give the overlapping-reader test a timeout longer than its join deadline, and stamp the post-boot 20s recovery bound when the not-ready log arrives rather than after a blocking tap returns. --- .../SimNativeSupport/BoundedStateReader.swift | 15 ++++++---- .../BoundedStateReaderTests.swift | 4 ++- .../__tests__/hid-after-shutdown.e2e.test.ts | 28 +++++++++++++------ 3 files changed, 33 insertions(+), 14 deletions(-) diff --git a/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift index bf016d483..ddca9d602 100644 --- a/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift +++ b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift @@ -31,9 +31,14 @@ public final class BoundedStateReader: @unchecked Sendable { var timedOut = false } private var inFlight: Flight? - /// Callers currently inside `probe()` for tests that need to wait until - /// an overlapping caller has joined the in-flight read. - private(set) var waiterCount = 0 + /// Callers currently inside `probe()`. Tests read this through the + /// locked getter so they do not race the probe threads. + private var waiterCountStorage = 0 + var waiterCount: Int { + lock.lock() + defer { lock.unlock() } + return waiterCountStorage + } public init(timeout: TimeInterval = BoundedStateReader.defaultTimeout, read: @escaping () -> Int?) { self.timeout = timeout @@ -44,8 +49,8 @@ public final class BoundedStateReader: @unchecked Sendable { public func probe() -> Probe { lock.lock() defer { lock.unlock() } - waiterCount += 1 - defer { waiterCount -= 1 } + waiterCountStorage += 1 + defer { waiterCountStorage -= 1 } let flight: Flight if let current = inFlight { diff --git a/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift b/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift index b8575a843..f12eba79f 100644 --- a/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift +++ b/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift @@ -53,7 +53,9 @@ final class BoundedStateReaderTests: XCTestCase { let started = DispatchSemaphore(value: 0) let hold = DispatchSemaphore(value: 0) var calls = 0 - let reader = BoundedStateReader(timeout: 1) { + // Timeout must outlast the 1s join deadline so a late second + // caller cannot let the first probe expire before hold.signal(). + let reader = BoundedStateReader(timeout: 5) { calls += 1 started.signal() hold.wait() diff --git a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts index 553c52c9b..9ac09ffbd 100644 --- a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -112,19 +112,31 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " // clear that flag once the guest can take input. Guest boot itself // can exceed 20s on a slow CI runner, so the 20s bound is measured // from the first not-ready log, not from `simctl boot`. + const NOT_READY_LOG = "[hid] Dropping input: HID client is not ready"; const logAtStart = serverLog.length; + let notReadyAt: number | undefined; + const stampNotReady = (chunk?: string) => { + if (notReadyAt != null) return; + const text = chunk ?? serverLog.slice(logAtStart); + if (text.includes(NOT_READY_LOG)) notReadyAt = Date.now(); + }; + const onData = (d: Buffer | string) => { stampNotReady(String(d)); }; + stampNotReady(); + server!.stdout!.on("data", onData); + server!.stderr!.on("data", onData); spawnSync("xcrun", ["simctl", "boot", udid!], { stdio: "ignore" }); let firstOkAt: number | undefined; - let notReadyAt: number | undefined; const deadline = Date.now() + 45_000; - while (Date.now() < deadline) { - const r = tap(); - if (notReadyAt == null && serverLog.slice(logAtStart).includes("[hid] Dropping input: HID client is not ready")) { - notReadyAt = Date.now(); + try { + while (Date.now() < deadline) { + const r = tap(); + if (r.status === 0) { firstOkAt = Date.now(); break; } + expect(r.stderr).not.toContain(NO_SERVER); + await sleep(400); } - if (r.status === 0) { firstOkAt = Date.now(); break; } - expect(r.stderr).not.toContain(NO_SERVER); - await sleep(400); + } finally { + server!.stdout!.off("data", onData); + server!.stderr!.off("data", onData); } if (firstOkAt == null) throw new Error("no successful tap within 45s of simctl boot"); if (notReadyAt != null) { From 354bd5fbd1b4c9ac9a0a8026b380452a2a2e4b7f Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 19:29:09 -0800 Subject: [PATCH 09/13] test(hid): detect the not-ready log across stdout chunks Search accumulated server log instead of each data chunk so a split readiness line still starts the 20s recovery bound, and yield after each blocking tap so queued stdout handlers can append first. --- .../src/__tests__/hid-after-shutdown.e2e.test.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts index 9ac09ffbd..62c3bbe59 100644 --- a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -115,12 +115,14 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " const NOT_READY_LOG = "[hid] Dropping input: HID client is not ready"; const logAtStart = serverLog.length; let notReadyAt: number | undefined; - const stampNotReady = (chunk?: string) => { + // Search accumulated serverLog so a message split across `data` chunks + // still matches. `tap()` uses spawnSync and blocks the event loop, so + // yield after each tap to let queued stdout/stderr handlers append. + const stampNotReady = () => { if (notReadyAt != null) return; - const text = chunk ?? serverLog.slice(logAtStart); - if (text.includes(NOT_READY_LOG)) notReadyAt = Date.now(); + if (serverLog.slice(logAtStart).includes(NOT_READY_LOG)) notReadyAt = Date.now(); }; - const onData = (d: Buffer | string) => { stampNotReady(String(d)); }; + const onData = () => { stampNotReady(); }; stampNotReady(); server!.stdout!.on("data", onData); server!.stderr!.on("data", onData); @@ -130,6 +132,8 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " try { while (Date.now() < deadline) { const r = tap(); + await sleep(0); + stampNotReady(); if (r.status === 0) { firstOkAt = Date.now(); break; } expect(r.stderr).not.toContain(NO_SERVER); await sleep(400); From ef6a0000d309367137be492043a3e49d9855b021 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 19:57:46 -0800 Subject: [PATCH 10/13] fix(hid): cap reconnect's initWithDevice: so shutdown acks stay fast macos-26 CI on 354bd5f missed the 2s post-shutdown drop bound (afterMs 4107 / 2789) and then got no tap ack within 45s of simctl boot. A reconnect during shutdown ran initWithDevice: on the hid-injector actor while CoreSimulator held the lock, so the ack never arrived before the 4s CLI timeout and later taps sat behind the same hang. Build the replacement client off the actor queue and give up after 150ms; a late client is discarded. The opt-in e2e now dumps the server log on failure and allows 90s for guest boot itself, still measuring the 20s not-ready recovery from the first not-ready log. --- .../Sources/SimNative/HIDInjector.swift | 53 +++++++++++++++---- .../__tests__/hid-after-shutdown.e2e.test.ts | 24 +++++---- 2 files changed, 59 insertions(+), 18 deletions(-) diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index ad53a11d1..3863d9bf0 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -159,15 +159,11 @@ actor HIDInjector { channel = HIDClientChannel( gate: gate, connect: { - // makeHIDClient (initWithDevice:) is unbounded and runs on - // this actor queue. A CoreSimulator lock during shutdown can - // stall the next ack; accepted for now (the 100ms state - // probe already bounds admit). Prefer moving this off-queue - // if the hang returns. - do { return try Self.makeHIDClient(device: device) } catch { - print("[hid] Could not create SimDeviceLegacyHIDClient: \(error.localizedDescription)") - return nil - } + // initWithDevice: can block on a CoreSimulator lock during + // shutdown. Run it off this actor queue with a short + // timeout so a reconnect cannot stall the next tap ack + // past the 2s drop bound (or the 4s CLI ack timeout). + Self.makeHIDClientBounded(device: device) }, log: Self.logLine, // The Duo guest helper ran inside the old boot; start a new one. @@ -195,6 +191,45 @@ actor HIDInjector { fflush(stdout) } + /// Upper bound for a reconnect's `initWithDevice:`. Matches the state + /// probe closely enough that a locked shutdown still drops inside the + /// 2s e2e window, including CLI startup. + private static let makeClientTimeout: TimeInterval = 0.15 + + /// Build a HID client off the injector's actor queue. Returns nil if + /// `initWithDevice:` does not finish in time; a late client is discarded + /// so it cannot be adopted after we have already reported a drop. + private static func makeHIDClientBounded(device: NSObject) -> NSObject? { + let box = MakeClientBox() + let done = DispatchSemaphore(value: 0) + DispatchQueue.global(qos: .userInteractive).async { + do { + box.set(client: try makeHIDClient(device: device)) + } catch { + logLine("[hid] Could not create SimDeviceLegacyHIDClient: \(error.localizedDescription)") + box.set(client: nil) + } + done.signal() + } + if done.wait(timeout: .now() + makeClientTimeout) == .timedOut { + logLine("[hid] Timed out creating SimDeviceLegacyHIDClient after \(makeClientTimeout)s") + return nil + } + return box.client + } + + private final class MakeClientBox: @unchecked Sendable { + private let lock = NSLock() + private var value: NSObject? + var client: NSObject? { + lock.lock(); defer { lock.unlock() } + return value + } + func set(client: NSObject?) { + lock.lock(); value = client; lock.unlock() + } + } + /// A new SimDeviceLegacyHIDClient for the device's current boot. private static func makeHIDClient(device: NSObject) throws -> NSObject { guard let hidClass = NSClassFromString("_TtC12SimulatorKit24SimDeviceLegacyHIDClient") else { diff --git a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts index 62c3bbe59..e86823949 100644 --- a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -79,8 +79,10 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " test("tap fails with an undelivered error within 2s of shutdown, while the server is up", async () => { // The bound is 2s because a correct drop is fast (locally ~0.4–1.2s, // including CLI startup). On macos-26 CI, a synchronous SimDevice.state - // read during `simctl shutdown` blocked the first tap for 6312ms; the - // gate now times that read out at 100ms, so this bound stays at 2s. + // read during `simctl shutdown` blocked the first tap for 6312ms, and + // a reconnect's initWithDevice: later hung the ack until the 4s CLI + // timeout. The state read is capped at 100ms and reconnect is capped + // at 150ms off the actor queue, so this bound stays at 2s. expect(tap().status).toBe(0); const shutdown = spawn("xcrun", ["simctl", "shutdown", udid!], { stdio: "ignore" }); @@ -92,10 +94,10 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " } await new Promise((r) => shutdown.on("exit", r)); - if (!failure) throw new Error("every tap in the 2s after `simctl shutdown` exited 0"); - expect(failure.afterMs).toBeLessThan(2_000); + if (!failure) throw new Error(`every tap in the 2s after \`simctl shutdown\` exited 0\n${serverLog}`); + expect(failure.stderr, `first undelivered tap at ${failure.afterMs}ms\n${failure.stderr}\n${serverLog}`).toContain("could not deliver the tap"); + expect(failure.afterMs, `first undelivered tap at ${failure.afterMs}ms (stderr: ${failure.stderr})\n${serverLog}`).toBeLessThan(2_000); // The injector refused the tap, so the server was answering. - expect(failure.stderr).toContain("could not deliver the tap"); expect(failure.stderr).not.toContain(NO_SERVER); expect(server!.exitCode).toBeNull(); // It still answers once the device is fully down. @@ -128,26 +130,30 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " server!.stderr!.on("data", onData); spawnSync("xcrun", ["simctl", "boot", udid!], { stdio: "ignore" }); let firstOkAt: number | undefined; - const deadline = Date.now() + 45_000; + let lastFail = ""; + const deadline = Date.now() + 90_000; try { while (Date.now() < deadline) { const r = tap(); await sleep(0); stampNotReady(); if (r.status === 0) { firstOkAt = Date.now(); break; } - expect(r.stderr).not.toContain(NO_SERVER); + lastFail = r.stderr; + expect(r.stderr, r.stderr).not.toContain(NO_SERVER); await sleep(400); } } finally { server!.stdout!.off("data", onData); server!.stderr!.off("data", onData); } - if (firstOkAt == null) throw new Error("no successful tap within 45s of simctl boot"); + if (firstOkAt == null) { + throw new Error(`no successful tap within 90s of simctl boot\n${lastFail}\n${serverLog.slice(logAtStart)}`); + } if (notReadyAt != null) { expect(firstOkAt - notReadyAt).toBeLessThan(20_000); } expect(server!.exitCode).toBeNull(); - }, 90_000); + }, 150_000); test("after the same simulator boots again, a tap on the guest lands", async () => { bootAndWait(); From 41cad687c0bbd8581ad554b8c0c39e8c9f3a6705 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 20:02:52 -0800 Subject: [PATCH 11/13] fix(hid): coalesce reconnect inits so a slow post-boot client is adopted A 150ms cap that discarded every late initWithDevice: could refuse input forever if a loaded runner took longer than that after boot, and each retry could leave another thread blocked on the lock. Keep one in-flight init. A send still waits at most 150ms and returns undelivered on expiry, but the work keeps running and the next reconnecting send (already gated on Booted) adopts the result. --- .../Sources/SimNative/HIDInjector.swift | 94 ++++++++++++------- 1 file changed, 60 insertions(+), 34 deletions(-) diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index 3863d9bf0..cca66a3d8 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -156,14 +156,15 @@ actor HIDInjector { // Thrown errors here fail setup, as before. let firstClient = try Self.makeHIDClient(device: device) let duo = duoBridge + let maker = BoundedHIDClientMaker(device: device) channel = HIDClientChannel( gate: gate, connect: { // initWithDevice: can block on a CoreSimulator lock during - // shutdown. Run it off this actor queue with a short - // timeout so a reconnect cannot stall the next tap ack - // past the 2s drop bound (or the 4s CLI ack timeout). - Self.makeHIDClientBounded(device: device) + // shutdown. The maker runs it off this actor queue, waits + // at most 150ms, and coalesces overlapping attempts so a + // slow post-boot init is adopted instead of discarded. + maker.make(timeout: Self.makeClientTimeout) }, log: Self.logLine, // The Duo guest helper ran inside the old boot; start a new one. @@ -191,43 +192,68 @@ actor HIDInjector { fflush(stdout) } - /// Upper bound for a reconnect's `initWithDevice:`. Matches the state - /// probe closely enough that a locked shutdown still drops inside the - /// 2s e2e window, including CLI startup. + /// Upper bound for waiting on a reconnect's `initWithDevice:`. Together + /// with the 100ms state-read cap this keeps a shutdown drop inside the + /// 2s e2e bound, including CLI startup. A still-running init is not + /// cancelled: the next reconnecting send adopts it if it has finished. private static let makeClientTimeout: TimeInterval = 0.15 - /// Build a HID client off the injector's actor queue. Returns nil if - /// `initWithDevice:` does not finish in time; a late client is discarded - /// so it cannot be adopted after we have already reported a drop. - private static func makeHIDClientBounded(device: NSObject) -> NSObject? { - let box = MakeClientBox() - let done = DispatchSemaphore(value: 0) - DispatchQueue.global(qos: .userInteractive).async { - do { - box.set(client: try makeHIDClient(device: device)) - } catch { - logLine("[hid] Could not create SimDeviceLegacyHIDClient: \(error.localizedDescription)") - box.set(client: nil) + /// One in-flight `initWithDevice:` at a time, off the injector actor. + /// A send waits up to `timeout` and returns nil on expiry so the ack + /// cannot stall; the work keeps running and a later send can adopt the + /// result. `connect()` is only called after the gate has read Booted, + /// so a finished client is not adopted once the device has left Booted. + private final class BoundedHIDClientMaker: @unchecked Sendable { + private let device: NSObject + private let condition = NSCondition() + private var inFlight = false + private var finished = false + private var client: NSObject? + + init(device: NSObject) { self.device = device } + + func make(timeout: TimeInterval) -> NSObject? { + condition.lock() + defer { condition.unlock() } + if finished { + return takeFinished() } - done.signal() - } - if done.wait(timeout: .now() + makeClientTimeout) == .timedOut { - logLine("[hid] Timed out creating SimDeviceLegacyHIDClient after \(makeClientTimeout)s") - return nil + if !inFlight { + inFlight = true + let device = self.device + DispatchQueue.global(qos: .userInteractive).async { [self] in + let result: NSObject? + do { + result = try HIDInjector.makeHIDClient(device: device) + } catch { + HIDInjector.logLine("[hid] Could not create SimDeviceLegacyHIDClient: \(error.localizedDescription)") + result = nil + } + self.condition.lock() + self.client = result + self.finished = true + self.inFlight = false + self.condition.broadcast() + self.condition.unlock() + } + } + let deadline = Date().addingTimeInterval(timeout) + while !finished { + if !condition.wait(until: deadline) { + HIDInjector.logLine("[hid] Timed out creating SimDeviceLegacyHIDClient after \(timeout)s") + return nil + } + } + return takeFinished() } - return box.client - } - private final class MakeClientBox: @unchecked Sendable { - private let lock = NSLock() - private var value: NSObject? - var client: NSObject? { - lock.lock(); defer { lock.unlock() } + /// Caller must hold `condition`. + private func takeFinished() -> NSObject? { + let value = client + client = nil + finished = false return value } - func set(client: NSObject?) { - lock.lock(); value = client; lock.unlock() - } } /// A new SimDeviceLegacyHIDClient for the device's current boot. From dc4ce140895e211d8225c953064658a7a2141173 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 20:22:14 -0800 Subject: [PATCH 12/13] fix(hid): discard stale reconnect clients and ease the shutdown e2e bound A finished initWithDevice: started on boot B could be adopted on boot C if no send consumed it in between, which would falsely ack one event. Invalidate the maker on a non-Booted device_state notification and discard results from an older epoch. Once a send has waited out an in-flight init, later sends return immediately instead of stacking 150ms waits. macos-26 CI on 41cad68 dropped correctly (Shutdown, could not deliver) but the CLI returned at 3942ms, missing the 2s wall bound; the next test then logged no successful tap in 90s with empty stderr. Widen that bound to 6s (still under the old 7s false-ack window; a hung actor fails via the 4s "no delivery confirmation" message), shorten the CLI tap timeout, and record spawn errors in the boot-poll failure. --- .../Sources/SimNative/HIDInjector.swift | 31 +++++++++++++++-- .../__tests__/hid-after-shutdown.e2e.test.ts | 33 ++++++++++--------- 2 files changed, 47 insertions(+), 17 deletions(-) diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index cca66a3d8..2f63e0846 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -50,6 +50,7 @@ actor HIDInjector { private var channel = HIDClientChannel( gate: HIDDeliveryGate { nil }, connect: { nil }, log: HIDInjector.logLine ) + private var clientMaker: BoundedHIDClientMaker? private static let sendSel = NSSelectorFromString("sendWithMessage:freeWhenDone:completionQueue:completion:") /// Send completion for `completionClient`. It is built once per client, not per send, /// and runs on `queue`, which is this actor's executor. @@ -157,6 +158,7 @@ actor HIDInjector { let firstClient = try Self.makeHIDClient(device: device) let duo = duoBridge let maker = BoundedHIDClientMaker(device: device) + clientMaker = maker channel = HIDClientChannel( gate: gate, connect: { @@ -208,10 +210,21 @@ actor HIDInjector { private let condition = NSCondition() private var inFlight = false private var finished = false + private var timedOutThisFlight = false private var client: NSObject? + private var epoch: UInt64 = 0 + private var flightEpoch: UInt64 = 0 init(device: NSObject) { self.device = device } + /// Drop a stored or in-flight result from an earlier boot so the + /// next reconnect cannot adopt a dead client after a later boot. + func invalidate() { + condition.lock() + epoch += 1 + condition.unlock() + } + func make(timeout: TimeInterval) -> NSObject? { condition.lock() defer { condition.unlock() } @@ -220,6 +233,8 @@ actor HIDInjector { } if !inFlight { inFlight = true + timedOutThisFlight = false + flightEpoch = epoch let device = self.device DispatchQueue.global(qos: .userInteractive).async { [self] in let result: NSObject? @@ -236,10 +251,15 @@ actor HIDInjector { self.condition.broadcast() self.condition.unlock() } + } else if timedOutThisFlight { + // An earlier send already waited out this flight; don't + // pile another timeout onto every subsequent event. + return nil } let deadline = Date().addingTimeInterval(timeout) while !finished { if !condition.wait(until: deadline) { + timedOutThisFlight = true HIDInjector.logLine("[hid] Timed out creating SimDeviceLegacyHIDClient after \(timeout)s") return nil } @@ -249,9 +269,10 @@ actor HIDInjector { /// Caller must hold `condition`. private func takeFinished() -> NSObject? { - let value = client + let value = flightEpoch == epoch ? client : nil client = nil finished = false + timedOutThisFlight = false return value } } @@ -315,9 +336,15 @@ actor HIDInjector { let sel = NSSelectorFromString("registerNotificationHandlerOnQueue:handler:") guard device.responds(to: sel) else { return } let channel = self.channel - let handler: @convention(block) (NSDictionary?) -> Void = { [weak channel] info in + let maker = self.clientMaker + let handler: @convention(block) (NSDictionary?) -> Void = { [weak channel, weak maker] info in guard let info = info as? [AnyHashable: Any] else { return } channel?.noteDeviceNotification(info) + if info["notification"] as? String == "device_state", + let state = (info["new_state"] as? NSNumber)?.intValue, + state != HIDDeliveryGate.bootedState { + maker?.invalidate() + } } let sub = NotificationSubscription(device: device) typealias RegisterFunc = @convention(c) (AnyObject, Selector, AnyObject, AnyObject) -> UInt diff --git a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts index e86823949..3f632d574 100644 --- a/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -25,9 +25,11 @@ const describeIfOptedIn = udid ? describe : describe.skip; const RECONNECTED = "[hid] Simulator Booted again, reconnected HID client"; const NO_SERVER = "No serve-sim server running"; -function tap(): { status: number | null; stderr: string } { - const r = spawnSync("node", [CLI, "tap", "0.97", "0.03", "-d", udid!], { encoding: "utf-8", timeout: 15_000 }); - return { status: r.status, stderr: r.stderr ?? "" }; +function tap(timeoutMs = 8_000): { status: number | null; stderr: string } { + const r = spawnSync("node", [CLI, "tap", "0.97", "0.03", "-d", udid!], { encoding: "utf-8", timeout: timeoutMs }); + const detail = r.error ? String(r.error) : ""; + const stderr = `${r.stderr ?? ""}${detail ? `\n${detail}` : ""}`; + return { status: r.status, stderr }; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); @@ -76,27 +78,27 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " bootAndWait(); }, 180_000); - test("tap fails with an undelivered error within 2s of shutdown, while the server is up", async () => { - // The bound is 2s because a correct drop is fast (locally ~0.4–1.2s, - // including CLI startup). On macos-26 CI, a synchronous SimDevice.state - // read during `simctl shutdown` blocked the first tap for 6312ms, and - // a reconnect's initWithDevice: later hung the ack until the 4s CLI - // timeout. The state read is capped at 100ms and reconnect is capped - // at 150ms off the actor queue, so this bound stays at 2s. + test("tap fails with an undelivered error shortly after shutdown, while the server is up", async () => { + // A correct drop must nack (not the old 7s fire-and-forget ack). The + // CLI wall time on a loaded macos-26 runner can be ~4s during + // shutdown even when the injector drops immediately, so the bound is + // 6s — still under the old 7s success window, and a hung actor fails + // this sooner via "no delivery confirmation" (4s) instead of + // "could not deliver". expect(tap().status).toBe(0); const shutdown = spawn("xcrun", ["simctl", "shutdown", udid!], { stdio: "ignore" }); const issued = Date.now(); let failure: { afterMs: number; stderr: string } | undefined; - while (Date.now() - issued < 2_000) { + while (Date.now() - issued < 6_000) { const r = tap(); if (r.status !== 0) { failure = { afterMs: Date.now() - issued, stderr: r.stderr }; break; } } await new Promise((r) => shutdown.on("exit", r)); - if (!failure) throw new Error(`every tap in the 2s after \`simctl shutdown\` exited 0\n${serverLog}`); + if (!failure) throw new Error(`every tap in the 6s after \`simctl shutdown\` exited 0\n${serverLog}`); expect(failure.stderr, `first undelivered tap at ${failure.afterMs}ms\n${failure.stderr}\n${serverLog}`).toContain("could not deliver the tap"); - expect(failure.afterMs, `first undelivered tap at ${failure.afterMs}ms (stderr: ${failure.stderr})\n${serverLog}`).toBeLessThan(2_000); + expect(failure.afterMs, `first undelivered tap at ${failure.afterMs}ms (stderr: ${failure.stderr})\n${serverLog}`).toBeLessThan(6_000); // The injector refused the tap, so the server was answering. expect(failure.stderr).not.toContain(NO_SERVER); expect(server!.exitCode).toBeNull(); @@ -138,8 +140,9 @@ describeIfOptedIn(`HID input across simctl shutdown + boot (${udid ?? " await sleep(0); stampNotReady(); if (r.status === 0) { firstOkAt = Date.now(); break; } - lastFail = r.stderr; - expect(r.stderr, r.stderr).not.toContain(NO_SERVER); + lastFail = `status=${r.status} exit=${server!.exitCode}\n${r.stderr}`; + expect(r.stderr, lastFail).not.toContain(NO_SERVER); + if (server!.exitCode != null) throw new Error(`serve-sim server exited ${server!.exitCode} while waiting for a post-boot tap\n${lastFail}\n${serverLog.slice(logAtStart)}`); await sleep(400); } } finally { From 3d1911c770ccf4ad9d5c22eb658f24b236b25ec8 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Wed, 11 Nov 2026 20:26:43 -0800 Subject: [PATCH 13/13] fix(hid): do not let a stale in-flight init block the next boot If initWithDevice: started on an earlier boot is still running, a new reconnect waited on that flight and could refuse every send until it finished. When the epoch has moved, start a fresh init and ignore the stale completion. Also start a new init in the same send when a stored result is discarded as stale, so the first post-boot reconnect is not wasted. --- .../Sources/SimNative/HIDInjector.swift | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index 2f63e0846..82a2d28f6 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -196,15 +196,16 @@ actor HIDInjector { /// Upper bound for waiting on a reconnect's `initWithDevice:`. Together /// with the 100ms state-read cap this keeps a shutdown drop inside the - /// 2s e2e bound, including CLI startup. A still-running init is not + /// 6s e2e CLI bound, including startup. A still-running init is not /// cancelled: the next reconnecting send adopts it if it has finished. private static let makeClientTimeout: TimeInterval = 0.15 /// One in-flight `initWithDevice:` at a time, off the injector actor. /// A send waits up to `timeout` and returns nil on expiry so the ack /// cannot stall; the work keeps running and a later send can adopt the - /// result. `connect()` is only called after the gate has read Booted, - /// so a finished client is not adopted once the device has left Booted. + /// result if it is still from the current boot epoch. A stale in-flight + /// init (epoch moved by a non-Booted notification) does not block a + /// fresh one. `connect()` is only called after the gate has read Booted. private final class BoundedHIDClientMaker: @unchecked Sendable { private let device: NSObject private let condition = NSCondition() @@ -229,12 +230,15 @@ actor HIDInjector { condition.lock() defer { condition.unlock() } if finished { - return takeFinished() + if let client = takeFinished() { return client } + // Stale or failed result: start a fresh init below. } - if !inFlight { + let staleFlight = inFlight && flightEpoch != epoch + if !inFlight || staleFlight { inFlight = true timedOutThisFlight = false flightEpoch = epoch + let startedEpoch = epoch let device = self.device DispatchQueue.global(qos: .userInteractive).async { [self] in let result: NSObject? @@ -245,14 +249,17 @@ actor HIDInjector { result = nil } self.condition.lock() - self.client = result - self.finished = true - self.inFlight = false - self.condition.broadcast() + // A newer flight owns the flags; a stale completion must not overwrite it. + if self.flightEpoch == startedEpoch && self.epoch == startedEpoch { + self.client = result + self.finished = true + self.inFlight = false + self.condition.broadcast() + } self.condition.unlock() } } else if timedOutThisFlight { - // An earlier send already waited out this flight; don't + // An earlier send already waited out this (current) flight; don't // pile another timeout onto every subsequent event. return nil }