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/.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/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 360b9ee9b..82a2d28f6 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -44,8 +44,18 @@ 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 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. + private var completion: AnyObject? + private weak var completionClient: NSObject? private var simDevice: NSObject? private let springBoardLauncher = SpringBoardLauncher() private var deviceHubKeyboardBridge: DeviceHubKeyboardBridge? @@ -136,6 +146,146 @@ actor HIDInjector { } + // 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 + let maker = BoundedHIDClientMaker(device: device) + clientMaker = maker + channel = HIDClientChannel( + gate: gate, + connect: { + // initWithDevice: can block on a CoreSimulator lock during + // 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. + // 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) + } + + /// Upper bound for waiting on a reconnect's `initWithDevice:`. Together + /// with the 100ms state-read cap this keeps a shutdown drop inside the + /// 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 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() + 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() } + if finished { + if let client = takeFinished() { return client } + // Stale or failed result: start a fresh init below. + } + 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? + do { + result = try HIDInjector.makeHIDClient(device: device) + } catch { + HIDInjector.logLine("[hid] Could not create SimDeviceLegacyHIDClient: \(error.localizedDescription)") + result = nil + } + self.condition.lock() + // 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 (current) 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 + } + } + return takeFinished() + } + + /// Caller must hold `condition`. + private func takeFinished() -> NSObject? { + let value = flightEpoch == epoch ? client : nil + client = nil + finished = false + timedOutThisFlight = false + return value + } + } + + /// 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"]) @@ -156,19 +306,87 @@ 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)") + /// 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 + 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 + let id = unsafeBitCast(device.method(for: sel), to: RegisterFunc.self)( + device, sel, queue, handler as AnyObject) + sub.setID(id) + notifications = sub + } + + private func unregisterStateNotifications() { + notifications?.unregister() + notifications = nil + } + + /// 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 + // 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 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 + return block as AnyObject } // IndigoHIDEdge values (x4 param to IndigoHIDMessageForMouseNSEvent). @@ -181,25 +399,44 @@ actor HIDInjector { static let edgeLeft: UInt32 = 1 // Left edge static let edgeRight: UInt32 = 4 // Right edge - /// 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. - @discardableResult - private func rawSend(_ msg: UnsafeMutableRawPointer) -> Bool { - guard let client = hidClient, let sendSel = sendSel else { - print("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") - free(msg) - return false - } + /// 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)!, sendSel) else { + 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 } - unsafeBitCast(sendIMP, to: SendFunc.self)(client, sendSel, msg, ObjCBool(true), nil, nil) 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), 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({ [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 + } + /// Build a single-finger touch message (normalized 0..1 coords). Pure — safe /// to call off `inputQueue`. NSSize(1,1) makes ratio = point. private func touchMessage(type: String, x: Double, y: Double, edge: UInt32) -> UnsafeMutableRawPointer? { @@ -446,6 +683,11 @@ actor HIDInjector { /// Returns whether the press was handed to the guest. @discardableResult func sendButtonHID(page: UInt32, usage: UInt32, phase: String) async -> Bool { + // 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") @@ -484,7 +726,12 @@ 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 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 @@ -614,7 +861,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 } @@ -624,11 +874,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 } @@ -747,6 +1000,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/BoundedStateReader.swift b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift new file mode 100644 index 000000000..ddca9d602 --- /dev/null +++ b/packages/serve-sim/Sources/SimNativeSupport/BoundedStateReader.swift @@ -0,0 +1,89 @@ +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() + /// 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()`. 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 + self.read = read + self.queue = DispatchQueue(label: "hid-delivery-gate.state", qos: .userInteractive) + } + + public func probe() -> Probe { + lock.lock() + defer { lock.unlock() } + waiterCountStorage += 1 + defer { waiterCountStorage -= 1 } + + 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() + flight.value = result + flight.finished = true + if self.inFlight === flight { + self.inFlight = nil + } + self.lock.broadcast() + self.lock.unlock() + } + } + + let deadline = Date().addingTimeInterval(timeout) + while !flight.finished { + if !lock.wait(until: deadline) { + flight.timedOut = true + return .timedOut + } + } + return .ready(flight.value) + } +} diff --git a/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift new file mode 100644 index 000000000..4ff325fb3 --- /dev/null +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift @@ -0,0 +1,231 @@ +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" } + 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 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 { + case drop + case deliver + case probe + } + + 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 let notReadyProbeInterval: TimeInterval + private var notReady = false + private var notReadySince: TimeInterval? + private var lastNotReadyProbeAt: TimeInterval? + private var loggedNotReady = false + private var loggedNotReadyLimit = false + public private(set) var client: Client? + + public init( + gate: HIDDeliveryGate, + connect: @escaping () -> Client?, + log: @escaping (String) -> Void, + didReconnect: @escaping () -> Void = {}, + now: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }, + notReadyLimit: TimeInterval = HIDClientChannel.notReadyLimit, + notReadyProbeInterval: TimeInterval = HIDClientChannel.notReadyProbeInterval + ) { + self.gate = gate + self.makeClient = connect + self.log = log + 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() + clearNotReady() + 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 + clearNotReady() + } + + /// 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 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, `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: + guard let client else { + log("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") + return false + } + return transmit(client) + case .probe: + guard let client else { + log("[hid] Dropped HID message: no SimDeviceLegacyHIDClient") + return false + } + if probe?(client) == true { + lastNotReadyProbeAt = now() + } + return false + } + } + + /// 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. A not-ready error + /// (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) { + gate.noteClientDisconnected() + clearNotReady() + return + } + guard HIDDeliveryGate.isClientNotReady(domain: domain, code: code) else { return } + if !notReady { + notReady = true + notReadySince = now() + lastNotReadyProbeAt = nil + loggedNotReady = false + loggedNotReadyLimit = 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 } + clearNotReady() + } + + /// See `HIDDeliveryGate.noteNotification`. + public func noteDeviceNotification(_ info: [AnyHashable: Any]) { + gate.noteNotification(info) + } + + /// 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): + 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 { + guard notReady else { return .deliver } + logNotReadyOnce() + logNotReadyLimitOnce() + let t = now() + if let last = lastNotReadyProbeAt, t - last < notReadyProbeInterval { + return .drop + } + return .probe + } + + private func logNotReadyOnce() { + if !loggedNotReady { + log(Self.notReadyMessage) + loggedNotReady = true + } + } + + 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/Sources/SimNativeSupport/HIDDeliveryGate.swift b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift new file mode 100644 index 000000000..67dbe5bda --- /dev/null +++ b/packages/serve-sim/Sources/SimNativeSupport/HIDDeliveryGate.swift @@ -0,0 +1,134 @@ +import Foundation + +/// 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 +/// 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` 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. +/// 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 { + /// `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?) + } + + /// 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). 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 { + switch currentState() { + case .timedOut: + // 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") + 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) + } + } + + /// 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 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)" + case 1: return "Shutdown (state 1)" + case 2: return "Booting (state 2)" + case 4: return "Shutting Down (state 4)" + 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..f12eba79f --- /dev/null +++ b/packages/serve-sim/Tests/SimNativeSupportTests/BoundedStateReaderTests.swift @@ -0,0 +1,93 @@ +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 + // 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() + 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() + } + // 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() + 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 new file mode 100644 index 000000000..7a2bd63e8 --- /dev/null +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDClientChannelTests.swift @@ -0,0 +1,290 @@ +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 + var now: TimeInterval = 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 }, + now: { [unowned self] in self.now }, + notReadyLimit: 30, + notReadyProbeInterval: 0.5 + ) + }() + + 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) + // Still the same client: error 2 means "not ready", not "disconnected". + // The caller's event is not sent; a non-action probe is. + var sends = 0 + 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 testHIDError2DropsUntilASuccessfulProbe() { + 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 + // 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 }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(sends, 1) + XCTAssertEqual(probes, 1) + 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 + 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 }, 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 }, 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 }, probe: { _ in probes += 1; return true })) + XCTAssertEqual(sends, 1) + XCTAssertEqual(probes, 2) + XCTAssertEqual(h.connects, 1) + } + + 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 sends += 1; return true }, probe: { _ in probes += 1; return true })) + h.now = 30 + 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) + } + + 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 + _ = 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 new file mode 100644 index 000000000..aae70e04f --- /dev/null +++ b/packages/serve-sim/Tests/SimNativeSupportTests/HIDDeliveryGateTests.swift @@ -0,0 +1,156 @@ +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(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(reconnect: false)) + } + + 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(reconnect: false)) + 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(reconnect: true)) + 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(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)) + } + + + 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 + // 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 { + last = gate.admit() + if case .deliver = last { break } + Thread.sleep(forTimeInterval: 0.01) + } + XCTAssertEqual(last, .deliver(reconnect: false)) + } + + 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/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 new file mode 100644 index 000000000..3f632d574 --- /dev/null +++ b/packages/serve-sim/src/__tests__/hid-after-shutdown.e2e.test.ts @@ -0,0 +1,206 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +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 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 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; +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"; + +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)); + +/** 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 () => { + bootAndWait(); + try { execFileSync("node", [CLI, "--kill", udid!], { stdio: "pipe" }); } catch {} + const port = 40_000 + Math.floor(Math.random() * 20_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(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 {} + // Leave the simulator booted, as the test found it. + bootAndWait(); + }, 180_000); + + 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 < 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 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(6_000); + // The injector refused the tap, so the server was answering. + 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 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. 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 NOT_READY_LOG = "[hid] Dropping input: HID client is not ready"; + const logAtStart = serverLog.length; + let notReadyAt: number | undefined; + // 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; + if (serverLog.slice(logAtStart).includes(NOT_READY_LOG)) notReadyAt = Date.now(); + }; + const onData = () => { stampNotReady(); }; + stampNotReady(); + server!.stdout!.on("data", onData); + server!.stderr!.on("data", onData); + spawnSync("xcrun", ["simctl", "boot", udid!], { stdio: "ignore" }); + let firstOkAt: number | undefined; + 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; } + 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 { + server!.stdout!.off("data", onData); + server!.stderr!.off("data", onData); + } + 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(); + }, 150_000); + + 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); + 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); + + // 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); +}); 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]); + }); +}); diff --git a/packages/serve-sim/src/ci-test-plan.ts b/packages/serve-sim/src/ci-test-plan.ts index 61b88fdcd..3f3f7c71f 100644 --- a/packages/serve-sim/src/ci-test-plan.ts +++ b/packages/serve-sim/src/ci-test-plan.ts @@ -16,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", @@ -25,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 {