Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/sim-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
4 changes: 4 additions & 0 deletions packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
310 changes: 283 additions & 27 deletions packages/serve-sim/Sources/SimNative/HIDInjector.swift

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -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)
}
}
231 changes: 231 additions & 0 deletions packages/serve-sim/Sources/SimNativeSupport/HIDClientChannel.swift
Original file line number Diff line number Diff line change
@@ -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<Client: AnyObject> {
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<Client>.notReadyLimit,
notReadyProbeInterval: TimeInterval = HIDClientChannel<Client>.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
}
}
Loading
Loading