Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
8c0e056
Add iOS pairing timeout regression tests
lawrencecchen Jun 20, 2026
5686dec
Bound iOS pairing attempts
lawrencecchen Jun 20, 2026
d33c2ad
Add launch restore timeout regression test
lawrencecchen Jun 20, 2026
d5902c4
Bound launch session restore
lawrencecchen Jun 20, 2026
333157f
Merge remote-tracking branch 'origin/main' into feat-ios-pairing-timeout
lawrencecchen Jun 20, 2026
0b0b726
Restore cached sessions immediately
lawrencecchen Jun 20, 2026
e38879b
Prefer cached session over dev auto-login restore
lawrencecchen Jun 20, 2026
df6ad97
Tighten iOS pairing timeout races
lawrencecchen Jun 20, 2026
df9d816
Tear down timed-out mobile RPC connects
lawrencecchen Jun 20, 2026
c2ec2a1
Claim mobile RPC timeout before teardown
lawrencecchen Jun 20, 2026
e8a2711
Bound mobile RPC auth augmentation
lawrencecchen Jun 20, 2026
a2666ae
Cancel preinstalled mobile RPC connects
lawrencecchen Jun 20, 2026
d6c3a2b
Bound timed-out auth phase cleanup
lawrencecchen Jun 20, 2026
a674753
Refine mobile timeout cleanup
lawrencecchen Jun 20, 2026
c3b3453
Merge remote-tracking branch 'origin/main' into feat-ios-pairing-timeout
lawrencecchen Jun 20, 2026
dffd30f
Fold timeout race helpers into timeout files
lawrencecchen Jun 20, 2026
690aba5
Allow RPC connect retry after timeout
lawrencecchen Jun 20, 2026
3560472
Add CLI session restore debug command
lawrencecchen Jun 21, 2026
66cd6fe
Rename session restore diagnostics to sessions list
lawrencecchen Jun 21, 2026
306fa38
Merge remote-tracking branch 'origin/main' into feat-ios-pairing-timeout
lawrencecchen Jun 22, 2026
055e961
Guard late exchange cleanup during sign-out capture
lawrencecchen Jun 22, 2026
547a53d
Hold connect gate while abandoned close hangs
lawrencecchen Jun 22, 2026
bc3fdcb
Bound abandoned close cleanup gate release
lawrencecchen Jun 22, 2026
451a73a
Move CLI regression tests to Swift Testing
lawrencecchen Jun 22, 2026
e592ac7
Split sessions CLI diagnostics
lawrencecchen Jun 22, 2026
ad288e2
Localize sessions CLI diagnostics
lawrencecchen Jun 22, 2026
7ef841e
Fix sessions CLI tuple inference
lawrencecchen Jun 22, 2026
686b390
Stop canceled validation token probes
lawrencecchen Jun 22, 2026
c79ed0b
Fix Swift Testing assertion shims
lawrencecchen Jun 22, 2026
2d475b6
Scope CLI Swift Testing helpers
lawrencecchen Jun 22, 2026
5528388
Clear late exchange tokens after timeout
lawrencecchen Jun 22, 2026
624fdab
Bound host status token fallback
lawrencecchen Jun 22, 2026
99d0ec6
Deflake render grid event test
lawrencecchen Jun 22, 2026
ad0fa68
Speed up browser sign-out race test
lawrencecchen Jun 22, 2026
810f2f7
Deflake auth runtime package CI
lawrencecchen Jun 22, 2026
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 @@ -3,6 +3,49 @@ internal import CmuxMobileShellModel
internal import CmuxMobileSupport
public import Foundation

private final class RPCRequestTimeoutState<T: Sendable>: @unchecked Sendable {
private let lock = NSLock()
private var continuation: CheckedContinuation<T, any Error>?
private var cancelHandler: (@Sendable () -> Void)?

func install(_ continuation: CheckedContinuation<T, any Error>) {
lock.lock()
self.continuation = continuation
lock.unlock()
}

func setCancelHandler(_ handler: @escaping @Sendable () -> Void) {
lock.lock()
cancelHandler = handler
lock.unlock()
}

func resume(returning value: T) {
finish { $0.resume(returning: value) }
}

func resume(throwing error: any Error) {
finish { $0.resume(throwing: error) }
}

func cancel() {
finish { $0.resume(throwing: CancellationError()) }
}

private func finish(_ resume: (CheckedContinuation<T, any Error>) -> Void) {
lock.lock()
let continuation = continuation
let cancelHandler = cancelHandler
self.continuation = nil
self.cancelHandler = nil
lock.unlock()

guard let continuation else { return }
cancelHandler?()
resume(continuation)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 RPCRequestTimeoutState is missing the finished flag, risking a leaked CheckedContinuation

AuthPhaseTimeoutState (the direct model for this class) guards both install and setCancelHandler against a prior cancel() call via a finished: Bool flag. RPCRequestTimeoutState does not: its install unconditionally stores the continuation, and its setCancelHandler never calls the handler eagerly.

Concrete failure: withTaskCancellationHandler guarantees that if the task is already cancelled when the function is called, onCancel fires before the body runs. If that happens, state.cancel() reads a nil continuation and returns without resuming anything; then install stores the continuation that nothing will ever resume. The result is a permanently hung CheckedContinuation — a logged runtime warning in release and a crash on dealloc in debug builds — leaving the pairing spinner active indefinitely.

Second gap: if cancel() fires after install but before setCancelHandler, the continuation is correctly resumed with CancellationError, but operationTask and timeoutTask are never cancelled because setCancelHandler does not call the handler eagerly when already finished. The AuthPhaseTimeoutState addresses this with if finished { handler() } in setCancelHandler. The same two-line pattern needs to be added here.


/// A multiplexed RPC client over a single persistent transport to a paired Mac.
///
/// All stored properties are immutable `let`s of `Sendable` types (the session
Expand Down Expand Up @@ -320,24 +363,32 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable {
operation: @escaping @Sendable () async throws -> T
) async throws -> T {
try Task.checkCancellation()
return try await withThrowingTaskGroup(of: T.self) { group in
group.addTask {
try await operation()
}
group.addTask {
try await Task.sleep(nanoseconds: timeoutNanoseconds)
throw MobileShellConnectionError.requestTimedOut
}
do {
guard let result = try await group.next() else {
throw CancellationError()
let state = RPCRequestTimeoutState<T>()
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
state.install(continuation)
let operationTask = Task {
do {
state.resume(returning: try await operation())
} catch {
state.resume(throwing: error)
}
}
let timeoutTask = Task {
do {
try await Task.sleep(nanoseconds: timeoutNanoseconds)
} catch {
return
}
state.resume(throwing: MobileShellConnectionError.requestTimedOut)
}
state.setCancelHandler {
operationTask.cancel()
timeoutTask.cancel()
}
group.cancelAll()
return result
} catch {
group.cancelAll()
throw error
}
} onCancel: {
state.cancel()
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ public protocol MobileSyncRuntime: Sendable {
/// Shorter deadline for pairing-time requests (ticket mint, initial
/// workspace list), in nanoseconds.
var pairingRequestTimeoutNanoseconds: UInt64 { get }
/// Hard deadline for one user-initiated pairing attempt, in nanoseconds.
/// This bounds the whole QR/manual flow, not just one route or RPC.
var pairingAttemptTimeoutNanoseconds: UInt64 { get }
/// Whether the host supports server-pushed events. When `false`, the shell
/// skips background subscribe/poll so scripted-transport tests do not
/// consume responses intended for foreground methods.
Expand All @@ -40,6 +43,10 @@ public protocol MobileSyncRuntime: Sendable {
}

public extension MobileSyncRuntime {
/// Default user-facing pairing deadline. Individual RPCs can have their own
/// request timeout, but the sheet must not spin through stacked route waits.
var pairingAttemptTimeoutNanoseconds: UInt64 { 8_000_000_000 }

/// Default probe deadline: generous against a momentarily loaded Mac,
/// while keeping dead-stream recovery within a few seconds of the silence
/// threshold instead of the full ``rpcRequestTimeoutNanoseconds``.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1192,6 +1192,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
}

let directRoute = try? Self.manualHostRoute(host: normalizedHost, port: port)
activeRoute = directRoute
let attemptID = beginPairingAttempt(method: "manual")
// Fast offline preflight: fail immediately instead of stacking
// per-route timeouts into the opaque ~60s blob.
Expand Down Expand Up @@ -3324,6 +3325,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
// therefore cannot authorize, which is intended.
let routeAllowsStackAuthFallback = allowsStackAuthFallback
?? supportedRoutes.allSatisfy(MobileShellRouteAuthPolicy.routeAllowsStackAuth)
let pairingAttemptStartedAt = Date()
var lastError: (any Error)?
for route in supportedRoutes {
activeRoute = route
Expand All @@ -3336,9 +3338,16 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
)
for workspaceListRequest in workspaceListRequests {
do {
let requestTimeoutNanoseconds = Self.boundedPairingRequestTimeoutNanoseconds(
runtime: runtime,
attemptStartedAt: pairingAttemptStartedAt
)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
guard requestTimeoutNanoseconds > 0 else {
throw MobileShellConnectionError.requestTimedOut
}
let resultData = try await client.sendRequest(
workspaceListRequest.data,
timeoutNanoseconds: runtime.pairingRequestTimeoutNanoseconds
timeoutNanoseconds: requestTimeoutNanoseconds
)
let response = try MobileSyncWorkspaceListResponse.decode(resultData)
guard isCurrentConnectionAttempt(generation) else { return nil }
Expand Down Expand Up @@ -3381,11 +3390,28 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
}
}

clearRemoteConnectionContext()
diagnosticLog?.record(DiagnosticEvent(.pairFail))
throw lastError ?? MobileShellConnectionError.connectionClosed
}

private static func boundedPairingRequestTimeoutNanoseconds(
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
runtime: any MobileSyncRuntime,
attemptStartedAt: Date
) -> UInt64 {
let requestTimeout = runtime.pairingRequestTimeoutNanoseconds
let attemptTimeout = runtime.pairingAttemptTimeoutNanoseconds
guard attemptTimeout > 0 else {
return requestTimeout
}

let elapsedSeconds = max(0, Date().timeIntervalSince(attemptStartedAt))
let elapsedNanoseconds = UInt64((elapsedSeconds * 1_000_000_000).rounded(.up))
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
guard elapsedNanoseconds < attemptTimeout else {
return 0
}
return min(requestTimeout, attemptTimeout - elapsedNanoseconds)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Wall-clock Date() bypasses the injected runtime.now clock

boundedPairingRequestTimeoutNanoseconds calls Date() directly to measure elapsed time, and the call site captures pairingAttemptStartedAt the same way. MobileSyncRuntime already carries a now: @Sendable () -> Date injectable clock precisely so time-dependent paths can be exercised deterministically.

Because both reads use the system clock, the new deadline math cannot be controlled in tests — the test in MobilePairingAttemptDeadlineTests works around this by setting pairingAttemptTimeoutNanoseconds to a 1 ms budget instead of driving injected time. Passing runtime.now into boundedPairingRequestTimeoutNanoseconds (and using it for pairingAttemptStartedAt) would keep the approach consistent with the rest of the codebase.


private struct WorkspaceListRequest {
var data: Data
var isScoped: Bool
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import CMUXMobileCore
import CmuxMobileRPC
import CmuxMobileShellModel
import CmuxMobileTransport
import Foundation
import Testing
@testable import CmuxMobileShell

@MainActor
@Suite struct MobilePairingAttemptDeadlineTests {
@Test func qrPairingURLTimesOutWithoutWaitingForStuckTransport() async throws {
let store = makeStore()
let startedAt = Date()

let result = await store.connectPairingURLResult(Self.qrURL)

#expect(result == .failed)
#expect(store.connectionState == .disconnected)
#expect(store.connectionError?.isEmpty == false)
#expect(store.connectionError?.contains("100.64.0.5") == true)
#expect(Date().timeIntervalSince(startedAt) < 0.05)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

@Test func scannedOrPastedPairingInputUsesSameDeadline() async throws {
let store = makeStore(pairingCode: Self.qrURL)
let startedAt = Date()

await store.connectPairingInput()

#expect(store.connectionState == .disconnected)
#expect(store.connectionError?.isEmpty == false)
#expect(store.connectionError?.contains("100.64.0.5") == true)
#expect(Date().timeIntervalSince(startedAt) < 0.05)
}

private static let qrURL = "cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465"

private func makeStore(pairingCode: String = "") -> MobileShellComposite {
MobileShellComposite(
runtime: PairingDeadlineRuntime(),
isSignedIn: true,
pairingCode: pairingCode,
reachability: AlwaysOnlineReachability(),
pairingHintDefaults: UserDefaults(suiteName: "pairing-deadline-\(UUID().uuidString)")!
)
}
}

private struct PairingDeadlineRuntime: MobileSyncRuntime {
var transportFactory: any CmxByteTransportFactory = SlowIgnoringCancellationTransportFactory()
var stackAccessTokenProvider: @Sendable () async throws -> String = { "test-stack-token" }
var stackAccessTokenForceRefresher: @Sendable () async throws -> String = { "test-stack-token" }
var rpcRequestTimeoutNanoseconds: UInt64 = 30 * 1_000_000_000
var now: @Sendable () -> Date = { Date() }
var supportedRouteKinds: [CmxAttachTransportKind] = [.tailscale]
var pairingRequestTimeoutNanoseconds: UInt64 = 30 * 1_000_000_000
var pairingAttemptTimeoutNanoseconds: UInt64 = 1_000_000
var supportsServerPushEvents: Bool = false
}

private struct AlwaysOnlineReachability: ReachabilityProviding {
var isOnline: Bool { get async { true } }

func pathChanges() -> AsyncStream<Void> {
AsyncStream { continuation in
continuation.finish()
}
}
}

private struct SlowIgnoringCancellationTransportFactory: CmxByteTransportFactory {
func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport {
SlowIgnoringCancellationTransport()
}
}

private actor SlowIgnoringCancellationTransport: CmxByteTransport {
func connect() async throws {
let startedAt = Date()
while Date().timeIntervalSince(startedAt) < 0.2 {
try? await Task.sleep(nanoseconds: 10_000_000)
}
throw CmxNetworkByteTransportError.connectionTimedOut
}

func receive() async throws -> Data? {
nil
}

func send(_ data: Data) async throws {}

func close() async {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ func makeTicket(clock: TestClock) throws -> CmxAttachTicket {
terminalID: "live-terminal",
macDeviceID: "test-mac",
macDisplayName: "Test Mac",
macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion,
routes: [route],
expiresAt: clock.now.addingTimeInterval(3600)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ struct MobilePairingScannerSheet: View {
switch authorizationStatus {
case .authorized:
QRCodeScannerView { code in
dismiss()
onCode(code)
}
.ignoresSafeArea(edges: .bottom)
Expand Down
6 changes: 6 additions & 0 deletions ios/cmuxPackage/Sources/cmuxFeature/CMUXMobileRuntime.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import OSLog
public struct CMUXMobileRuntime: Sendable, MobileSyncRuntime {
public static let defaultRPCRequestTimeoutNanoseconds: UInt64 = 30 * 1_000_000_000
public static let defaultPairingRequestTimeoutNanoseconds: UInt64 = 8 * 1_000_000_000
public static let defaultPairingAttemptTimeoutNanoseconds: UInt64 = 8 * 1_000_000_000

public var supportedRouteKinds: [CmxAttachTransportKind]
public var transportFactory: any CmxByteTransportFactory
Expand All @@ -20,6 +21,7 @@ public struct CMUXMobileRuntime: Sendable, MobileSyncRuntime {
public var stackAccessTokenForceRefresher: @Sendable () async throws -> String
public var rpcRequestTimeoutNanoseconds: UInt64
public var pairingRequestTimeoutNanoseconds: UInt64
public var pairingAttemptTimeoutNanoseconds: UInt64
public var now: @Sendable () -> Date
/// When false, `MobileShellStore` skips background terminal refresh.
/// Scripted transport tests set this off so background subscribe/poll
Expand Down Expand Up @@ -112,6 +114,7 @@ public struct CMUXMobileRuntime: Sendable, MobileSyncRuntime {
stackAccessTokenForceRefresher: (@Sendable () async throws -> String)? = nil,
rpcRequestTimeoutNanoseconds: UInt64 = CMUXMobileRuntime.defaultRPCRequestTimeoutNanoseconds,
pairingRequestTimeoutNanoseconds: UInt64 = CMUXMobileRuntime.defaultPairingRequestTimeoutNanoseconds,
pairingAttemptTimeoutNanoseconds: UInt64 = CMUXMobileRuntime.defaultPairingAttemptTimeoutNanoseconds,
now: @escaping @Sendable () -> Date = Date.init,
supportsServerPushEvents: Bool = true
) {
Expand All @@ -121,6 +124,7 @@ public struct CMUXMobileRuntime: Sendable, MobileSyncRuntime {
self.stackAccessTokenForceRefresher = stackAccessTokenForceRefresher ?? { throw AuthError.unauthorized }
self.rpcRequestTimeoutNanoseconds = rpcRequestTimeoutNanoseconds
self.pairingRequestTimeoutNanoseconds = pairingRequestTimeoutNanoseconds
self.pairingAttemptTimeoutNanoseconds = pairingAttemptTimeoutNanoseconds
self.now = now
self.supportsServerPushEvents = supportsServerPushEvents
}
Expand All @@ -131,6 +135,7 @@ public struct CMUXMobileRuntime: Sendable, MobileSyncRuntime {
stackAccessTokenForceRefresher: (@Sendable () async throws -> String)? = nil,
rpcRequestTimeoutNanoseconds: UInt64 = CMUXMobileRuntime.defaultRPCRequestTimeoutNanoseconds,
pairingRequestTimeoutNanoseconds: UInt64 = CMUXMobileRuntime.defaultPairingRequestTimeoutNanoseconds,
pairingAttemptTimeoutNanoseconds: UInt64 = CMUXMobileRuntime.defaultPairingAttemptTimeoutNanoseconds,
now: @escaping @Sendable () -> Date = Date.init,
supportsServerPushEvents: Bool = true
) {
Expand All @@ -140,6 +145,7 @@ public struct CMUXMobileRuntime: Sendable, MobileSyncRuntime {
self.stackAccessTokenForceRefresher = stackAccessTokenForceRefresher ?? { throw AuthError.unauthorized }
self.rpcRequestTimeoutNanoseconds = rpcRequestTimeoutNanoseconds
self.pairingRequestTimeoutNanoseconds = pairingRequestTimeoutNanoseconds
self.pairingAttemptTimeoutNanoseconds = pairingAttemptTimeoutNanoseconds
self.supportsServerPushEvents = supportsServerPushEvents
self.now = now
}
Expand Down
Loading