From 30c424ca8e21fb221dea77104ffee1fda8df65b5 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Thu, 16 Jul 2026 12:43:39 -0700 Subject: [PATCH 01/21] Mobile state sync v2: per-record deltas replace invalidate-and-refetch Adds a versioned delta protocol for the iOS workspace list. The Mac keeps an epoch + per-collection revision store of typed workspace/group records, answers mobile.sync.fetch with a snapshot or the exact missing span, and pushes mobile.sync.delta events carrying only the rows a change touched. The phone mirrors records with a cursor, projects them through the same applyRemoteWorkspaceList path the legacy full list uses, and stops re-fetching the entire list on every workspace.updated push. Legacy phones and Macs keep today's behavior via method_not_found negotiation. Design doc: docs/mobile-state-sync-v2.md Co-Authored-By: Claude Fable 5 --- .../MobileStateSyncFrames.swift | 185 +++++++++++++++ .../MobileStateSyncMirror.swift | 152 ++++++++++++ .../MobileStateSyncRecords.swift | 170 ++++++++++++++ .../CMUXMobileCore/MobileStateSyncStore.swift | 184 +++++++++++++++ .../MobileStateSyncFrameCodingTests.swift | 129 ++++++++++ .../MobileStateSyncMirrorTests.swift | 168 +++++++++++++ .../MobileStateSyncStoreTests.swift | 188 +++++++++++++++ .../MobileSyncWorkspaceListResponse.swift | 81 +++++++ .../MobileShellComposite+StateSync.swift | 174 ++++++++++++++ .../MobileShellComposite.swift | 31 ++- ...leShellRenderGridLivenessTestSupport.swift | 26 ++- .../MobileShellStateSyncTests.swift | 204 ++++++++++++++++ ...obileHostService+TicketAuthorization.swift | 4 + Sources/Mobile/MobileStateSync.swift | 220 ++++++++++++++++++ .../Mobile/MobileWorkspaceListObserver.swift | 4 + Sources/TerminalController.swift | 2 + cmux.xcodeproj/project.pbxproj | 4 + docs/mobile-state-sync-v2.md | 104 +++++++++ 18 files changed, 2025 insertions(+), 5 deletions(-) create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift create mode 100644 Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift create mode 100644 Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncMirrorTests.swift create mode 100644 Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift create mode 100644 Sources/Mobile/MobileStateSync.swift create mode 100644 docs/mobile-state-sync-v2.md diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift new file mode 100644 index 000000000000..22807f3682e4 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift @@ -0,0 +1,185 @@ +import Foundation + +/// Client-held position in one collection's revision stream. Only meaningful +/// while the Mac's `epoch` is unchanged; a cursor from another epoch always +/// resolves to a snapshot. +public struct MobileSyncCursor: Codable, Equatable, Sendable { + public let epoch: String + public let rev: UInt64 + + public init(epoch: String, rev: UInt64) { + self.epoch = epoch + self.rev = rev + } +} + +/// How a fetch response section carries its records. +public enum MobileSyncPayloadMode: String, Codable, Sendable { + /// `records` is the full row set; replace local state. + case snapshot + /// `records`/`removed_ids` are changes in `(from_rev, rev]`; apply over + /// local state at `from_rev` or newer. + case delta +} + +/// One collection section of a `mobile.sync.fetch` response. +public struct MobileSyncCollectionPayload: Codable, Equatable, Sendable { + public let mode: MobileSyncPayloadMode + /// Head revision the payload brings the client to. + public let rev: UInt64 + /// The client revision this delta starts from. Absent for snapshots. + public let fromRev: UInt64? + public let records: [Record] + public let removedIDs: [String] + + public init( + mode: MobileSyncPayloadMode, + rev: UInt64, + fromRev: UInt64?, + records: [Record], + removedIDs: [String] + ) { + self.mode = mode + self.rev = rev + self.fromRev = fromRev + self.records = records + self.removedIDs = removedIDs + } + + private enum CodingKeys: String, CodingKey { + case mode + case rev + case fromRev = "from_rev" + case records + case removedIDs = "removed_ids" + } +} + +/// The `mobile.sync.fetch` request body: one cursor entry per collection the +/// client wants. A missing cursor means cold start (snapshot). +public struct MobileSyncFetchRequest: Codable, Equatable, Sendable { + public struct Collection: Codable, Equatable, Sendable { + public let id: MobileSyncCollectionID + public let epoch: String? + public let rev: UInt64? + + public init(id: MobileSyncCollectionID, epoch: String?, rev: UInt64?) { + self.id = id + self.epoch = epoch + self.rev = rev + } + + /// The cursor this entry carries, when it carries a complete one. + public var cursor: MobileSyncCursor? { + guard let epoch, let rev else { return nil } + return MobileSyncCursor(epoch: epoch, rev: rev) + } + } + + public let collections: [Collection] + + public init(collections: [Collection]) { + self.collections = collections + } +} + +/// The `mobile.sync.fetch` response body. Sections are optional so the shape +/// can grow collections without breaking older peers; a client ignores +/// sections it did not request and tolerates missing ones. +public struct MobileSyncFetchResponse: Codable, Equatable, Sendable { + public let epoch: String + public let workspaces: MobileSyncCollectionPayload? + public let groups: MobileSyncCollectionPayload? + + public init( + epoch: String, + workspaces: MobileSyncCollectionPayload?, + groups: MobileSyncCollectionPayload? + ) { + self.epoch = epoch + self.workspaces = workspaces + self.groups = groups + } +} + +/// One `mobile.sync.delta` event: the changes one producer tick made to one +/// collection. Applies iff the epoch matches and `from_rev <= local rev` +/// (idempotent overlap); `from_rev > local rev` is a gap the client repairs +/// with a cursor fetch. +public struct MobileSyncDeltaEvent: Codable, Equatable, Sendable { + public let epoch: String + public let collection: MobileSyncCollectionID + public let fromRev: UInt64 + public let toRev: UInt64 + public let records: [Record] + public let removedIDs: [String] + + public init( + epoch: String, + collection: MobileSyncCollectionID, + fromRev: UInt64, + toRev: UInt64, + records: [Record], + removedIDs: [String] + ) { + self.epoch = epoch + self.collection = collection + self.fromRev = fromRev + self.toRev = toRev + self.records = records + self.removedIDs = removedIDs + } + + private enum CodingKeys: String, CodingKey { + case epoch + case collection + case fromRev = "from_rev" + case toRev = "to_rev" + case records + case removedIDs = "removed_ids" + } +} + +/// Collection discriminator decoded before choosing the typed +/// `MobileSyncDeltaEvent` record type for a `mobile.sync.delta` payload. +public struct MobileSyncDeltaEventHeader: Codable, Equatable, Sendable { + public let collection: MobileSyncCollectionID + + public init(collection: MobileSyncCollectionID) { + self.collection = collection + } +} + +/// JSON bridging between the typed frames and the `[String: Any]` payloads the +/// mobile RPC envelope carries. One round-trip through `JSONSerialization` per +/// frame; frames are small (changed rows only), so this stays off every hot +/// path that matters. +public enum MobileSyncFrameJSON { + public static func jsonObject(from value: some Encodable) throws -> [String: Any] { + let data = try JSONEncoder().encode(value) + guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { + throw MobileSyncFrameJSONError.notAnObject + } + return object + } + + public static func decode( + _ type: Value.Type, + fromJSONObject object: [String: Any] + ) throws -> Value { + let data = try JSONSerialization.data(withJSONObject: object) + return try JSONDecoder().decode(type, from: data) + } + + public static func decode( + _ type: Value.Type, + fromJSONString string: String + ) throws -> Value { + try JSONDecoder().decode(type, from: Data(string.utf8)) + } +} + +/// Failure bridging a sync frame to or from the RPC envelope's JSON container. +public enum MobileSyncFrameJSONError: Error, Equatable, Sendable { + case notAnObject +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift new file mode 100644 index 000000000000..cc8405000825 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift @@ -0,0 +1,152 @@ +/// Outcome of applying a sync frame to a client mirror. +public enum MobileSyncApplyResult: Equatable, Sendable { + /// The frame advanced (or re-covered) local state. + case applied + /// The frame ended at or before the local revision; nothing to do. + case staleIgnored + /// The frame starts past the local revision or belongs to another epoch; + /// the caller must repair with a cursor fetch. + case gap +} + +/// Client-side mirror of one synced collection. +/// +/// Holds full records keyed by id plus the cursor that proves how current they +/// are. Deltas apply iff contiguous-or-overlapping within the same epoch; +/// anything else reports `.gap` and leaves state untouched so the repair fetch +/// has a stable cursor to send. Main-actor confined to match its only +/// consumer, the shell state. +@MainActor +public final class MobileSyncCollectionMirror { + public private(set) var epoch: String? + public private(set) var rev: UInt64 = 0 + private var recordsByID: [String: Record] = [:] + + public init() {} + + /// Records in presentation order: `syncSortIndex`, then id for + /// determinism when a delta lands between two rows' index updates. + public var orderedRecords: [Record] { + recordsByID.values.sorted { + ($0.syncSortIndex, $0.syncID) < ($1.syncSortIndex, $1.syncID) + } + } + + /// Whether the mirror has adopted any state for `epoch` yet. + public var hasState: Bool { epoch != nil } + + /// The cursor to present in a `mobile.sync.fetch`, once state exists. + public var cursor: MobileSyncCursor? { + guard let epoch else { return nil } + return MobileSyncCursor(epoch: epoch, rev: rev) + } + + /// Applies one fetch response section. Snapshots replace state + /// unconditionally; deltas follow the same contiguity rule as events. + public func apply(payload: MobileSyncCollectionPayload, epoch payloadEpoch: String) -> MobileSyncApplyResult { + switch payload.mode { + case .snapshot: + recordsByID = Dictionary( + payload.records.map { ($0.syncID, $0) }, + uniquingKeysWith: { _, last in last } + ) + epoch = payloadEpoch + rev = payload.rev + return .applied + case .delta: + return applyChanges( + epoch: payloadEpoch, + fromRev: payload.fromRev ?? payload.rev, + toRev: payload.rev, + records: payload.records, + removedIDs: payload.removedIDs + ) + } + } + + /// Applies one `mobile.sync.delta` event. + public func apply(delta: MobileSyncDeltaEvent) -> MobileSyncApplyResult { + applyChanges( + epoch: delta.epoch, + fromRev: delta.fromRev, + toRev: delta.toRev, + records: delta.records, + removedIDs: delta.removedIDs + ) + } + + private func applyChanges( + epoch changeEpoch: String, + fromRev: UInt64, + toRev: UInt64, + records: [Record], + removedIDs: [String] + ) -> MobileSyncApplyResult { + guard let epoch, epoch == changeEpoch else { return .gap } + guard fromRev <= rev else { return .gap } + guard toRev > rev else { return .staleIgnored } + for record in records { + recordsByID[record.syncID] = record + } + for id in removedIDs { + recordsByID[id] = nil + } + rev = toRev + return .applied + } + + /// Drops all state (disconnect-forget, sign-out, Mac unpair). The next + /// fetch is a cold start. + public func reset() { + epoch = nil + rev = 0 + recordsByID = [:] + } +} + +/// Client-side root mirror pairing the two synced collections, with the +/// cursor plumbing a `mobile.sync.fetch` round-trip needs. +@MainActor +public final class MobileStateSyncMirror { + public let workspaces = MobileSyncCollectionMirror() + public let groups = MobileSyncCollectionMirror() + + public init() {} + + /// The fetch request that brings both collections current from their + /// respective cursors (snapshots on cold start). + public var fetchRequest: MobileSyncFetchRequest { + MobileSyncFetchRequest(collections: [ + MobileSyncFetchRequest.Collection( + id: .workspaces, + epoch: workspaces.cursor?.epoch, + rev: workspaces.cursor?.rev + ), + MobileSyncFetchRequest.Collection( + id: .groups, + epoch: groups.cursor?.epoch, + rev: groups.cursor?.rev + ), + ]) + } + + /// Applies a fetch response to both collections. Returns `.gap` if either + /// section gapped (caller re-fetches), `.applied` if anything advanced. + public func apply(response: MobileSyncFetchResponse) -> MobileSyncApplyResult { + var results: [MobileSyncApplyResult] = [] + if let payload = response.workspaces { + results.append(workspaces.apply(payload: payload, epoch: response.epoch)) + } + if let payload = response.groups { + results.append(groups.apply(payload: payload, epoch: response.epoch)) + } + if results.contains(.gap) { return .gap } + if results.contains(.applied) { return .applied } + return .staleIgnored + } + + public func reset() { + workspaces.reset() + groups.reset() + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift new file mode 100644 index 000000000000..750ed8a3ab1a --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift @@ -0,0 +1,170 @@ +/// A record participating in mobile state sync v2 (`docs/mobile-state-sync-v2.md`). +/// +/// Records are full rows keyed by a stable id: a delta frame carries the whole +/// changed record, never a field patch, so overlapping frames apply +/// idempotently and the client never needs field-merge logic. Equality drives +/// the Mac-side diff: a record that compares equal to the stored one bumps no +/// revision and travels on no wire. +public protocol MobileSyncRecord: Codable, Equatable, Sendable { + /// Stable identity within the collection (workspace/group UUID string). + var syncID: String { get } + /// Position in the Mac's presented order. The client sorts by this, then by + /// `syncID` for determinism when indices collide mid-delta. + var syncSortIndex: Int { get } +} + +/// Identifies a synced collection on the wire. A raw string wrapper (not an +/// enum) so an older client can skip frames for collections it does not know +/// instead of failing to decode the envelope. +public struct MobileSyncCollectionID: RawRepresentable, Codable, Hashable, Sendable { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + /// The flattened cross-window workspace list. + public static let workspaces = MobileSyncCollectionID(rawValue: "workspaces") + /// Workspace group sections. + public static let groups = MobileSyncCollectionID(rawValue: "groups") +} + +/// One workspace row, mirroring the fields of the legacy +/// `mobile.workspace.list` payload (same snake_case wire names) plus an +/// explicit `sort_index` so list order syncs without positional inference. +public struct WorkspaceSyncRecord: MobileSyncRecord { + /// One terminal row within a workspace. + public struct Terminal: Codable, Equatable, Sendable { + public let id: String + public let title: String + public let currentDirectory: String? + public let isReady: Bool + public let isFocused: Bool + + public init( + id: String, + title: String, + currentDirectory: String?, + isReady: Bool, + isFocused: Bool + ) { + self.id = id + self.title = title + self.currentDirectory = currentDirectory + self.isReady = isReady + self.isFocused = isFocused + } + + private enum CodingKeys: String, CodingKey { + case id + case title + case currentDirectory = "current_directory" + case isReady = "is_ready" + case isFocused = "is_focused" + } + } + + public let id: String + public let windowID: String? + public let title: String + public let currentDirectory: String? + public let isSelected: Bool + public let isPinned: Bool + public let groupID: String? + public let preview: String? + public let previewAt: Double? + public let lastActivityAt: Double + public let hasUnread: Bool + public let sortIndex: Int + public let terminals: [Terminal] + + public var syncID: String { id } + public var syncSortIndex: Int { sortIndex } + + public init( + id: String, + windowID: String?, + title: String, + currentDirectory: String?, + isSelected: Bool, + isPinned: Bool, + groupID: String?, + preview: String?, + previewAt: Double?, + lastActivityAt: Double, + hasUnread: Bool, + sortIndex: Int, + terminals: [Terminal] + ) { + self.id = id + self.windowID = windowID + self.title = title + self.currentDirectory = currentDirectory + self.isSelected = isSelected + self.isPinned = isPinned + self.groupID = groupID + self.preview = preview + self.previewAt = previewAt + self.lastActivityAt = lastActivityAt + self.hasUnread = hasUnread + self.sortIndex = sortIndex + self.terminals = terminals + } + + private enum CodingKeys: String, CodingKey { + case id + case windowID = "window_id" + case title + case currentDirectory = "current_directory" + case isSelected = "is_selected" + case isPinned = "is_pinned" + case groupID = "group_id" + case preview + case previewAt = "preview_at" + case lastActivityAt = "last_activity_at" + case hasUnread = "has_unread" + case sortIndex = "sort_index" + case terminals + } +} + +/// One workspace group section, mirroring the legacy list payload's group +/// fields. Membership stays derived on the client from each workspace's +/// `group_id` in workspace order, exactly as the legacy list is consumed, so +/// this record intentionally carries no member array to invalidate. +public struct GroupSyncRecord: MobileSyncRecord { + public let id: String + public let name: String + public let isCollapsed: Bool + public let isPinned: Bool + public let anchorWorkspaceID: String + public let sortIndex: Int + + public var syncID: String { id } + public var syncSortIndex: Int { sortIndex } + + public init( + id: String, + name: String, + isCollapsed: Bool, + isPinned: Bool, + anchorWorkspaceID: String, + sortIndex: Int + ) { + self.id = id + self.name = name + self.isCollapsed = isCollapsed + self.isPinned = isPinned + self.anchorWorkspaceID = anchorWorkspaceID + self.sortIndex = sortIndex + } + + private enum CodingKeys: String, CodingKey { + case id + case name + case isCollapsed = "is_collapsed" + case isPinned = "is_pinned" + case anchorWorkspaceID = "anchor_workspace_id" + case sortIndex = "sort_index" + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift new file mode 100644 index 000000000000..a1a0292b14e1 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift @@ -0,0 +1,184 @@ +import Foundation + +/// The changes one `apply(rows:)` tick made to a collection, shaped for direct +/// embedding in a `mobile.sync.delta` event. `nil` change means the tick was a +/// no-op and nothing travels. +public struct MobileSyncCollectionChange: Equatable, Sendable { + public let fromRev: UInt64 + public let toRev: UInt64 + public let records: [Record] + public let removedIDs: [String] +} + +/// Mac-side versioned store for one synced collection. +/// +/// The producer hands it the full current row set on every change tick; the +/// store diffs by record equality, stamps changed rows with a single new head +/// revision, records removals as bounded tombstones, and answers cursor +/// queries with a delta when the cursor is coverable and a snapshot otherwise. +/// Confined to the main actor because every producer input (TabManager, +/// notification store) and every consumer (RPC handlers) already lives there. +@MainActor +public final class MobileSyncCollectionStore { + /// A record plus the head revision that last changed it. + private struct Stamped { + let record: Record + let rev: UInt64 + } + + private struct Tombstone { + let id: String + let rev: UInt64 + } + + /// Upper bound on retained tombstones. A cursor older than the oldest + /// retained removal cannot prove it missed no removal, so it gets a + /// snapshot. 1024 removals between two client fetches is far past any real + /// workspace-churn rate; the bound exists so memory never tracks history. + private let maximumTombstoneCount: Int + + public private(set) var headRev: UInt64 = 0 + private var stampedByID: [String: Stamped] = [:] + private var tombstones: [Tombstone] = [] + /// True once tombstones have been discarded to honor the bound; from then + /// on only cursors at or above the oldest retained tombstone are coverable. + private var droppedTombstones = false + + public init(maximumTombstoneCount: Int = 1024) { + self.maximumTombstoneCount = maximumTombstoneCount + } + + /// All current records, unordered. Ordering is the client's job via + /// `syncSortIndex`. + public var records: [Record] { + stampedByID.values.map(\.record) + } + + /// Diffs `rows` against the stored state. Changed and new rows are stamped + /// with one new head revision; rows absent from `rows` become tombstones at + /// that same revision. Returns `nil` when nothing changed (head unmoved). + public func apply(rows: [Record]) -> MobileSyncCollectionChange? { + var changed: [Record] = [] + var seenIDs = Set() + seenIDs.reserveCapacity(rows.count) + for row in rows { + guard seenIDs.insert(row.syncID).inserted else { continue } + if stampedByID[row.syncID]?.record != row { + changed.append(row) + } + } + let removedIDs = stampedByID.keys.filter { !seenIDs.contains($0) } + guard !changed.isEmpty || !removedIDs.isEmpty else { return nil } + + let fromRev = headRev + headRev += 1 + for row in changed { + stampedByID[row.syncID] = Stamped(record: row, rev: headRev) + } + for id in removedIDs { + stampedByID[id] = nil + tombstones.append(Tombstone(id: id, rev: headRev)) + } + if tombstones.count > maximumTombstoneCount { + tombstones.removeFirst(tombstones.count - maximumTombstoneCount) + droppedTombstones = true + } + return MobileSyncCollectionChange( + fromRev: fromRev, + toRev: headRev, + records: changed, + removedIDs: removedIDs + ) + } + + /// Whether a delta from `rev` can prove completeness. Coverable means every + /// removal after `rev` is still retained; otherwise the client must + /// snapshot. Upserts are always coverable because records store their full + /// current row. + private func canCover(rev: UInt64) -> Bool { + guard rev <= headRev else { return false } + guard droppedTombstones else { return true } + guard let oldestRetained = tombstones.first?.rev else { + // All tombstones were discarded; only a fully current cursor needs + // no removal history. + return rev == headRev + } + // A cursor at `rev` needs every removal with rev > `rev`. Retained + // tombstones start at `oldestRetained`, so anything at or after + // `oldestRetained - 1` is provably complete. + return rev >= oldestRetained - 1 + } + + /// Answers one fetch section for a client at `cursor`. `nil` cursor, an + /// epoch handled as mismatched by the caller, an uncoverable revision, or a + /// future revision all resolve to a snapshot. + public func payload(since rev: UInt64?) -> MobileSyncCollectionPayload { + guard let rev, rev != headRev, canCover(rev: rev) else { + if let rev, rev == headRev { + return MobileSyncCollectionPayload( + mode: .delta, + rev: headRev, + fromRev: rev, + records: [], + removedIDs: [] + ) + } + return MobileSyncCollectionPayload( + mode: .snapshot, + rev: headRev, + fromRev: nil, + records: records, + removedIDs: [] + ) + } + let upserts = stampedByID.values.filter { $0.rev > rev }.map(\.record) + let removals = tombstones.filter { $0.rev > rev }.map(\.id) + return MobileSyncCollectionPayload( + mode: .delta, + rev: headRev, + fromRev: rev, + records: upserts, + removedIDs: removals + ) + } +} + +/// The Mac's root sync store: one epoch spanning every collection, plus the +/// per-collection stores. Created once per app launch; the fresh epoch is what +/// invalidates every client cursor from a previous run. +@MainActor +public final class MobileStateSyncStore { + public let epoch: String + public let workspaces: MobileSyncCollectionStore + public let groups: MobileSyncCollectionStore + + public init(epoch: String = UUID().uuidString) { + self.epoch = epoch + self.workspaces = MobileSyncCollectionStore() + self.groups = MobileSyncCollectionStore() + } + + /// Answers a full `mobile.sync.fetch` request. Cursor epochs that do not + /// match the store's epoch are treated as absent, which resolves to + /// snapshots. + public func fetchResponse(for request: MobileSyncFetchRequest) -> MobileSyncFetchResponse { + var workspacesPayload: MobileSyncCollectionPayload? + var groupsPayload: MobileSyncCollectionPayload? + for collection in request.collections { + let rev = collection.epoch == epoch ? collection.rev : nil + switch collection.id { + case .workspaces: + workspacesPayload = workspaces.payload(since: rev) + case .groups: + groupsPayload = groups.payload(since: rev) + default: + continue + } + } + return MobileSyncFetchResponse( + epoch: epoch, + workspaces: workspacesPayload, + groups: groupsPayload + ) + } +} diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift new file mode 100644 index 000000000000..05ca85c45838 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift @@ -0,0 +1,129 @@ +import Foundation +import Testing + +@testable import CMUXMobileCore + +struct MobileStateSyncFrameCodingTests { + private var workspace: WorkspaceSyncRecord { + WorkspaceSyncRecord( + id: "ws-1", + windowID: "win-1", + title: "build", + currentDirectory: "/repo", + isSelected: true, + isPinned: false, + groupID: "grp-1", + preview: "tests passed", + previewAt: 1_700_000_000, + lastActivityAt: 1_700_000_001, + hasUnread: true, + sortIndex: 3, + terminals: [ + WorkspaceSyncRecord.Terminal( + id: "t-1", + title: "zsh", + currentDirectory: "/repo", + isReady: true, + isFocused: false + ) + ] + ) + } + + @Test func workspaceRecordUsesLegacyWireKeys() throws { + let object = try MobileSyncFrameJSON.jsonObject(from: workspace) + #expect(object["id"] as? String == "ws-1") + #expect(object["window_id"] as? String == "win-1") + #expect(object["current_directory"] as? String == "/repo") + #expect(object["is_selected"] as? Bool == true) + #expect(object["is_pinned"] as? Bool == false) + #expect(object["group_id"] as? String == "grp-1") + #expect(object["preview_at"] as? Double == 1_700_000_000) + #expect(object["last_activity_at"] as? Double == 1_700_000_001) + #expect(object["has_unread"] as? Bool == true) + #expect(object["sort_index"] as? Int == 3) + let terminals = object["terminals"] as? [[String: Any]] + #expect(terminals?.first?["is_ready"] as? Bool == true) + #expect(terminals?.first?["is_focused"] as? Bool == false) + } + + @Test func deltaEventRoundTripsThroughJSONObject() throws { + let event = MobileSyncDeltaEvent( + epoch: "e1", + collection: .workspaces, + fromRev: 41, + toRev: 42, + records: [workspace], + removedIDs: ["ws-9"] + ) + let object = try MobileSyncFrameJSON.jsonObject(from: event) + #expect(object["from_rev"] as? UInt64 == 41) + #expect(object["to_rev"] as? UInt64 == 42) + #expect(object["removed_ids"] as? [String] == ["ws-9"]) + + let decoded = try MobileSyncFrameJSON.decode( + MobileSyncDeltaEvent.self, + fromJSONObject: object + ) + #expect(decoded == event) + } + + @Test func deltaHeaderDecodesCollectionFirst() throws { + let event = MobileSyncDeltaEvent( + epoch: "e1", + collection: .groups, + fromRev: 1, + toRev: 2, + records: [], + removedIDs: [] + ) + let object = try MobileSyncFrameJSON.jsonObject(from: event) + let header = try MobileSyncFrameJSON.decode(MobileSyncDeltaEventHeader.self, fromJSONObject: object) + #expect(header.collection == .groups) + } + + @Test func fetchRequestDecodesFromUntypedParams() throws { + let params: [String: Any] = [ + "collections": [ + ["id": "workspaces", "epoch": "e1", "rev": 12], + ["id": "groups"], + ["id": "future_collection", "epoch": "e1", "rev": 3], + ] + ] + let request = try MobileSyncFrameJSON.decode(MobileSyncFetchRequest.self, fromJSONObject: params) + #expect(request.collections.count == 3) + #expect(request.collections[0].cursor == MobileSyncCursor(epoch: "e1", rev: 12)) + #expect(request.collections[1].cursor == nil) + #expect(request.collections[2].id == MobileSyncCollectionID(rawValue: "future_collection")) + } + + @Test func fetchResponseOmitsAbsentSections() throws { + let response = MobileSyncFetchResponse( + epoch: "e1", + workspaces: MobileSyncCollectionPayload( + mode: .snapshot, + rev: 4, + fromRev: nil, + records: [workspace], + removedIDs: [] + ), + groups: nil + ) + let object = try MobileSyncFrameJSON.jsonObject(from: response) + #expect(object["groups"] == nil) + let section = object["workspaces"] as? [String: Any] + #expect(section?["mode"] as? String == "snapshot") + #expect(section?["from_rev"] == nil) + + let decoded = try MobileSyncFrameJSON.decode(MobileSyncFetchResponse.self, fromJSONObject: object) + #expect(decoded == response) + } + + @Test func unknownCollectionIDDecodesInsteadOfFailing() throws { + let decoded = try MobileSyncFrameJSON.decode( + MobileSyncDeltaEventHeader.self, + fromJSONString: #"{"collection":"records_from_the_future"}"# + ) + #expect(decoded.collection.rawValue == "records_from_the_future") + } +} diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncMirrorTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncMirrorTests.swift new file mode 100644 index 000000000000..d01ff87e4220 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncMirrorTests.swift @@ -0,0 +1,168 @@ +import Testing + +@testable import CMUXMobileCore + +@MainActor +struct MobileStateSyncMirrorTests { + private func group(id: String, name: String = "g", sortIndex: Int = 0) -> GroupSyncRecord { + GroupSyncRecord( + id: id, + name: name, + isCollapsed: false, + isPinned: false, + anchorWorkspaceID: id + "-anchor", + sortIndex: sortIndex + ) + } + + private func snapshot( + _ records: [GroupSyncRecord], + rev: UInt64 + ) -> MobileSyncCollectionPayload { + MobileSyncCollectionPayload( + mode: .snapshot, + rev: rev, + fromRev: nil, + records: records, + removedIDs: [] + ) + } + + private func delta( + epoch: String, + fromRev: UInt64, + toRev: UInt64, + records: [GroupSyncRecord] = [], + removedIDs: [String] = [] + ) -> MobileSyncDeltaEvent { + MobileSyncDeltaEvent( + epoch: epoch, + collection: .groups, + fromRev: fromRev, + toRev: toRev, + records: records, + removedIDs: removedIDs + ) + } + + @Test func snapshotReplacesStateAndAdoptsCursor() { + let mirror = MobileSyncCollectionMirror() + #expect(mirror.cursor == nil) + let result = mirror.apply(payload: snapshot([group(id: "a"), group(id: "b")], rev: 7), epoch: "e1") + #expect(result == .applied) + #expect(mirror.cursor == MobileSyncCursor(epoch: "e1", rev: 7)) + #expect(mirror.orderedRecords.map(\.syncID) == ["a", "b"]) + } + + @Test func contiguousDeltaAdvances() { + let mirror = MobileSyncCollectionMirror() + _ = mirror.apply(payload: snapshot([group(id: "a")], rev: 1), epoch: "e1") + let result = mirror.apply(delta: delta(epoch: "e1", fromRev: 1, toRev: 2, records: [group(id: "b")])) + #expect(result == .applied) + #expect(mirror.rev == 2) + #expect(mirror.orderedRecords.map(\.syncID) == ["a", "b"]) + } + + @Test func overlappingDeltaAppliesIdempotently() { + let mirror = MobileSyncCollectionMirror() + _ = mirror.apply(payload: snapshot([group(id: "a")], rev: 5), epoch: "e1") + // A frame covering (3, 6] arrives after a snapshot at 5: overlap, safe. + let result = mirror.apply( + delta: delta(epoch: "e1", fromRev: 3, toRev: 6, records: [group(id: "a", name: "renamed")]) + ) + #expect(result == .applied) + #expect(mirror.rev == 6) + #expect(mirror.orderedRecords.first?.name == "renamed") + } + + @Test func staleDeltaIsIgnoredWithoutStateChange() { + let mirror = MobileSyncCollectionMirror() + _ = mirror.apply(payload: snapshot([group(id: "a")], rev: 5), epoch: "e1") + let result = mirror.apply( + delta: delta(epoch: "e1", fromRev: 2, toRev: 4, removedIDs: ["a"]) + ) + #expect(result == .staleIgnored) + #expect(mirror.rev == 5) + #expect(mirror.orderedRecords.count == 1) + } + + @Test func gappedDeltaReportsGapAndLeavesStateUntouched() { + let mirror = MobileSyncCollectionMirror() + _ = mirror.apply(payload: snapshot([group(id: "a")], rev: 5), epoch: "e1") + let result = mirror.apply(delta: delta(epoch: "e1", fromRev: 7, toRev: 9, removedIDs: ["a"])) + #expect(result == .gap) + #expect(mirror.rev == 5) + #expect(mirror.orderedRecords.count == 1) + } + + @Test func epochMismatchReportsGap() { + let mirror = MobileSyncCollectionMirror() + _ = mirror.apply(payload: snapshot([group(id: "a")], rev: 5), epoch: "e1") + #expect(mirror.apply(delta: delta(epoch: "e2", fromRev: 5, toRev: 6)) == .gap) + } + + @Test func deltaBeforeAnyStateReportsGap() { + let mirror = MobileSyncCollectionMirror() + #expect(mirror.apply(delta: delta(epoch: "e1", fromRev: 0, toRev: 1)) == .gap) + } + + @Test func removalDropsRecord() { + let mirror = MobileSyncCollectionMirror() + _ = mirror.apply(payload: snapshot([group(id: "a"), group(id: "b")], rev: 1), epoch: "e1") + _ = mirror.apply(delta: delta(epoch: "e1", fromRev: 1, toRev: 2, removedIDs: ["a"])) + #expect(mirror.orderedRecords.map(\.syncID) == ["b"]) + } + + @Test func orderingFollowsSortIndexThenID() { + let mirror = MobileSyncCollectionMirror() + _ = mirror.apply( + payload: snapshot( + [group(id: "z", sortIndex: 0), group(id: "a", sortIndex: 1), group(id: "m", sortIndex: 0)], + rev: 1 + ), + epoch: "e1" + ) + #expect(mirror.orderedRecords.map(\.syncID) == ["m", "z", "a"]) + } + + @Test func resetForgetsEverything() { + let mirror = MobileSyncCollectionMirror() + _ = mirror.apply(payload: snapshot([group(id: "a")], rev: 5), epoch: "e1") + mirror.reset() + #expect(mirror.cursor == nil) + #expect(mirror.orderedRecords.isEmpty) + // After reset, a delta cannot apply until a snapshot re-establishes state. + #expect(mirror.apply(delta: delta(epoch: "e1", fromRev: 5, toRev: 6)) == .gap) + } + + @Test func rootMirrorRoundTripsWithRootStore() { + let store = MobileStateSyncStore() + _ = store.groups.apply(rows: [group(id: "g1")]) + let mirror = MobileStateSyncMirror() + + // Cold fetch: snapshot. + let cold = store.fetchResponse(for: mirror.fetchRequest) + #expect(cold.groups?.mode == .snapshot) + #expect(mirror.apply(response: cold) == .applied) + #expect(mirror.groups.orderedRecords.map(\.syncID) == ["g1"]) + + // Change on the Mac, delta event to the phone. + let change = store.groups.apply(rows: [group(id: "g1", name: "renamed"), group(id: "g2", sortIndex: 1)]) + let event = MobileSyncDeltaEvent( + epoch: store.epoch, + collection: .groups, + fromRev: change?.fromRev ?? 0, + toRev: change?.toRev ?? 0, + records: change?.records ?? [], + removedIDs: change?.removedIDs ?? [] + ) + #expect(mirror.groups.apply(delta: event) == .applied) + #expect(mirror.groups.orderedRecords.map(\.name) == ["renamed", "g"]) + + // Warm fetch after the event: empty delta, nothing to re-send. + let warm = store.fetchResponse(for: mirror.fetchRequest) + #expect(warm.groups?.mode == .delta) + #expect(warm.groups?.records.isEmpty == true) + #expect(mirror.apply(response: warm) == .staleIgnored) + } +} diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift new file mode 100644 index 000000000000..e7124dbc3891 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift @@ -0,0 +1,188 @@ +import Testing + +@testable import CMUXMobileCore + +@MainActor +struct MobileStateSyncStoreTests { + private func workspace( + id: String, + title: String = "ws", + preview: String? = nil, + hasUnread: Bool = false, + sortIndex: Int = 0 + ) -> WorkspaceSyncRecord { + WorkspaceSyncRecord( + id: id, + windowID: "w1", + title: title, + currentDirectory: "/tmp", + isSelected: false, + isPinned: false, + groupID: nil, + preview: preview, + previewAt: preview == nil ? nil : 1.0, + lastActivityAt: 1.0, + hasUnread: hasUnread, + sortIndex: sortIndex, + terminals: [ + WorkspaceSyncRecord.Terminal( + id: id + "-t1", + title: "zsh", + currentDirectory: "/tmp", + isReady: true, + isFocused: true + ) + ] + ) + } + + @Test func firstApplyStampsEveryRowAtRevOne() { + let store = MobileSyncCollectionStore() + let change = store.apply(rows: [workspace(id: "a"), workspace(id: "b")]) + #expect(change?.fromRev == 0) + #expect(change?.toRev == 1) + #expect(change?.records.count == 2) + #expect(change?.removedIDs.isEmpty == true) + #expect(store.headRev == 1) + } + + @Test func identicalApplyIsANoOpAndMovesNoRevision() { + let store = MobileSyncCollectionStore() + let rows = [workspace(id: "a"), workspace(id: "b")] + _ = store.apply(rows: rows) + #expect(store.apply(rows: rows) == nil) + #expect(store.headRev == 1) + } + + @Test func changedRowTravelsAloneInTheDelta() { + let store = MobileSyncCollectionStore() + _ = store.apply(rows: [workspace(id: "a"), workspace(id: "b")]) + let change = store.apply(rows: [ + workspace(id: "a", preview: "new output", hasUnread: true), + workspace(id: "b"), + ]) + #expect(change?.records.map(\.syncID) == ["a"]) + #expect(change?.fromRev == 1) + #expect(change?.toRev == 2) + } + + @Test func removalBecomesTombstoneAndDeltaCarriesIt() { + let store = MobileSyncCollectionStore() + _ = store.apply(rows: [workspace(id: "a"), workspace(id: "b")]) + let change = store.apply(rows: [workspace(id: "a")]) + #expect(change?.records.isEmpty == true) + #expect(change?.removedIDs == ["b"]) + + let payload = store.payload(since: 1) + #expect(payload.mode == .delta) + #expect(payload.removedIDs == ["b"]) + #expect(payload.records.isEmpty) + #expect(payload.rev == 2) + } + + @Test func duplicateIDsInOneApplyKeepTheFirstRow() { + let store = MobileSyncCollectionStore() + let change = store.apply(rows: [ + workspace(id: "a", title: "first"), + workspace(id: "a", title: "second"), + ]) + #expect(change?.records.map(\.title) == ["first"]) + } + + @Test func currentCursorGetsEmptyDelta() { + let store = MobileSyncCollectionStore() + _ = store.apply(rows: [workspace(id: "a")]) + let payload = store.payload(since: store.headRev) + #expect(payload.mode == .delta) + #expect(payload.records.isEmpty) + #expect(payload.removedIDs.isEmpty) + #expect(payload.fromRev == store.headRev) + #expect(payload.rev == store.headRev) + } + + @Test func coldCursorGetsSnapshot() { + let store = MobileSyncCollectionStore() + _ = store.apply(rows: [workspace(id: "a"), workspace(id: "b")]) + let payload = store.payload(since: nil) + #expect(payload.mode == .snapshot) + #expect(payload.records.count == 2) + #expect(payload.fromRev == nil) + } + + @Test func futureCursorGetsSnapshot() { + let store = MobileSyncCollectionStore() + _ = store.apply(rows: [workspace(id: "a")]) + #expect(store.payload(since: 99).mode == .snapshot) + } + + @Test func deltaSpansMultipleTicks() { + let store = MobileSyncCollectionStore() + _ = store.apply(rows: [workspace(id: "a")]) + _ = store.apply(rows: [workspace(id: "a"), workspace(id: "b")]) + _ = store.apply(rows: [workspace(id: "b")]) + let payload = store.payload(since: 1) + #expect(payload.mode == .delta) + #expect(payload.records.map(\.syncID) == ["b"]) + #expect(payload.removedIDs == ["a"]) + #expect(payload.rev == 3) + } + + @Test func cursorOlderThanRetainedTombstonesGetsSnapshot() { + let store = MobileSyncCollectionStore(maximumTombstoneCount: 2) + _ = store.apply(rows: [ + workspace(id: "a"), workspace(id: "b"), + workspace(id: "c"), workspace(id: "d"), + ]) + _ = store.apply(rows: [workspace(id: "b"), workspace(id: "c"), workspace(id: "d")]) + _ = store.apply(rows: [workspace(id: "c"), workspace(id: "d")]) + _ = store.apply(rows: [workspace(id: "d")]) + // Three removals happened (revs 2, 3, 4); the ring keeps two. A cursor + // from rev 1 cannot prove it saw removal rev 2, so it must snapshot. + #expect(store.payload(since: 1).mode == .snapshot) + // A cursor at rev 2 needs removals 3 and 4, both retained: delta. + let covered = store.payload(since: 2) + #expect(covered.mode == .delta) + #expect(Set(covered.removedIDs) == Set(["b", "c"])) + } + + @Test func rootStoreMismatchedEpochResolvesToSnapshot() { + let store = MobileStateSyncStore(epoch: "epoch-1") + _ = store.workspaces.apply(rows: [workspace(id: "a")]) + let response = store.fetchResponse( + for: MobileSyncFetchRequest(collections: [ + MobileSyncFetchRequest.Collection(id: .workspaces, epoch: "epoch-0", rev: 1) + ]) + ) + #expect(response.epoch == "epoch-1") + #expect(response.workspaces?.mode == .snapshot) + #expect(response.groups == nil) + } + + @Test func rootStoreMatchingEpochResolvesToDelta() { + let store = MobileStateSyncStore(epoch: "epoch-1") + _ = store.workspaces.apply(rows: [workspace(id: "a")]) + _ = store.workspaces.apply(rows: [workspace(id: "a", hasUnread: true)]) + let response = store.fetchResponse( + for: MobileSyncFetchRequest(collections: [ + MobileSyncFetchRequest.Collection(id: .workspaces, epoch: "epoch-1", rev: 1) + ]) + ) + #expect(response.workspaces?.mode == .delta) + #expect(response.workspaces?.records.map(\.syncID) == ["a"]) + } + + @Test func rootStoreIgnoresUnknownCollections() { + let store = MobileStateSyncStore() + let response = store.fetchResponse( + for: MobileSyncFetchRequest(collections: [ + MobileSyncFetchRequest.Collection( + id: MobileSyncCollectionID(rawValue: "future_collection"), + epoch: nil, + rev: nil + ) + ]) + ) + #expect(response.workspaces == nil) + #expect(response.groups == nil) + } +} diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift index 73a2da2ca417..da0634baf428 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift @@ -56,6 +56,37 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { case hasUnread = "has_unread" case terminals } + + /// Memberwise construction for callers that assemble a row from an + /// already-synced local source (mobile state sync v2 projects its + /// record mirror through the same apply path as the wire response). + public init( + id: String, + windowID: String?, + title: String, + currentDirectory: String?, + isSelected: Bool, + isPinned: Bool?, + groupID: String?, + preview: String?, + previewAt: Double?, + lastActivityAt: Double?, + hasUnread: Bool?, + terminals: [Terminal] + ) { + self.id = id + self.windowID = windowID + self.title = title + self.currentDirectory = currentDirectory + self.isSelected = isSelected + self.isPinned = isPinned + self.groupID = groupID + self.preview = preview + self.previewAt = previewAt + self.lastActivityAt = lastActivityAt + self.hasUnread = hasUnread + self.terminals = terminals + } } /// A workspace group section in the list response. Mirrors the iOS-facing @@ -86,6 +117,21 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { case isPinned = "is_pinned" case anchorWorkspaceID = "anchor_workspace_id" } + + /// Memberwise construction for locally-synced sources (state sync v2). + public init( + id: String, + name: String, + isCollapsed: Bool, + isPinned: Bool, + anchorWorkspaceID: String + ) { + self.id = id + self.name = name + self.isCollapsed = isCollapsed + self.isPinned = isPinned + self.anchorWorkspaceID = anchorWorkspaceID + } } /// A terminal entry within a workspace. @@ -108,6 +154,21 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { case isFocused = "is_focused" case isReady = "is_ready" } + + /// Memberwise construction for locally-synced sources (state sync v2). + public init( + id: String, + title: String, + currentDirectory: String?, + isFocused: Bool, + isReady: Bool? + ) { + self.id = id + self.title = title + self.currentDirectory = currentDirectory + self.isFocused = isFocused + self.isReady = isReady + } } /// The full workspace list. @@ -148,3 +209,23 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { try JSONDecoder().decode(Self.self, from: data) } } + +// Memberwise construction for callers that assemble a list response from an +// already-synced local source (mobile state sync v2 projects its record mirror +// through the same apply path the decoded wire response uses). +extension MobileSyncWorkspaceListResponse { + public init( + workspaces: [Workspace], + groups: [Group], + createdWorkspaceID: String?, + createdTerminalID: String? + ) { + self.workspaces = workspaces + self.groups = groups + self.createdWorkspaceID = createdWorkspaceID + self.createdTerminalID = createdTerminalID + } +} + + + diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift new file mode 100644 index 000000000000..92d8ed64cb42 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -0,0 +1,174 @@ +import CMUXMobileCore +import CmuxMobileRPC +import Foundation +internal import OSLog + +private let mobileStateSyncLog = Logger( + subsystem: Bundle.main.bundleIdentifier ?? "dev.cmux.ios", + category: "mobile-state-sync" +) + +// MARK: - Mobile state sync v2 (docs/mobile-state-sync-v2.md) +// +// Consumes `mobile.sync.delta` events and the `mobile.sync.fetch` cursor RPC, +// mirrors the Mac's workspace/group records locally, and projects the mirror +// into the exact `MobileSyncWorkspaceListResponse` shape the legacy full-list +// path applies, so everything downstream of `applyRemoteWorkspaceList` (per-Mac +// state, group collapse, selection sync) is shared, not duplicated. A Mac that +// does not implement `mobile.sync.fetch` answers `method_not_found` and this +// connection silently stays on the legacy refetch loop. +extension MobileShellComposite { + /// Starts (or restarts) v2 negotiation for a freshly subscribed event + /// stream. Runs concurrently with event consumption; a delta racing the + /// fetch overlaps idempotently or gaps into a repair fetch. + func beginStateSyncNegotiation(client: MobileCoreRPCClient) { + stateSyncActive = false + scheduleStateSyncFetch(client: client) + } + + /// Handles one `mobile.sync.delta` event from the foreground event stream. + /// The caller already proved the event belongs to the current client and a + /// connected session. + func handleStateSyncDeltaEvent(_ event: MobileEventEnvelope) { + guard let payload = event.payloadJSON else { return } + guard let header = try? JSONDecoder().decode(MobileSyncDeltaEventHeader.self, from: payload) else { + return + } + let result: MobileSyncApplyResult + switch header.collection { + case .workspaces: + guard let delta = try? JSONDecoder().decode( + MobileSyncDeltaEvent.self, from: payload + ) else { return } + result = stateSyncMirror.workspaces.apply(delta: delta) + case .groups: + guard let delta = try? JSONDecoder().decode( + MobileSyncDeltaEvent.self, from: payload + ) else { return } + result = stateSyncMirror.groups.apply(delta: delta) + default: + // A newer Mac may sync collections this build does not know; they + // are simply not mirrored here. + return + } + switch result { + case .applied: + applyStateSyncProjection() + case .staleIgnored: + break + case .gap: + // Missed revisions (lost registration, dropped event). The cursor + // fetch returns exactly the missing span, or a snapshot when the + // span is no longer retained. + if let client = remoteClient { + scheduleStateSyncFetch(client: client) + } + } + } + + /// Single-flight, restart-on-newest cursor fetch (negotiation and gap + /// repair share it, mirroring ``workspaceListRefreshTask`` semantics). + private func scheduleStateSyncFetch(client: MobileCoreRPCClient) { + stateSyncFetchTask?.cancel() + stateSyncFetchTask = Task { @MainActor [weak self] in + defer { self?.stateSyncFetchTask = nil } + await self?.runStateSyncFetch(client: client) + } + } + + private func runStateSyncFetch(client: MobileCoreRPCClient) async { + let params: [String: Any] + do { + params = try MobileSyncFrameJSON.jsonObject(from: stateSyncMirror.fetchRequest) + } catch { + return + } + do { + let request = try MobileCoreRPCClient.requestData( + method: "mobile.sync.fetch", + params: params + ) + let data = try await client.sendRequest( + request, + timeoutNanoseconds: runtime?.rpcRequestTimeoutNanoseconds + ) + guard remoteClient === client, connectionState == .connected, !Task.isCancelled else { return } + let response = try JSONDecoder().decode(MobileSyncFetchResponse.self, from: data) + let result = stateSyncMirror.apply(response: response) + stateSyncActive = true + switch result { + case .applied: + applyStateSyncProjection() + case .staleIgnored: + break + case .gap: + // A fetch section can only gap if the store moved between + // building the response's sections; one repair round covers it. + scheduleStateSyncFetch(client: client) + } + } catch let error as MobileShellConnectionError { + if case .rpcError(let code, _) = error, code == "method_not_found" { + // Legacy Mac: stay on the workspace.updated refetch loop for + // this connection. Not an error. + stateSyncActive = false + return + } + mobileStateSyncLog.error( + "state sync fetch failed: \(String(describing: error), privacy: .private)" + ) + } catch { + mobileStateSyncLog.error( + "state sync fetch failed: \(String(describing: error), privacy: .private)" + ) + } + } + + /// Projects the mirror into the legacy full-list response shape and hands + /// it to the shared apply path. The mirror always holds full records, so + /// the projection is always a complete, ordered list. + private func applyStateSyncProjection() { + let workspaces = stateSyncMirror.workspaces.orderedRecords.map { record in + MobileSyncWorkspaceListResponse.Workspace( + id: record.id, + windowID: record.windowID, + title: record.title, + currentDirectory: record.currentDirectory, + isSelected: record.isSelected, + isPinned: record.isPinned, + groupID: record.groupID, + preview: record.preview, + previewAt: record.previewAt, + lastActivityAt: record.lastActivityAt, + hasUnread: record.hasUnread, + terminals: record.terminals.map { terminal in + MobileSyncWorkspaceListResponse.Terminal( + id: terminal.id, + title: terminal.title, + currentDirectory: terminal.currentDirectory, + isFocused: terminal.isFocused, + isReady: terminal.isReady + ) + } + ) + } + let groups = stateSyncMirror.groups.orderedRecords.map { record in + MobileSyncWorkspaceListResponse.Group( + id: record.id, + name: record.name, + isCollapsed: record.isCollapsed, + isPinned: record.isPinned, + anchorWorkspaceID: record.anchorWorkspaceID + ) + } + applyRemoteWorkspaceList( + MobileSyncWorkspaceListResponse( + workspaces: workspaces, + groups: groups, + createdWorkspaceID: nil, + createdTerminalID: nil + ), + preferActiveTicketTarget: false + ) + syncSelectedTerminalForWorkspace() + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 77d175a90352..28f6576ddf17 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -45,11 +45,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { var eventTopics: [String] { switch self { case .hybrid: - return ["workspace.updated", "terminal.bytes", "terminal.render_grid", "terminal.set_font", "notification.dismissed", "notification.badge"] + return ["workspace.updated", "mobile.sync.delta", "terminal.bytes", "terminal.render_grid", "terminal.set_font", "notification.dismissed", "notification.badge"] case .renderGrid: - return ["workspace.updated", "terminal.render_grid", "terminal.set_font", "notification.dismissed", "notification.badge"] + return ["workspace.updated", "mobile.sync.delta", "terminal.render_grid", "terminal.set_font", "notification.dismissed", "notification.badge"] case .rawBytes: - return ["workspace.updated", "terminal.bytes", "terminal.set_font", "notification.dismissed", "notification.badge"] + return ["workspace.updated", "mobile.sync.delta", "terminal.bytes", "terminal.set_font", "notification.dismissed", "notification.badge"] } } @@ -711,6 +711,18 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { var createWorkspaceTaskGroupID: MobileWorkspaceGroupPreview.ID? private var createTerminalTask: Task? private var workspaceListRefreshTask: Task? + /// Mobile state sync v2 (docs/mobile-state-sync-v2.md): full-record mirror + /// of the foreground Mac's workspace/group collections plus its cursor. + /// Never reset on reconnect; the epoch in every frame invalidates stale + /// cursors, so a same-Mac resubscribe catches up with one small delta. + let stateSyncMirror = MobileStateSyncMirror() + /// Whether the connected Mac answered `mobile.sync.fetch` this connection. + /// While true, `workspace.updated` no longer schedules full-list refetches; + /// `mobile.sync.delta` events own the list. + var stateSyncActive = false + /// Single-flight handle for negotiation and gap-repair fetches, restart-on- + /// newest like ``workspaceListRefreshTask``. + var stateSyncFetchTask: Task? /// The user pull-to-refresh round-trip, kept on its own handle so the /// event-driven ``workspaceListRefreshTask`` cancel/restart can never truncate /// the spinner the pull is awaiting. Rapid pulls coalesce onto this single task. @@ -6186,6 +6198,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { topics: topics, transport: outputTransport ) + // Probe mobile state sync v2 concurrently with consumption, for the + // same reason as the subscribe handshake above: the fetch must not + // park the consumer loop. Subscribing before fetching means a delta + // racing the fetch either overlaps (idempotent) or gaps (repair + // fetch); no change can be silently lost in between. + self?.beginStateSyncNegotiation(client: client) // Keep the listener alive without keeping the shell store alive. for await event in stream { guard !Task.isCancelled else { return } @@ -6197,6 +6215,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { self.markMacConnectionHealthy() if event.topic == "workspace.updated" { self.scheduleWorkspaceListRefreshFromEvent() + } else if event.topic == "mobile.sync.delta" { + self.handleStateSyncDeltaEvent(event) } else if event.topic == "terminal.render_grid" { self.handleTerminalRenderGridEvent(event) } else if event.topic == "terminal.set_font" { @@ -7274,6 +7294,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func scheduleWorkspaceListRefreshFromEvent() { guard remoteClient != nil else { return } + // With state sync v2 negotiated, `workspace.updated` is redundant with + // the `mobile.sync.delta` stream (the Mac emits both on the same tick + // for old and new phones); the delta already carried the change, so the + // full-list refetch this event used to trigger is pure amplification. + guard !stateSyncActive else { return } // Keep the event path's "latest event wins" semantics: a `workspace.updated` // arriving mid-fetch restarts the fetch so the applied list reflects the // change the Mac pushed *after* this fetch started. This cancels only the diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift index 18760ef2b79a..159e418e6edb 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift @@ -55,11 +55,23 @@ actor LivenessHostRouter { private var macInstanceTag: String? = "default" private var macDisplayName: String? = "Test Mac" private var workspaceListResponseHook: (@Sendable () -> Void)? + /// FIFO of scripted `mobile.sync.fetch` results (state sync v2 tests). + private var syncFetchResults: [[String: Any]] = [] private var replayPayloads: [(text: String?, sequence: UInt64?, renderGrid: MobileTerminalRenderGridFrame?)] = [] private var replayTexts: [String] = [] private var replayFailuresRemaining = 0 private var emptyReplayResponsesRemaining = 0; private var viewportEffectiveGridOverride: LivenessViewportReport?; private var emptyViewportResponsesRemaining = 0 + /// Scripts the next `mobile.sync.fetch` answer (state sync v2 tests). The + /// payload crosses the actor boundary as encoded JSON so the test-side + /// builder can use `JSONSerialization` freely without Sendable friction. + func scriptSyncFetchResult(jsonData: Data) { + guard let object = (try? JSONSerialization.jsonObject(with: jsonData)) as? [String: Any] else { + return + } + syncFetchResults.append(object) + } + func record(method: String?, topics: [String]?, workspaceID: String? = nil) { recorded.append(RecordedRequest( method: method, @@ -371,6 +383,14 @@ actor LivenessHostRouter { ]) case "mobile.events.unsubscribe": return try? Self.resultFrame(id: id, result: [:]) + case "mobile.sync.fetch": + // Unscripted routers model a legacy Mac: the real host answers an + // unknown method with `method_not_found`, which the shell treats + // as "stay on the workspace.updated refetch loop". + guard !syncFetchResults.isEmpty else { + return try? Self.errorFrame(id: id, code: "method_not_found", message: "Unknown mobile method") + } + return try? Self.resultFrame(id: id, result: syncFetchResults.removeFirst()) case "mobile.terminal.viewport": viewportRequestCount += 1 if heldViewportRequestNumbers.contains(viewportRequestCount) { @@ -407,11 +427,13 @@ actor LivenessHostRouter { return try MobileSyncFrameCodec.encodeFrame(JSONSerialization.data(withJSONObject: envelope)) } - private static func errorFrame(id: String?, message: String) throws -> Data { + private static func errorFrame(id: String?, code: String? = nil, message: String) throws -> Data { + var error: [String: Any] = ["message": message] + if let code { error["code"] = code } let envelope: [String: Any] = [ "id": id ?? UUID().uuidString, "ok": false, - "error": ["message": message], + "error": error, ] return try MobileSyncFrameCodec.encodeFrame(JSONSerialization.data(withJSONObject: envelope)) } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift new file mode 100644 index 000000000000..877799afaa31 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift @@ -0,0 +1,204 @@ +import CMUXMobileCore +import CmuxMobileRPC +import Foundation +import Testing + +@testable import CmuxMobileShell + +// Behavior tests for mobile state sync v2 (docs/mobile-state-sync-v2.md): +// negotiation via `mobile.sync.fetch`, delta application from +// `mobile.sync.delta` events, legacy fallback on `method_not_found`, and the +// suppression of full-list refetches while v2 is active. Uses the scripted +// liveness host router/transport so events flow through the production +// subscribe/consume path. + +private func workspaceRecord( + id: String, + title: String, + sortIndex: Int +) -> WorkspaceSyncRecord { + WorkspaceSyncRecord( + id: id, + windowID: "win-1", + title: title, + currentDirectory: nil, + isSelected: false, + isPinned: false, + groupID: nil, + preview: nil, + previewAt: nil, + lastActivityAt: 1.0, + hasUnread: false, + sortIndex: sortIndex, + terminals: [] + ) +} + +private func syncSnapshotResultData( + epoch: String, + rev: UInt64, + records: [WorkspaceSyncRecord] +) throws -> Data { + let response = MobileSyncFetchResponse( + epoch: epoch, + workspaces: MobileSyncCollectionPayload( + mode: .snapshot, + rev: rev, + fromRev: nil, + records: records, + removedIDs: [] + ), + groups: MobileSyncCollectionPayload( + mode: .snapshot, + rev: rev, + fromRev: nil, + records: [], + removedIDs: [] + ) + ) + return try JSONEncoder().encode(response) +} + +private func syncDeltaEventFrame( + epoch: String, + fromRev: UInt64, + toRev: UInt64, + records: [WorkspaceSyncRecord], + removedIDs: [String] = [] +) throws -> Data { + let event = MobileSyncDeltaEvent( + epoch: epoch, + collection: .workspaces, + fromRev: fromRev, + toRev: toRev, + records: records, + removedIDs: removedIDs + ) + let envelope: [String: Any] = [ + "kind": "event", + "topic": "mobile.sync.delta", + "payload": try MobileSyncFrameJSON.jsonObject(from: event), + ] + return try MobileSyncFrameCodec.encodeFrame(JSONSerialization.data(withJSONObject: envelope)) +} + +private func workspaceUpdatedEventFrame() throws -> Data { + let envelope: [String: Any] = [ + "kind": "event", + "topic": "workspace.updated", + "payload": [String: Any](), + ] + return try MobileSyncFrameCodec.encodeFrame(JSONSerialization.data(withJSONObject: envelope)) +} + +@MainActor +struct MobileShellStateSyncTests { + @Test func negotiationAppliesSnapshotAndSuppressesLegacyRefetch() async throws { + let router = LivenessHostRouter() + await router.scriptSyncFetchResult( + jsonData: try syncSnapshotResultData( + epoch: "epoch-1", + rev: 3, + records: [ + workspaceRecord(id: UUID().uuidString, title: "synced-alpha", sortIndex: 0), + workspaceRecord(id: UUID().uuidString, title: "synced-beta", sortIndex: 1), + ] + ) + ) + let box = TransportBox() + let clock = TestClock() + let store = try await makeConnectedStore(router: router, box: box, clock: clock) + + let negotiated = try await pollUntil { store.stateSyncActive } + #expect(negotiated, "v2 negotiation must complete against a scripted sync host") + let projected = try await pollUntil { + store.workspaces.map(\.name).contains("synced-alpha") + } + #expect(projected, "snapshot projection must reach the published workspace list") + + // A workspace.updated push must no longer trigger the legacy full-list + // refetch while v2 owns the list. + let listCallsBefore = await router.count(of: "mobile.workspace.list") + let transport = try #require(box.get()) + await transport.deliver(try workspaceUpdatedEventFrame()) + // Deliver a delta behind it; its application proves the updated event + // was consumed first (same stream, in order). + await transport.deliver(try syncDeltaEventFrame( + epoch: "epoch-1", + fromRev: 3, + toRev: 4, + records: [workspaceRecord(id: UUID().uuidString, title: "synced-gamma", sortIndex: 2)] + )) + let deltaApplied = try await pollUntil { + store.workspaces.map(\.name).contains("synced-gamma") + } + #expect(deltaApplied, "contiguous delta must extend the mirrored list") + let listCallsAfter = await router.count(of: "mobile.workspace.list") + #expect( + listCallsAfter == listCallsBefore, + "workspace.updated must not schedule a full-list refetch while state sync is active" + ) + } + + @Test func gappedDeltaTriggersCursorRepairFetch() async throws { + let router = LivenessHostRouter() + await router.scriptSyncFetchResult( + jsonData: try syncSnapshotResultData( + epoch: "epoch-1", + rev: 3, + records: [workspaceRecord(id: UUID().uuidString, title: "synced-alpha", sortIndex: 0)] + ) + ) + // The repair fetch answers with the missing span's outcome (snapshot + // for simplicity; the mirror accepts either). + await router.scriptSyncFetchResult( + jsonData: try syncSnapshotResultData( + epoch: "epoch-1", + rev: 9, + records: [workspaceRecord(id: UUID().uuidString, title: "repaired", sortIndex: 0)] + ) + ) + let box = TransportBox() + let clock = TestClock() + let store = try await makeConnectedStore(router: router, box: box, clock: clock) + _ = try await pollUntil { store.stateSyncActive } + + let transport = try #require(box.get()) + // fromRev 7 > mirror rev 3: a gap the shell must repair with a fetch. + await transport.deliver(try syncDeltaEventFrame( + epoch: "epoch-1", + fromRev: 7, + toRev: 8, + records: [workspaceRecord(id: UUID().uuidString, title: "lost", sortIndex: 1)] + )) + let repaired = try await pollUntil { + store.workspaces.map(\.name).contains("repaired") + } + #expect(repaired, "a gapped delta must trigger a cursor fetch that re-bases the mirror") + let fetches = await router.count(of: "mobile.sync.fetch") + #expect(fetches >= 2, "gap repair must issue a second mobile.sync.fetch") + } + + @Test func legacyMacKeepsWorkspaceUpdatedRefetchLoop() async throws { + // No scripted sync result: the router answers `method_not_found`, + // modeling a released Mac. + let router = LivenessHostRouter() + let box = TransportBox() + let clock = TestClock() + let store = try await makeConnectedStore(router: router, box: box, clock: clock) + + let probed = try await pollUntil { + await router.count(of: "mobile.sync.fetch") >= 1 + } + #expect(probed, "the shell must probe mobile.sync.fetch once per connection") + #expect(store.stateSyncActive == false) + + let listCallsBefore = await router.count(of: "mobile.workspace.list") + let transport = try #require(box.get()) + await transport.deliver(try workspaceUpdatedEventFrame()) + let refetched = try await pollUntil { + await router.count(of: "mobile.workspace.list") > listCallsBefore + } + #expect(refetched, "a legacy Mac must keep the workspace.updated refetch loop") + } +} diff --git a/Sources/Mobile/MobileHostService+TicketAuthorization.swift b/Sources/Mobile/MobileHostService+TicketAuthorization.swift index 3057f37b1b68..4d610a4456a8 100644 --- a/Sources/Mobile/MobileHostService+TicketAuthorization.swift +++ b/Sources/Mobile/MobileHostService+TicketAuthorization.swift @@ -40,6 +40,10 @@ extension MobileHostService { switch request.method { case "mobile.workspace.list", "workspace.list": return nil + case "mobile.sync.fetch": + // Cursor-based read of the same Mac-scoped list state as + // `mobile.workspace.list`; carries no workspace/terminal selection. + return nil case "workspace.create": guard request.params["group_id"] == nil || request.params["group_id"] is NSNull else { return ticketMacScopedWorkspaceMutationAuthorizationError(authorization: authorization) diff --git a/Sources/Mobile/MobileStateSync.swift b/Sources/Mobile/MobileStateSync.swift new file mode 100644 index 000000000000..72d7dc4b5eaf --- /dev/null +++ b/Sources/Mobile/MobileStateSync.swift @@ -0,0 +1,220 @@ +import CMUXMobileCore +import Foundation + +/// Mac-side owner of mobile state sync v2 (`docs/mobile-state-sync-v2.md`). +/// +/// Holds the versioned record store, rebuilds the typed iOS-facing rows from +/// the same sources the legacy `mobile.workspace.list` payload reads, and +/// broadcasts `mobile.sync.delta` events carrying only the rows a change tick +/// actually touched. The legacy empty-payload `workspace.updated` event keeps +/// firing unchanged for released phones; v2 phones subscribe to the delta +/// topic and stop re-fetching full lists. +@MainActor +final class MobileStateSyncHost { + static let shared = MobileStateSyncHost() + + /// Event topic v2 phones subscribe to through `mobile.events.subscribe`. + static let deltaTopic = "mobile.sync.delta" + + let store = MobileStateSyncStore() + + /// Sanitized-preview cache keyed by workspace. The sanitizer walks up to + /// ~2K scalars of notification text per row; caching on the notification + /// identity means a rebuild only re-sanitizes rows whose latest + /// notification actually changed. + private struct PreviewCacheEntry { + let notificationID: UUID + let createdAt: Date + let text: String? + } + + private var previewCache: [UUID: PreviewCacheEntry] = [:] + + /// Observer tick entry point: cheap no-op unless some phone subscribed to + /// the delta topic (the store then also stays cold until the first + /// `mobile.sync.fetch` populates it). + func broadcastIfSubscribed() { + guard MobileHostService.hasEventSubscribers(topic: Self.deltaTopic) else { return } + refreshAndBroadcast() + } + + /// `mobile.sync.fetch` handler. Refreshes the store first so the answer is + /// current even when no observer tick has fired yet, and so the refresh's + /// delta event (if any) reaches already-subscribed phones and keeps their + /// cursors contiguous with this response's revisions. + func fetch(params: [String: Any]) -> TerminalController.V2CallResult { + let request: MobileSyncFetchRequest + do { + request = try MobileSyncFrameJSON.decode(MobileSyncFetchRequest.self, fromJSONObject: params) + } catch { + return .err(code: "invalid_params", message: "Missing or invalid collections", data: nil) + } + guard !request.collections.isEmpty else { + return .err(code: "invalid_params", message: "Missing or invalid collections", data: nil) + } + refreshAndBroadcast() + let response = store.fetchResponse(for: request) + guard let payload = try? MobileSyncFrameJSON.jsonObject(from: response) else { + return .err(code: "internal_error", message: "Failed to encode sync response", data: nil) + } + return .ok(payload) + } + + /// Rebuilds the typed rows, diffs them into the store, and broadcasts one + /// delta event per changed collection. No-op frames emit nothing. + private func refreshAndBroadcast() { + let rows = buildRows() + if let change = store.workspaces.apply(rows: rows.workspaces) { + emit(collection: .workspaces, change: change) + } + if let change = store.groups.apply(rows: rows.groups) { + emit(collection: .groups, change: change) + } + } + + private func emit( + collection: MobileSyncCollectionID, + change: MobileSyncCollectionChange + ) { + let event = MobileSyncDeltaEvent( + epoch: store.epoch, + collection: collection, + fromRev: change.fromRev, + toRev: change.toRev, + records: change.records, + removedIDs: change.removedIDs + ) + guard let payload = try? MobileSyncFrameJSON.jsonObject(from: event) else { return } + MobileHostService.shared.emitEvent(topic: Self.deltaTopic, payload: payload) + } + + // MARK: - Row building + + /// Builds the flattened cross-window rows, mirroring the enumeration and + /// field semantics of `v2MobileWorkspaceList`'s all-windows branch (same + /// sources, same fallbacks) so the two views of the list can never + /// disagree on content, only on transport shape. + private func buildRows() -> (workspaces: [WorkspaceSyncRecord], groups: [GroupSyncRecord]) { + guard let app = AppDelegate.shared else { + return ([], []) + } + let controller = TerminalController.shared + let selectedWorkspaceID = app.currentScriptableMainWindow()?.tabManager.selectedTabId + let notificationStore = app.notificationStore + + var workspaceRows: [WorkspaceSyncRecord] = [] + var groupRows: [GroupSyncRecord] = [] + var seenWindowIDs: Set = [] + var seenWorkspaceIDs: Set = [] + var seenGroupIDs: Set = [] + var liveWorkspaceIDs: Set = [] + + for summary in app.listMainWindowSummaries() { + guard seenWindowIDs.insert(summary.windowId).inserted else { continue } + guard let windowTabManager = app.tabManagerFor(windowId: summary.windowId) else { continue } + for group in windowTabManager.workspaceGroups where seenGroupIDs.insert(group.id).inserted { + groupRows.append( + GroupSyncRecord( + id: group.id.uuidString, + name: group.name, + isCollapsed: group.isCollapsed, + isPinned: group.isPinned, + anchorWorkspaceID: group.anchorWorkspaceId.uuidString, + sortIndex: groupRows.count + ) + ) + } + for workspace in windowTabManager.tabs where seenWorkspaceIDs.insert(workspace.id).inserted { + liveWorkspaceIDs.insert(workspace.id) + workspaceRows.append( + workspaceRow( + workspace: workspace, + windowID: summary.windowId, + isSelected: workspace.id == selectedWorkspaceID, + sortIndex: workspaceRows.count, + controller: controller, + notificationStore: notificationStore + ) + ) + } + } + previewCache = previewCache.filter { liveWorkspaceIDs.contains($0.key) } + return (workspaceRows, groupRows) + } + + private func workspaceRow( + workspace: Workspace, + windowID: UUID, + isSelected: Bool, + sortIndex: Int, + controller: TerminalController, + notificationStore: TerminalNotificationStore? + ) -> WorkspaceSyncRecord { + let terminals = controller.mobileTerminalPanels(in: workspace).map { terminal -> WorkspaceSyncRecord.Terminal in + let terminalDirectory = workspace.effectivePanelDirectory( + panelId: terminal.id, + localFallback: controller.mobileNonEmpty(terminal.directory) + ?? controller.mobileNonEmpty(terminal.requestedWorkingDirectory) + ) + return WorkspaceSyncRecord.Terminal( + id: terminal.id.uuidString, + title: workspace.panelTitle(panelId: terminal.id) ?? terminal.displayTitle, + currentDirectory: terminalDirectory, + isReady: terminal.surface.surface != nil, + isFocused: terminal.id == workspace.focusedPanelId + ) + } + let latestNotification = notificationStore?.latestNotification(forTabId: workspace.id) + let preview = cachedPreview(workspaceID: workspace.id, latestNotification: latestNotification) + return WorkspaceSyncRecord( + id: workspace.id.uuidString, + windowID: windowID.uuidString, + title: workspace.title, + currentDirectory: workspace.presentedCurrentDirectory, + isSelected: isSelected, + isPinned: workspace.isPinned, + groupID: workspace.groupId?.uuidString, + preview: preview?.text, + previewAt: preview?.epochSeconds, + lastActivityAt: (latestNotification?.createdAt ?? workspace.createdAt).timeIntervalSince1970, + hasUnread: notificationStore?.workspaceIsUnread(forTabId: workspace.id) ?? false, + sortIndex: sortIndex, + terminals: terminals + ) + } + + /// The legacy path's `mobileWorkspacePreview` semantics with a cache: the + /// sanitizer runs only when the workspace's latest notification identity + /// changed since the last rebuild. + private func cachedPreview( + workspaceID: UUID, + latestNotification: TerminalNotification? + ) -> (text: String, epochSeconds: Double)? { + guard let notification = latestNotification else { + previewCache[workspaceID] = nil + return nil + } + if let cached = previewCache[workspaceID], + cached.notificationID == notification.id, + cached.createdAt == notification.createdAt { + guard let text = cached.text else { return nil } + return (text, notification.createdAt.timeIntervalSince1970) + } + let raw = notification.body.isEmpty ? notification.title : notification.body + let text = TerminalController.mobilePreviewSanitize(raw) + previewCache[workspaceID] = PreviewCacheEntry( + notificationID: notification.id, + createdAt: notification.createdAt, + text: text + ) + guard let text else { return nil } + return (text, notification.createdAt.timeIntervalSince1970) + } +} + +extension TerminalController { + /// `mobile.sync.fetch`: cursor-based fetch for mobile state sync v2. + func v2MobileSyncFetch(params: [String: Any]) -> V2CallResult { + MobileStateSyncHost.shared.fetch(params: params) + } +} diff --git a/Sources/Mobile/MobileWorkspaceListObserver.swift b/Sources/Mobile/MobileWorkspaceListObserver.swift index 3779c9496494..b2e6d68de932 100644 --- a/Sources/Mobile/MobileWorkspaceListObserver.swift +++ b/Sources/Mobile/MobileWorkspaceListObserver.swift @@ -292,6 +292,10 @@ final class MobileWorkspaceListObserver { cmuxDebugLog("mobile.observer EMIT workspace.updated hash=\(hash) tabs=\(tabManager.tabs.count) force=\(force)") #endif MobileHostService.shared.emitEvent(topic: "workspace.updated", payload: [:]) + // v2 phones get per-record deltas instead of the empty invalidation + // above. Same tick, same throttle; a no-op diff emits nothing, and the + // call returns immediately when no phone subscribed to the delta topic. + MobileStateSyncHost.shared.broadcastIfSubscribed() } /// Stable hash of the iOS-facing shape: workspace ids + titles + their diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 6c0a57d60034..f5623209f0e6 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -13864,6 +13864,8 @@ class TerminalController { result = v2MobileNotificationReconcile(params: request.params) case "dogfood.feedback.submit": result = await v2MobileDogfoodFeedbackSubmit(params: request.params) + case "mobile.sync.fetch": + result = v2MobileSyncFetch(params: request.params) default: result = .err(code: "method_not_found", message: "Unknown mobile method", data: [ "method": request.method diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index b033800653bc..85d145f9f0db 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1060,6 +1060,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A2538FE83AE79539E3BF9248 /* MobilePairingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9BC53FA4991A6EBFB930EDF /* MobilePairingView.swift */; }; 18A8E29E9BD87E184983527C /* MobilePairingWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AE701F43A0B49F08835191C /* MobilePairingWindowController.swift */; }; 9916B44C7A9914E172D112D4 /* MobileRouteResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A956C76162B79EC74AF9965 /* MobileRouteResolver.swift */; }; + 7BD32764E8A31FA15DCCF257 /* MobileStateSync.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2DBE587F52C8A3B2A2CFCB8 /* MobileStateSync.swift */; }; AB57F0C27BECE8EDFC6B2B97 /* MobileTerminalByteTee.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F05EBBC2FE0D5CB2F662B8A /* MobileTerminalByteTee.swift */; }; C9CFB398DF94D6DDEAF42D67 /* MobileTerminalRenderObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = F51B54FAD18160281FC1C2B6 /* MobileTerminalRenderObserver.swift */; }; F7A110000000000000000003 /* MobileTerminalThemeEmissionDecision.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7A110000000000000000004 /* MobileTerminalThemeEmissionDecision.swift */; }; @@ -3032,6 +3033,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = F9BC53FA4991A6EBFB930EDF /* MobilePairingView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Pairing/MobilePairingView.swift"; sourceTree = ""; }; 5AE701F43A0B49F08835191C /* MobilePairingWindowController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Pairing/MobilePairingWindowController.swift"; sourceTree = ""; }; 7A956C76162B79EC74AF9965 /* MobileRouteResolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileRouteResolver.swift; sourceTree = ""; }; + A2DBE587F52C8A3B2A2CFCB8 /* MobileStateSync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileStateSync.swift; sourceTree = ""; }; 4F05EBBC2FE0D5CB2F662B8A /* MobileTerminalByteTee.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileTerminalByteTee.swift; sourceTree = ""; }; F51B54FAD18160281FC1C2B6 /* MobileTerminalRenderObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileTerminalRenderObserver.swift; sourceTree = ""; }; F7A110000000000000000004 /* MobileTerminalThemeEmissionDecision.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileTerminalThemeEmissionDecision.swift; sourceTree = ""; }; @@ -4165,6 +4167,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B8B056D90000000000000002 /* MobileHostIdentity.swift */, 47BDC06F004C02A52B05E4A0 /* MobileHostRPC.swift */, 7ACA497A6831165EA879C642 /* MobileHostService.swift */, + A2DBE587F52C8A3B2A2CFCB8 /* MobileStateSync.swift */, 1B0B09010000000000000001 /* MobileHostIrohRuntime.swift */, 1B0B09020000000000000001 /* MobileHostIrohRuntime+Activation.swift */, 1B0B09030000000000000001 /* MobileHostIrohRuntime+SettingsControl.swift */, @@ -7095,6 +7098,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A2538FE83AE79539E3BF9248 /* MobilePairingView.swift in Sources */, 18A8E29E9BD87E184983527C /* MobilePairingWindowController.swift in Sources */, 9916B44C7A9914E172D112D4 /* MobileRouteResolver.swift in Sources */, + 7BD32764E8A31FA15DCCF257 /* MobileStateSync.swift in Sources */, AB57F0C27BECE8EDFC6B2B97 /* MobileTerminalByteTee.swift in Sources */, C9CFB398DF94D6DDEAF42D67 /* MobileTerminalRenderObserver.swift in Sources */, F7A110000000000000000003 /* MobileTerminalThemeEmissionDecision.swift in Sources */, diff --git a/docs/mobile-state-sync-v2.md b/docs/mobile-state-sync-v2.md new file mode 100644 index 000000000000..6cf203ff0a6c --- /dev/null +++ b/docs/mobile-state-sync-v2.md @@ -0,0 +1,104 @@ +# Mobile state sync v2 (delta protocol) + +Status: implementing, July 2026. Replaces the invalidate-and-refetch workspace +sync between the Mac host and iOS clients. Transport-agnostic: rides the +existing framed RPC control stream and event subscription on both the legacy +TCP path and Iroh; it does not depend on Iroh work in flight. + +## Problem + +Today any workspace change (notification line, title, unread dot, selection) +emits `workspace.updated` with an empty payload, throttled to 80ms, and every +subscribed phone re-fetches the entire `mobile.workspace.list` response. Each +workspace row is ~0.5-1KB of JSON (including a 140-char activity preview), so +at 100+ workspaces one changed field costs ~100KB of serialization on the Mac +main actor plus ~100KB on the wire, per phone, per change burst. The phone then +diffs nothing: it replaces its whole list. The event also carries no ordering +information, so a missed edge is silent staleness until the next change. + +## Design + +Two collections, `workspaces` and `groups`, are synced as versioned records. + +Versioning: +- `epoch`: UUID minted when the Mac's sync store is created (process launch). + A client cursor is only meaningful within one epoch. +- `rev`: per-collection monotonic UInt64 head revision. Every change tick that + modifies a collection bumps its head by one; all records changed in that tick + are stamped with the new head. +- Removals are recorded as `(id, rev)` tombstones in a bounded ring (1024). A + cursor older than the oldest retained tombstone gets a snapshot instead of a + delta. + +Wire contract (same JSON envelope and framing as every other mobile RPC): +- `mobile.sync.fetch` request: `{"collections": [{"id": "workspaces", + "epoch": "...", "rev": 123}, ...]}`. `epoch`/`rev` omitted on cold start. + Response per collection is either `{"mode": "delta", "from_rev": 123, + "rev": 130, "records": [changed rows], "removed_ids": [...]}` or + `{"mode": "snapshot", "rev": 130, "records": [all rows]}`, plus the current + top-level `epoch`. +- Event topic `mobile.sync.delta` (subscribed through the existing + `mobile.events.subscribe`): `{"epoch", "collection", "from_rev", "to_rev", + "records": [changed rows], "removed_ids": [...]}`. + +Client apply rule: a delta applies iff the epoch matches and +`from_rev <= local rev < to_rev`. Records are full rows keyed by id, so +overlapping frames apply idempotently. `from_rev > local rev` is a gap: the +client re-runs `mobile.sync.fetch` with its cursor and gets a delta or +snapshot. Ordering violations therefore self-heal instead of accumulating. + +Startup ordering: the client subscribes to `mobile.sync.delta` first, then +fetches. A delta arriving during the fetch either overlaps (idempotent) or +gaps (repair fetch); there is no window where a change can be silently lost. + +Record shapes mirror the existing `mobile.workspace.list` row fields +(snake_case), plus `sort_index` so list order syncs explicitly. Group +membership stays derived from each workspace's `group_id` on the client, +matching current behavior. + +## Compatibility and negotiation + +The capability check is the method itself: a new phone calls +`mobile.sync.fetch`; a Mac that does not implement it returns method-not-found +and the phone falls back to the legacy refetch loop. Old phones never call it +and keep the legacy `workspace.updated` behavior, which the Mac continues to +emit unchanged. No settings flag. + +## Mac-side production + +`MobileWorkspaceListObserver` already owns the change sources (tabs, selection, +groups, notifications, unread indicators) behind an 80ms latest-wins throttle. +Each tick additionally builds typed rows, applies them to the store (which +diffs by value and bumps revs only for real changes), and emits one +`mobile.sync.delta` frame per changed collection when the topic has +subscribers. The store diff replaces the current summary-hash dedup for v2 +consumers; the legacy empty event keeps using the hash. + +Cost model: each tick is one O(rows) typed rebuild and diff on the main actor, +bounded by the same 80ms throttle as today, and replaces per-phone full-list +serialization with one shared small frame. The activity-preview sanitizer runs +only for rows whose source notification changed. + +## iOS-side consumption + +A mirror store per connected Mac holds records + cursor and projects ordered +rows into the same published state the workspace list UI renders today. The +adapter negotiates v2 at connect; on event-stream loss or reconnect it fetches +with its cursor instead of reloading the full list. Foreground Mac first; +secondary Macs move to the same path once the foreground path is proven. + +## Explicitly out of scope here + +- Terminal byte/render-grid streaming (separate lane work; the render-grid + path is already delta-based and well-coalesced). +- The RPC session write-stall/heartbeat hardening (next PR in this program). +- Refactors of `MobileShellComposite`/`TerminalController` beyond the minimal + seams (new extension files, no restructuring). + +## Future refinements (documented, not built) + +- Fractional ordering keys to avoid N sort_index bumps on reorder. +- Per-client outbox coalescing for slow phones (today's bounded per-connection + event queue suffices because delta frames are ~1000x smaller than the + refetches they replace). +- Binary record encoding once the control stream grows an opcode envelope. From f5d513de957e6621ebd0e0f2a7fff5c5c649448e Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Fri, 17 Jul 2026 00:11:35 -0700 Subject: [PATCH 02/21] Merge main (iOS reconnect/build isolation fix) and guard stale sync fetches Merges origin/main to pull in the dev-build flakiness fix from https://github.com/manaflow-ai/cmux/pull/8299. The negotiation fetch now checks client currency and cancellation before sending, so a fetch task from a replaced listener generation can never redial its stale client's route underneath the replacement connection (caught by manualReconnectRedialsWhenLiveStreamIsUnavailableButRPCStateIsConnected after the merge). Co-Authored-By: Claude Fable 5 --- .../CmuxMobileShell/MobileShellComposite+StateSync.swift | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index 92d8ed64cb42..430437a19c22 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -77,6 +77,13 @@ extension MobileShellComposite { } private func runStateSyncFetch(client: MobileCoreRPCClient) async { + // Currency check BEFORE the send, not only after: a negotiation task + // scheduled for a listener generation that has since been replaced + // must not touch its stale client at all — `sendRequest` on a + // torn-down session would redial that client's route underneath the + // replacement connection (an extra transport dial the reconnect + // paths never asked for). + guard remoteClient === client, connectionState == .connected, !Task.isCancelled else { return } let params: [String: Any] do { params = try MobileSyncFrameJSON.jsonObject(from: stateSyncMirror.fetchRequest) From 4788fd7498b09cdd4403813e178185561198cb04 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Fri, 17 Jul 2026 00:32:49 -0700 Subject: [PATCH 03/21] Use explicit self in sidebar row tint closure for newer toolchains main's SidebarWorkspaceRowSlotViews.swift fails to compile on the Blacksmith macos-26 runners (escaping-closure capture of 'color' needs explicit self there). Out of this PR's feature scope, but required to produce any dev build of a branch containing current main on that toolchain; behavior unchanged. Co-Authored-By: Claude Fable 5 --- .../AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift index 659d7dc50925..37cc31126f64 100644 --- a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift +++ b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift @@ -98,7 +98,10 @@ final class SidebarRowPullRequestIconView: NSView { // transparent backing draws nothing (no destination pixels). let tinted = NSImage(size: image.size, flipped: false) { drawRect in image.draw(in: drawRect, from: .zero, operation: .sourceOver, fraction: 1) - color.set() + // Explicit self: newer Swift toolchains (Blacksmith + // macos-26 runners) require it for the escaping-closure + // capture here and refuse to compile otherwise. + self.color.set() drawRect.fill(using: .sourceAtop) return true } From c9f807942eae6e76741abb0e64fac792373faf18 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 13:13:03 -0700 Subject: [PATCH 04/21] Adopt main's sidebar tint-closure fix verbatim Main fixed the Blacksmith toolchain compile with a [color] capture; drop this branch's interim explicit-self variant so the file matches main. Co-Authored-By: Claude Fable 5 --- .../AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift index e725a3703bd0..df8b7e78b4b1 100644 --- a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift +++ b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift @@ -114,10 +114,7 @@ final class SidebarRowPullRequestIconView: NSView { // transparent backing draws nothing (no destination pixels). let tinted = NSImage(size: image.size, flipped: false) { [color] drawRect in image.draw(in: drawRect, from: .zero, operation: .sourceOver, fraction: 1) - // Explicit self: newer Swift toolchains (Blacksmith - // macos-26 runners) require it for the escaping-closure - // capture here and refuse to compile otherwise. - self.color.set() + color.set() drawRect.fill(using: .sourceAtop) return true } From e04e0063e69dfe8c0294622883d845489e4228ed Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 14:15:12 -0700 Subject: [PATCH 05/21] Prove mobile.sync.delta rides the independent Iroh server-events lane Adds a session-level test: a typed state-sync delta pushed through the independent event stream (the lane an admitted Iroh connection negotiates via iroh_server_events_v1) reaches a mobile.sync.delta topic listener and decodes to the typed frame. Locks in that sync v2 is lane-agnostic on the Iroh transport. Co-Authored-By: Claude Fable 5 --- .../MobileCoreRPCIndependentEventTests.swift | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift index 64b94d95e781..41c91ae00668 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift @@ -131,6 +131,73 @@ struct MobileCoreRPCIndependentEventTests { await client.disconnect() } + @Test + func stateSyncDeltaRidesTheIndependentIrohLaneAndDecodesTyped() async throws { + // Mobile state sync v2 events must be lane-agnostic: on an Iroh + // connection the negotiated `iroh_server_events_v1` stream, not the + // control stream, carries `mobile.sync.delta`. Prove the topic flows + // through the independent lane and decodes to the typed frame. + let route = try irohRoute(hexBytePair: "ef") + let source = IndependentEventSource() + let runtime = TestMobileSyncRuntime( + transportFactory: FixedTransportFactory(transport: NeverConnectedTransport()), + independentEventByteStreamProvider: { _ in + await source.makeStream() + } + ) + let client = MobileCoreRPCClient( + runtime: runtime, + route: route, + ticket: try ticket(route: route, deviceSuffix: "005") + ) + let subscription = await client.subscribe(to: ["mobile.sync.delta"]) + var events = subscription.makeAsyncIterator() + + #expect(await client.prepareIndependentServerEvents()) + + let delta = MobileSyncDeltaEvent( + epoch: "epoch-iroh", + collection: .workspaces, + fromRev: 7, + toRev: 8, + records: [ + WorkspaceSyncRecord( + id: "ws-iroh", + windowID: "win-1", + title: "over-iroh", + currentDirectory: nil, + isSelected: false, + isPinned: false, + groupID: nil, + preview: nil, + previewAt: nil, + lastActivityAt: 1, + hasUnread: false, + sortIndex: 0, + terminals: [] + ) + ], + removedIDs: ["ws-gone"] + ) + let envelope = try JSONSerialization.data(withJSONObject: [ + "kind": "event", + "topic": "mobile.sync.delta", + "payload": try MobileSyncFrameJSON.jsonObject(from: delta), + ]) + await source.yield(try MobileSyncFrameCodec.encodeFrame(envelope)) + + let event = await events.next() + #expect(event?.topic == "mobile.sync.delta") + let payload = try #require(event?.payloadJSON) + let decoded = try JSONDecoder().decode( + MobileSyncDeltaEvent.self, + from: payload + ) + #expect(decoded == delta) + + await client.disconnect() + } + @Test func independentStreamFailureDoesNotFinishControlEventListeners() async throws { let route = try irohRoute(hexBytePair: "cd") From 1546b8ca270dd4a030271cfc677caf19a6db4f5e Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 19:54:20 -0700 Subject: [PATCH 06/21] Regression test: hung redial must settle and unfreeze recovery A transport dial that parks forever (wedged Iroh dial, issue 8531) holds the recovery owner's in-flight claim indefinitely: no failure settles, no backoff retry is scheduled, and every other trigger defers forever. Fails without the fix. Co-Authored-By: Claude Fable 5 --- ...hellRenderGridLivenessRuntimeSupport.swift | 1 + .../ReconnectAttemptDeadlineTests.swift | 68 +++++++++++++++++++ ...ReconnectRouteSelectionTests+Support.swift | 38 +++++++++++ 3 files changed, 107 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessRuntimeSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessRuntimeSupport.swift index 447ec2421568..5c957bbf02cb 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessRuntimeSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessRuntimeSupport.swift @@ -27,4 +27,5 @@ struct LivenessTestRuntime: MobileSyncRuntime { var pairingAttemptTimeoutNanoseconds: UInt64 = 8 * 1_000_000_000 var supportsServerPushEvents: Bool = true var livenessProbeTimeoutNanoseconds: UInt64 = 200_000_000 + var reconnectAttemptDeadlineNanoseconds: UInt64 = 30 * 1_000_000_000 } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift new file mode 100644 index 000000000000..65fb891a6561 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift @@ -0,0 +1,68 @@ +import CMUXMobileCore +import Foundation +import Testing + +@testable import CmuxMobileShell + +// Regression coverage for https://github.com/manaflow-ai/cmux/issues/8531's +// wedge half: a redial whose transport dial hangs forever (relay DNS churn, +// hole-punch stall) must not hold the recovery owner's in-flight claim +// indefinitely. The attempt has a hard deadline; at expiry it settles as a +// timed-out failure, transient backoff is recorded, and the recovery machine +// accepts new triggers (manual retry succeeds immediately). +@MainActor +extension ReconnectRouteSelectionTests { + @Test func hungRedialSettlesAtDeadlineAndUnfreezesRecovery() async throws { + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let factory = KindRecordingTransportFactory(router: router, box: box) + var runtime = LivenessTestRuntime( + transportFactory: factory, + now: { clock.now }, + supportedRouteKinds: [.iroh] + ) + // Small enough that the test settles fast; the production default is 30s. + runtime.reconnectAttemptDeadlineNanoseconds = 150_000_000 + let store = try await makeReconnectStore( + routes: [try iroh()], + runtime: runtime + ) + + #expect(await store.reconnectActiveMacIfAvailable(stackUserID: "user-1")) + #expect(store.connectionState == .connected) + let client = try #require(store.remoteClient) + + // Every dial from here on parks forever, exactly like the observed + // wedged Iroh dial. + factory.setHangingKinds([.iroh]) + let dialsBeforeDrop = factory.attemptedKinds().count + + store.recoverDeadConnection(trigger: .eventStreamEnded, expectedClient: client) + + // Pre-fix: the attempt never settles, isRedialingOrValidating stays + // true forever, and this poll times out. Post-fix: the deadline + // abandons the hung dial and settles the attempt as failed. + let settled = try await pollUntil { + !store.connectionRecoveryOwner.isRedialingOrValidating + } + #expect(settled, "a hung dial must settle at the attempt deadline, not hold recovery forever") + #expect(factory.attemptedKinds().count > dialsBeforeDrop, "the hung dial itself was attempted") + #expect(store.connectionState != .connected) + + // The timed-out attempt must feed the automatic retry loop: transient + // backoff is recorded for the account the attempt dialed for. + #expect(store.automaticIrohReconnectIsBlocked(accountID: "user-1")) + + // And the machine is unfrozen: a manual retry (hang lifted, modeling + // the network recovering) dials fresh and connects. + factory.setHangingKinds([]) + let dialsBeforeManual = factory.attemptedKinds().count + await store.reconnectOrRefresh() + let reconnected = try await pollUntil { + store.connectionState == .connected + } + #expect(reconnected, "manual retry after a settled deadline must reconnect") + #expect(factory.attemptedKinds().count > dialsBeforeManual) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift index a75466e4dd69..ef132dafdce3 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift @@ -174,6 +174,14 @@ final class KindRecordingTransportFactory: CmxByteTransportFactory, @unchecked S private let lock = NSLock() private var kinds: [CmxAttachTransportKind] = [] private var authorizationModes: [CmxTransportAuthorizationMode] = [] + private var hangingKinds: Set = [] + + /// Route kinds whose transports park forever in `connect()` from now on. + /// Models an Iroh dial that neither completes nor fails (relay DNS churn, + /// hole-punch stall) so tests can prove recovery attempts stay bounded. + func setHangingKinds(_ kinds: Set) { + lock.withLock { hangingKinds = kinds } + } init( router: LivenessHostRouter, @@ -206,6 +214,9 @@ final class KindRecordingTransportFactory: CmxByteTransportFactory, @unchecked S if failingKinds.contains(route.kind) { throw RouteRecordingTransportError.routeFailed } + if lock.withLock({ hangingKinds.contains(route.kind) }) { + return HangingConnectTransport() + } let transport = LivenessTransport(router: router) box.set(transport) return transport @@ -219,3 +230,30 @@ final class KindRecordingTransportFactory: CmxByteTransportFactory, @unchecked S lock.withLock { authorizationModes } } } + +/// A transport whose `connect()` parks forever, ignoring cancellation the way +/// a wedged FFI dial does. Reads/sends are unreachable because connect never +/// returns. +actor HangingConnectTransport: CmxByteTransport { + private var parked: [CheckedContinuation] = [] + + func connect() async throws { + await withCheckedContinuation { continuation in + parked.append(continuation) + } + } + + func receive() async throws -> Data? { nil } + + func send(_ data: Data) async throws { + throw MobileShellConnectionError.connectionClosed + } + + func close() async { + let waiters = parked + parked = [] + for waiter in waiters { + waiter.resume() + } + } +} From a2f59a3613bdfaf8863fe31553623ae718cbc82c Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 19:54:20 -0700 Subject: [PATCH 07/21] Bound reconnect attempts with a hard deadline; manual retry clears backoff Every automatic stored-Mac redial now races a per-attempt deadline (runtime-injectable, default 30s). At expiry the attempt is abandoned (generation guards make late completion harmless), settled as timedOut, and transient backoff schedules the next automatic try, so a hung Iroh dial can no longer freeze the recovery machine into a permanent "Disconnected - Tap Reconnect" dead end. The user's explicit reconnect/pull gesture now clears transient backoff the same way recoverMobileConnection(.manual) does, so a recorded cooldown can never swallow a manual tap. Co-Authored-By: Claude Fable 5 --- .../CmuxMobileRPC/MobileSyncRuntime.swift | 15 +++++ ...ileShellComposite+ConnectionRecovery.swift | 64 +++++++++++++++++-- ...ShellComposite+WorkspaceListRecovery.swift | 8 +++ 3 files changed, 83 insertions(+), 4 deletions(-) diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncRuntime.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncRuntime.swift index 8ccb6e2af1cc..7174d316b656 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncRuntime.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncRuntime.swift @@ -51,6 +51,16 @@ public protocol MobileSyncRuntime: Sendable { /// declaring the stream dead; the deadline bounds how long a dead /// transport can stall that verdict. var livenessProbeTimeoutNanoseconds: UInt64 { get } + + /// Hard ceiling on one automatic reconnect attempt (stored-Mac redial) + /// end to end. An Iroh dial can hang far past any per-transport connect + /// timeout (relay DNS churn, hole-punch stalls), and an unbounded attempt + /// wedges the recovery owner: no failure is ever recorded, no backoff + /// retry is ever scheduled, and every other trigger defers to the + /// "in-flight" attempt forever. At the deadline the attempt is abandoned + /// and settled as timed out so the automatic backoff retry loop keeps + /// running. + var reconnectAttemptDeadlineNanoseconds: UInt64 { get } } public extension MobileSyncRuntime { @@ -71,4 +81,9 @@ public extension MobileSyncRuntime { /// while keeping dead-stream recovery within a few seconds of the silence /// threshold instead of the full ``rpcRequestTimeoutNanoseconds``. var livenessProbeTimeoutNanoseconds: UInt64 { 3_000_000_000 } + + /// Default reconnect-attempt ceiling: comfortably above a slow relay dial + /// (transport connects bound themselves near 15s) while turning a hung + /// dial into a settled, retryable failure within half a minute. + var reconnectAttemptDeadlineNanoseconds: UInt64 { 30_000_000_000 } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 0e1c1ebbe624..9b45008bc18a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -233,12 +233,47 @@ extension MobileShellComposite { // Recovery uses authenticated local Iroh state first. A stuck // account-backup fetch must not block a known EndpointID from // dialing; normal launch reconnect still refreshes first. - let reconnectOutcome = await self.reconnectActiveMacOutcome( - stackUserID: stackUserID, - refreshBackupBeforeDial: false - ) + // + // The redial runs under a hard deadline. An Iroh dial can hang + // far past any per-transport connect timeout (observed: relay + // DNS churn for 15+ minutes), and while this attempt is + // in-flight the recovery owner defers every other trigger, so + // one hung dial used to freeze the entire recovery machine + // with no failure, no backoff retry, and a permanent + // "Disconnected - Tap Reconnect" dead end + // (https://github.com/manaflow-ai/cmux/issues/8531). At the + // deadline the attempt is abandoned (generation guards make a + // late completion harmless: a late success just connects, a + // late failure finds the attempt already settled) and the + // transient backoff owner schedules the next automatic try. + let deadlineNanoseconds = self.runtime?.reconnectAttemptDeadlineNanoseconds + ?? 30_000_000_000 + let reconnectOutcome = await Self.raceAgainstDeadline( + nanoseconds: deadlineNanoseconds + ) { [weak self] in + await self?.reconnectActiveMacOutcome( + stackUserID: stackUserID, + refreshBackupBeforeDial: false + ) ?? .superseded + } guard !Task.isCancelled, self.connectionRecoveryOwner.isCurrent(attempt) else { return } + guard let reconnectOutcome else { + MobileDebugLog.anchormux( + "connection.recovery redial deadline expired; abandoning attempt \(attempt.id.uuidString)" + ) + guard self.failConnectionRecovery(attempt, failure: .timedOut) else { return } + if self.connectionState == .connected { + self.connectionState = .disconnected + self.macConnectionStatus = .unavailable + self.clearRemoteConnectionContext() + } + if let accountID = stackUserID ?? self.identityProvider?.currentUserID { + self.recordTransientAutomaticReconnectBackoff(accountID: accountID) + } + self.applyConnectionRecoveryOwnerState() + return + } guard self.settleConnectionRecovery( attempt, outcome: reconnectOutcome, @@ -803,4 +838,25 @@ extension MobileShellComposite { /// `mobile.attach_ticket.create` connects via a synthetic `manual-…` ticket; /// passing the real id keys the foreground aggregate state under it instead of /// the synthetic id. `nil` for a genuinely manual/unknown host. + + /// Races `operation` against a wall-clock deadline. Returns the + /// operation's value, or `nil` when the deadline expires first. The + /// losing side is cancelled best-effort; a hung FFI dial may ignore + /// cancellation, which is exactly why the caller must abandon the + /// attempt instead of awaiting it forever. + static func raceAgainstDeadline( + nanoseconds: UInt64, + _ operation: @escaping @Sendable () async -> Value + ) async -> Value? { + await withTaskGroup(of: Value?.self) { group in + group.addTask { await operation() } + group.addTask { + try? await Task.sleep(nanoseconds: nanoseconds) + return nil + } + let first = await group.next() ?? nil + group.cancelAll() + return first + } + } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceListRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceListRecovery.swift index 5b532af4a4f8..ac955b4f7ef6 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceListRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceListRecovery.swift @@ -55,6 +55,14 @@ extension MobileShellComposite { return } let reconnectTargetMacDeviceID = workspaceListReconnectTargetMacDeviceID() + // This is the user's explicit Reconnect/pull gesture: like + // `recoverMobileConnection(trigger: .manual)`, it must bypass the + // automatic-retry cooldown. Without this, a transient backoff recorded + // by a failed (or deadline-abandoned) automatic attempt silently + // swallows the user's tap and the dial never happens. + if let accountID = identityProvider?.currentUserID { + clearTransientAutomaticReconnectBackoff(accountID: accountID) + } if connectionState == .connected { // The live event stream can fail before the RPC client's transport // closes. In that state the workspace list correctly renders the From f7bcc0d5237f074d801aa4ba2d04176315f21329 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 20:56:55 -0700 Subject: [PATCH 08/21] Address review findings: sync integrity guards + fetch handle race - Store payloads no longer emit tombstones for ids that are live again (remove-then-readd inside a cursor span would have deleted the re-added record on the client); mirror applies removals before upserts as belt-and-braces. - Same-epoch snapshots older than the mirror cursor are ignored (a stale in-flight fetch response can no longer roll the mirror back). - An undecodable delta for a known collection now schedules a cursor repair fetch instead of leaving the mirror silently stale. - While v2 owns the list, the legacy full-list reload path keeps its liveness-probe role but re-bases the mirror through a cursor fetch instead of overwriting projected state. - The single-flight fetch handle is generation-guarded so a cancelled predecessor's deferred cleanup cannot erase its replacement's handle. - Qualify the payload-reduction claim in the design doc. Co-Authored-By: Claude Fable 5 --- .../MobileStateSyncMirror.swift | 15 +++++-- .../CMUXMobileCore/MobileStateSyncStore.swift | 8 +++- .../MobileStateSyncMirrorTests.swift | 16 +++++++ .../MobileStateSyncStoreTests.swift | 15 +++++++ ...ileShellComposite+ConnectionRecovery.swift | 10 +++++ .../MobileShellComposite+StateSync.swift | 42 +++++++++++++++++-- .../MobileShellComposite.swift | 3 ++ docs/mobile-state-sync-v2.md | 5 ++- 8 files changed, 104 insertions(+), 10 deletions(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift index cc8405000825..200348c72248 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift @@ -46,6 +46,12 @@ public final class MobileSyncCollectionMirror { public func apply(payload: MobileSyncCollectionPayload, epoch payloadEpoch: String) -> MobileSyncApplyResult { switch payload.mode { case .snapshot: + // A same-epoch snapshot older than the cursor is a stale in-flight + // response overtaken by newer deltas; applying it would roll the + // mirror back until the next delta gaps and repairs. Ignore it. + if let epoch, epoch == payloadEpoch, payload.rev < rev { + return .staleIgnored + } recordsByID = Dictionary( payload.records.map { ($0.syncID, $0) }, uniquingKeysWith: { _, last in last } @@ -85,12 +91,15 @@ public final class MobileSyncCollectionMirror { guard let epoch, epoch == changeEpoch else { return .gap } guard fromRev <= rev else { return .gap } guard toRev > rev else { return .staleIgnored } - for record in records { - recordsByID[record.syncID] = record - } + // Removals first: the producer already excludes tombstones for + // currently-live ids, so within one payload an id in both lists means + // the upsert is the newer fact and must win. for id in removedIDs { recordsByID[id] = nil } + for record in records { + recordsByID[record.syncID] = record + } rev = toRev return .applied } diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift index a1a0292b14e1..13042d469deb 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift @@ -132,7 +132,13 @@ public final class MobileSyncCollectionStore { ) } let upserts = stampedByID.values.filter { $0.rev > rev }.map(\.record) - let removals = tombstones.filter { $0.rev > rev }.map(\.id) + // A tombstone whose id is live again (removed then re-added inside the + // cursor span) must not travel: the upsert alone is the correct final + // state, and a client applying upserts and removals from one payload + // would otherwise delete the re-added record. + let removals = tombstones + .filter { $0.rev > rev && stampedByID[$0.id] == nil } + .map(\.id) return MobileSyncCollectionPayload( mode: .delta, rev: headRev, diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncMirrorTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncMirrorTests.swift index d01ff87e4220..71be7ba2895d 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncMirrorTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncMirrorTests.swift @@ -95,6 +95,22 @@ struct MobileStateSyncMirrorTests { #expect(mirror.orderedRecords.count == 1) } + @Test func staleSameEpochSnapshotIsIgnored() { + let mirror = MobileSyncCollectionMirror() + _ = mirror.apply(payload: snapshot([group(id: "a"), group(id: "b")], rev: 8), epoch: "e1") + // An in-flight fetch response from rev 5 lands after newer deltas + // advanced the mirror to 8: applying it would roll state back until + // the next delta gaps. It must be ignored. + let result = mirror.apply(payload: snapshot([group(id: "a")], rev: 5), epoch: "e1") + #expect(result == .staleIgnored) + #expect(mirror.rev == 8) + #expect(mirror.orderedRecords.count == 2) + // A NEW epoch's snapshot always applies, whatever its revision. + let newEpoch = mirror.apply(payload: snapshot([group(id: "c")], rev: 1), epoch: "e2") + #expect(newEpoch == .applied) + #expect(mirror.orderedRecords.map(\.syncID) == ["c"]) + } + @Test func epochMismatchReportsGap() { let mirror = MobileSyncCollectionMirror() _ = mirror.apply(payload: snapshot([group(id: "a")], rev: 5), epoch: "e1") diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift index e7124dbc3891..f2a581c5bf29 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift @@ -145,6 +145,21 @@ struct MobileStateSyncStoreTests { #expect(Set(covered.removedIDs) == Set(["b", "c"])) } + @Test func removedThenReaddedRecordTravelsAsUpsertWithoutTombstone() { + let store = MobileSyncCollectionStore() + _ = store.apply(rows: [workspace(id: "a"), workspace(id: "b")]) + _ = store.apply(rows: [workspace(id: "b")]) + _ = store.apply(rows: [workspace(id: "b"), workspace(id: "a", title: "reborn")]) + // A cursor from before the removal spans remove-then-readd. The + // payload must deliver the live row and no tombstone for it; a client + // applying both would delete the re-added record. + let payload = store.payload(since: 1) + #expect(payload.mode == .delta) + #expect(payload.records.map(\.syncID) == ["a"]) + #expect(payload.records.first?.title == "reborn") + #expect(payload.removedIDs.isEmpty) + } + @Test func rootStoreMismatchedEpochResolvesToSnapshot() { let store = MobileStateSyncStore(epoch: "epoch-1") _ = store.workspaces.apply(rows: [workspace(id: "a")]) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 9b45008bc18a..f026aea85a03 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -819,6 +819,16 @@ extension MobileShellComposite { ) let response = try MobileSyncWorkspaceListResponse.decode(data) guard remoteClient === client, connectionState == .connected else { return false } + if stateSyncActive { + // The round-trip above already proved liveness, which is all + // this path's probe callers need. While state sync v2 owns the + // list, applying this legacy full response would overwrite + // mirror-projected state with a snapshot the next delta then + // contradicts; re-base the mirror through its cursor instead + // (the fetch also refreshes the Mac-side store from truth). + requestStateSyncFetch(client: client) + return true + } applyRemoteWorkspaceList(response, preferActiveTicketTarget: false) syncSelectedTerminalForWorkspace() return true diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index 430437a19c22..65a9136ba39d 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -30,8 +30,12 @@ extension MobileShellComposite { /// The caller already proved the event belongs to the current client and a /// connected session. func handleStateSyncDeltaEvent(_ event: MobileEventEnvelope) { - guard let payload = event.payloadJSON else { return } + guard let payload = event.payloadJSON else { + scheduleStateSyncRepairIfActive() + return + } guard let header = try? JSONDecoder().decode(MobileSyncDeltaEventHeader.self, from: payload) else { + scheduleStateSyncRepairIfActive() return } let result: MobileSyncApplyResult @@ -39,12 +43,21 @@ extension MobileShellComposite { case .workspaces: guard let delta = try? JSONDecoder().decode( MobileSyncDeltaEvent.self, from: payload - ) else { return } + ) else { + // A delta we KNOW is for a mirrored collection but cannot + // decode is a lost update: without repair the mirror stays + // silently stale until the next unrelated change gaps it. + scheduleStateSyncRepairIfActive() + return + } result = stateSyncMirror.workspaces.apply(delta: delta) case .groups: guard let delta = try? JSONDecoder().decode( MobileSyncDeltaEvent.self, from: payload - ) else { return } + ) else { + scheduleStateSyncRepairIfActive() + return + } result = stateSyncMirror.groups.apply(delta: delta) default: // A newer Mac may sync collections this build does not know; they @@ -66,12 +79,33 @@ extension MobileShellComposite { } } + /// Entry point for sibling composite extensions (liveness probe and + /// pull-to-refresh paths): re-base the mirror through its cursor. + func requestStateSyncFetch(client: MobileCoreRPCClient) { + scheduleStateSyncFetch(client: client) + } + + /// Repairs the mirror with a cursor fetch when the current client is v2. + private func scheduleStateSyncRepairIfActive() { + guard stateSyncActive, let client = remoteClient else { return } + scheduleStateSyncFetch(client: client) + } + /// Single-flight, restart-on-newest cursor fetch (negotiation and gap /// repair share it, mirroring ``workspaceListRefreshTask`` semantics). private func scheduleStateSyncFetch(client: MobileCoreRPCClient) { stateSyncFetchTask?.cancel() + let generation = UUID() + stateSyncFetchGeneration = generation stateSyncFetchTask = Task { @MainActor [weak self] in - defer { self?.stateSyncFetchTask = nil } + defer { + // Only the generation that still owns the handle may clear + // it: a cancelled predecessor's deferred cleanup must not + // erase the replacement's cancel handle. + if let self, self.stateSyncFetchGeneration == generation { + self.stateSyncFetchTask = nil + } + } await self?.runStateSyncFetch(client: client) } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index f5eca06b19a4..840464167b55 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -778,6 +778,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// Single-flight handle for negotiation and gap-repair fetches, restart-on- /// newest like ``workspaceListRefreshTask``. var stateSyncFetchTask: Task? + /// Identifies the fetch generation that owns ``stateSyncFetchTask``, so a + /// cancelled predecessor's deferred cleanup cannot clear its replacement. + var stateSyncFetchGeneration = UUID() /// The user pull-to-refresh round-trip, kept on its own handle so the /// event-driven ``workspaceListRefreshTask`` cancel/restart can never truncate /// the spinner the pull is awaiting. Rapid pulls coalesce onto this single task. diff --git a/docs/mobile-state-sync-v2.md b/docs/mobile-state-sync-v2.md index 6cf203ff0a6c..6b54746937ec 100644 --- a/docs/mobile-state-sync-v2.md +++ b/docs/mobile-state-sync-v2.md @@ -99,6 +99,7 @@ secondary Macs move to the same path once the foreground path is proven. - Fractional ordering keys to avoid N sort_index bumps on reorder. - Per-client outbox coalescing for slow phones (today's bounded per-connection - event queue suffices because delta frames are ~1000x smaller than the - refetches they replace). + event queue suffices because a typical one-row delta frame is around two + orders of magnitude smaller than the full-list refetch it replaces at a + 100+ workspace scale). - Binary record encoding once the control stream grows an opcode envelope. From defc6eb6aa9dfd4341174fd27633a0b2e31eb5ed Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 21:13:15 -0700 Subject: [PATCH 09/21] Address autoreview round 1: unstructured deadline race, repair fallback, tombstone rev bound - raceAgainstDeadline no longer uses a task group (which structurally awaits a cancellation-ignoring dial); the operation runs unstructured and a lock-guarded once resumes whichever side finishes first. Direct tests cover an operation that never completes and ignores cancellation. - A transiently failed gap-repair fetch now drops back to legacy list semantics (stateSyncActive off + one authoritative reload) instead of stranding the mirror behind a suppressed refetch loop; v2 re-negotiates on the next listener generation. - Tombstone pruning tracks the highest discarded revision; coverability is judged against that bound so a same-revision batch split by the ring cap can never produce a delta that omits a removal. Co-Authored-By: Claude Fable 5 --- .../CMUXMobileCore/MobileStateSyncStore.swift | 30 ++++++------ .../MobileStateSyncStoreTests.swift | 19 +++++++ ...ileShellComposite+ConnectionRecovery.swift | 49 ++++++++++++++----- .../MobileShellComposite+StateSync.swift | 17 +++++++ ...leShellRenderGridLivenessTestSupport.swift | 12 ++++- .../MobileShellStateSyncTests.swift | 33 +++++++++++++ .../ReconnectAttemptDeadlineTests.swift | 21 ++++++++ 7 files changed, 153 insertions(+), 28 deletions(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift index 13042d469deb..27e8bfa23beb 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift @@ -40,9 +40,11 @@ public final class MobileSyncCollectionStore { public private(set) var headRev: UInt64 = 0 private var stampedByID: [String: Stamped] = [:] private var tombstones: [Tombstone] = [] - /// True once tombstones have been discarded to honor the bound; from then - /// on only cursors at or above the oldest retained tombstone are coverable. - private var droppedTombstones = false + /// The highest revision any discarded tombstone carried. Pruning by count + /// can split a batch of removals sharing one revision, so coverability + /// must be judged against the discarded revision bound, not against the + /// oldest retained tombstone (which may be a partial batch). + private var discardedTombstoneRevBound: UInt64 = 0 public init(maximumTombstoneCount: Int = 1024) { self.maximumTombstoneCount = maximumTombstoneCount @@ -80,8 +82,11 @@ public final class MobileSyncCollectionStore { tombstones.append(Tombstone(id: id, rev: headRev)) } if tombstones.count > maximumTombstoneCount { - tombstones.removeFirst(tombstones.count - maximumTombstoneCount) - droppedTombstones = true + let discarded = tombstones.prefix(tombstones.count - maximumTombstoneCount) + if let highestDiscarded = discarded.last?.rev { + discardedTombstoneRevBound = max(discardedTombstoneRevBound, highestDiscarded) + } + tombstones.removeFirst(discarded.count) } return MobileSyncCollectionChange( fromRev: fromRev, @@ -94,19 +99,12 @@ public final class MobileSyncCollectionStore { /// Whether a delta from `rev` can prove completeness. Coverable means every /// removal after `rev` is still retained; otherwise the client must /// snapshot. Upserts are always coverable because records store their full - /// current row. + /// current row. Tombstones with revisions at or below + /// ``discardedTombstoneRevBound`` may be missing (including part of a + /// same-revision batch), so only a cursor at or above that bound is safe. private func canCover(rev: UInt64) -> Bool { guard rev <= headRev else { return false } - guard droppedTombstones else { return true } - guard let oldestRetained = tombstones.first?.rev else { - // All tombstones were discarded; only a fully current cursor needs - // no removal history. - return rev == headRev - } - // A cursor at `rev` needs every removal with rev > `rev`. Retained - // tombstones start at `oldestRetained`, so anything at or after - // `oldestRetained - 1` is provably complete. - return rev >= oldestRetained - 1 + return rev >= discardedTombstoneRevBound } /// Answers one fetch section for a client at `cursor`. `nil` cursor, an diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift index f2a581c5bf29..3d89b9409c72 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift @@ -160,6 +160,25 @@ struct MobileStateSyncStoreTests { #expect(payload.removedIDs.isEmpty) } + @Test func splitTombstoneRevisionBatchForcesSnapshot() { + let store = MobileSyncCollectionStore(maximumTombstoneCount: 2) + _ = store.apply(rows: [ + workspace(id: "a"), workspace(id: "b"), + workspace(id: "c"), workspace(id: "d"), + ]) + // One tick removes three records, all tombstoned at rev 2; the ring + // keeps only two of them. A cursor at rev 1 cannot prove it saw the + // discarded rev-2 removal, so a delta would leave a ghost record — + // it must snapshot even though retained tombstones start at rev 2. + _ = store.apply(rows: [workspace(id: "d")]) + #expect(store.payload(since: 1).mode == .snapshot) + // A cursor at the discarded bound itself is safe: every removal it + // needs (rev > 2) is fully retained. + _ = store.apply(rows: []) + #expect(store.payload(since: 2).mode == .delta) + #expect(store.payload(since: 2).removedIDs == ["d"]) + } + @Test func rootStoreMismatchedEpochResolvesToSnapshot() { let store = MobileStateSyncStore(epoch: "epoch-1") _ = store.workspaces.apply(rows: [workspace(id: "a")]) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index f026aea85a03..caf9d0057962 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -850,23 +850,50 @@ extension MobileShellComposite { /// the synthetic id. `nil` for a genuinely manual/unknown host. /// Races `operation` against a wall-clock deadline. Returns the - /// operation's value, or `nil` when the deadline expires first. The - /// losing side is cancelled best-effort; a hung FFI dial may ignore - /// cancellation, which is exactly why the caller must abandon the - /// attempt instead of awaiting it forever. + /// operation's value, or `nil` when the deadline expires first. + /// + /// Deliberately UNSTRUCTURED: a task group would structurally await the + /// losing child, so a dial that ignores cancellation (the exact wedge + /// this exists for) would suspend the race forever. Instead the + /// operation runs in its own task that the deadline path abandons after + /// a best-effort cancel; the once-guard is MainActor-confined so exactly + /// one side resumes. An abandoned dial retains its captures until it + /// eventually resolves — bounded by transport teardown and precisely the + /// cost of not being wedged. static func raceAgainstDeadline( nanoseconds: UInt64, _ operation: @escaping @Sendable () async -> Value ) async -> Value? { - await withTaskGroup(of: Value?.self) { group in - group.addTask { await operation() } - group.addTask { + await withCheckedContinuation { (continuation: CheckedContinuation) in + let once = RaceContinuationOnce(continuation) + let operationTask = Task { + once.finish(await operation()) + } + Task { try? await Task.sleep(nanoseconds: nanoseconds) - return nil + operationTask.cancel() + once.finish(nil) } - let first = await group.next() ?? nil - group.cancelAll() - return first } } } + +/// Resumes a race continuation exactly once, whichever side finishes first. +/// Lock-based rather than actor-based so both racing tasks can call it +/// without an isolation hop. +private final class RaceContinuationOnce: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + + init(_ continuation: CheckedContinuation) { + self.continuation = continuation + } + + func finish(_ value: Value?) { + lock.lock() + let continuation = self.continuation + self.continuation = nil + lock.unlock() + continuation?.resume(returning: value) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index 65a9136ba39d..c2bc191fa579 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -157,10 +157,27 @@ extension MobileShellComposite { mobileStateSyncLog.error( "state sync fetch failed: \(String(describing: error), privacy: .private)" ) + fallBackToLegacyListAfterFetchFailure(client: client) } catch { mobileStateSyncLog.error( "state sync fetch failed: \(String(describing: error), privacy: .private)" ) + fallBackToLegacyListAfterFetchFailure(client: client) + } + } + + /// A failed repair fetch must not strand the mirror: while + /// ``stateSyncActive`` suppresses the `workspace.updated` refetch loop, + /// the missed delta may have been the last event, so with no fallback the + /// list could stay stale indefinitely. Drop back to legacy semantics (the + /// availability floor) and converge with one authoritative reload; the + /// next event-listener generation re-negotiates v2. + private func fallBackToLegacyListAfterFetchFailure(client: MobileCoreRPCClient) { + guard remoteClient === client, connectionState == .connected else { return } + guard stateSyncActive else { return } + stateSyncActive = false + Task { @MainActor [weak self] in + _ = await self?.reloadWorkspaceListFromMac() } } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift index 159e418e6edb..89deffa87fae 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift @@ -72,6 +72,12 @@ actor LivenessHostRouter { syncFetchResults.append(object) } + /// Scripts the next `mobile.sync.fetch` to fail with a transient (non + /// method_not_found) error, modeling a timeout/decoding failure mid-repair. + func scriptSyncFetchTransientError() { + syncFetchResults.append(["__transient_error__": true]) + } + func record(method: String?, topics: [String]?, workspaceID: String? = nil) { recorded.append(RecordedRequest( method: method, @@ -390,7 +396,11 @@ actor LivenessHostRouter { guard !syncFetchResults.isEmpty else { return try? Self.errorFrame(id: id, code: "method_not_found", message: "Unknown mobile method") } - return try? Self.resultFrame(id: id, result: syncFetchResults.removeFirst()) + let scripted = syncFetchResults.removeFirst() + if scripted["__transient_error__"] as? Bool == true { + return try? Self.errorFrame(id: id, message: "scripted transient sync failure") + } + return try? Self.resultFrame(id: id, result: scripted) case "mobile.terminal.viewport": viewportRequestCount += 1 if heldViewportRequestNumbers.contains(viewportRequestCount) { diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift index 877799afaa31..8676b8e095f7 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift @@ -179,6 +179,39 @@ struct MobileShellStateSyncTests { #expect(fetches >= 2, "gap repair must issue a second mobile.sync.fetch") } + @Test func failedRepairFetchFallsBackToLegacyListAndReenablesRefetch() async throws { + let router = LivenessHostRouter() + await router.scriptSyncFetchResult( + jsonData: try syncSnapshotResultData( + epoch: "epoch-1", + rev: 3, + records: [workspaceRecord(id: UUID().uuidString, title: "synced-alpha", sortIndex: 0)] + ) + ) + // The gap-repair fetch fails transiently; the shell must not strand + // the mirror behind a suppressed refetch loop. + await router.scriptSyncFetchTransientError() + let box = TransportBox() + let clock = TestClock() + let store = try await makeConnectedStore(router: router, box: box, clock: clock) + _ = try await pollUntil { store.stateSyncActive } + + let listCallsBefore = await router.count(of: "mobile.workspace.list") + let transport = try #require(box.get()) + await transport.deliver(try syncDeltaEventFrame( + epoch: "epoch-1", + fromRev: 9, + toRev: 10, + records: [workspaceRecord(id: UUID().uuidString, title: "lost", sortIndex: 1)] + )) + let fellBack = try await pollUntil { !store.stateSyncActive } + #expect(fellBack, "a failed repair fetch must drop back to legacy semantics") + let reloaded = try await pollUntil { + await router.count(of: "mobile.workspace.list") > listCallsBefore + } + #expect(reloaded, "the fallback must converge with one authoritative legacy reload") + } + @Test func legacyMacKeepsWorkspaceUpdatedRefetchLoop() async throws { // No scripted sync result: the router answers `method_not_found`, // modeling a released Mac. diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift index 65fb891a6561..4cd881bbb2d7 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift @@ -12,6 +12,27 @@ import Testing // accepts new triggers (manual retry succeeds immediately). @MainActor extension ReconnectRouteSelectionTests { + @Test func deadlineRaceReturnsNilWhenOperationIgnoresCancellation() async { + // The race must not structurally await the losing side: an operation + // that never completes AND ignores cancellation (the wedged-FFI-dial + // shape) must still let the deadline resolve the race. + let outcome: Int? = await MobileShellComposite.raceAgainstDeadline( + nanoseconds: 50_000_000 + ) { + await withCheckedContinuation { (_: CheckedContinuation) in + // Parked forever; no cancellation handler on purpose. + } + } + #expect(outcome == nil) + } + + @Test func deadlineRaceReturnsOperationValueWhenItWins() async { + let outcome: Int? = await MobileShellComposite.raceAgainstDeadline( + nanoseconds: 5_000_000_000 + ) { 42 } + #expect(outcome == 42) + } + @Test func hungRedialSettlesAtDeadlineAndUnfreezesRecovery() async throws { let clock = TestClock() let router = LivenessHostRouter() From ffdc47e8a8b6980e63191b6f179d29513bbb9b7f Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 21:25:49 -0700 Subject: [PATCH 10/21] Address autoreview round 2: bounded abandoned dials + fallback reload retries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Deadline races hand back the abandoned operation task; the composite counts unresolved abandoned dials, pauses automatic retries above a small ceiling, and re-arms the retry loop when an abandoned dial finally resolves while still disconnected. A persistently wedged transport can no longer accumulate unbounded retained reconnect tasks. - The legacy fallback reload after a failed gap-repair fetch retries up to three times with short pauses instead of fire-and-forget, and reports exhaustion; connection-death cases remain owned by the recovery paths. Rejected (named boundary): moving MobileStateSyncHost off `shared` — the Mac mobile plane is currently rooted in TerminalController.shared / MobileHostService.shared at every call site, the host's epoch is process-lifetime by design, and the testable sync logic lives in the injected CMUXMobileCore classes; the injectable-owner move rides the de-singletonizing follow-up rather than this PR. Co-Authored-By: Claude Fable 5 --- ...ileShellComposite+ConnectionRecovery.swift | 57 ++++++++++++++++--- .../MobileShellComposite+StateSync.swift | 14 ++++- .../MobileShellComposite.swift | 4 ++ .../ReconnectAttemptDeadlineTests.swift | 10 ++-- 4 files changed, 73 insertions(+), 12 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index caf9d0057962..988578526b9e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -248,7 +248,7 @@ extension MobileShellComposite { // transient backoff owner schedules the next automatic try. let deadlineNanoseconds = self.runtime?.reconnectAttemptDeadlineNanoseconds ?? 30_000_000_000 - let reconnectOutcome = await Self.raceAgainstDeadline( + let race = await Self.raceAgainstDeadline( nanoseconds: deadlineNanoseconds ) { [weak self] in await self?.reconnectActiveMacOutcome( @@ -258,7 +258,7 @@ extension MobileShellComposite { } guard !Task.isCancelled, self.connectionRecoveryOwner.isCurrent(attempt) else { return } - guard let reconnectOutcome else { + guard let reconnectOutcome = race.value else { MobileDebugLog.anchormux( "connection.recovery redial deadline expired; abandoning attempt \(attempt.id.uuidString)" ) @@ -268,7 +268,13 @@ extension MobileShellComposite { self.macConnectionStatus = .unavailable self.clearRemoteConnectionContext() } - if let accountID = stackUserID ?? self.identityProvider?.currentUserID { + self.registerAbandonedReconnectDial(race.abandoned) + // Schedule the next automatic try only while the number of + // still-wedged abandoned dials is bounded; each dial that + // eventually resolves re-arms the retry itself. Manual, + // foreground, and network-change triggers are never gated. + if self.abandonedReconnectDialCount <= Self.maximumAbandonedReconnectDials, + let accountID = stackUserID ?? self.identityProvider?.currentUserID { self.recordTransientAutomaticReconnectBackoff(accountID: accountID) } self.applyConnectionRecoveryOwnerState() @@ -860,14 +866,47 @@ extension MobileShellComposite { /// one side resumes. An abandoned dial retains its captures until it /// eventually resolves — bounded by transport teardown and precisely the /// cost of not being wedged. + /// Ceiling on concurrently outstanding abandoned (wedged) dials before + /// automatic retries pause. A dial that resolves reclaims its slot and + /// re-arms the automatic retry when still disconnected. + static var maximumAbandonedReconnectDials: Int { 3 } + + /// Tracks an abandoned dial until it resolves, so a persistently wedged + /// transport cannot accumulate an unbounded set of retained reconnect + /// tasks across automatic retries. On resolution, if the shell is still + /// signed in and disconnected, the automatic retry loop is re-armed + /// (covers the case where retries were paused at the ceiling). + func registerAbandonedReconnectDial(_ task: Task?) { + guard let task else { return } + abandonedReconnectDialCount += 1 + Task { @MainActor [weak self] in + _ = await task.value + guard let self else { return } + self.abandonedReconnectDialCount = max(0, self.abandonedReconnectDialCount - 1) + guard self.isSignedIn, self.connectionState != .connected, + let accountID = self.identityProvider?.currentUserID else { return } + self.recordTransientAutomaticReconnectBackoff(accountID: accountID) + } + } + + /// The race result: `value` is nil when the deadline won, in which case + /// `abandoned` is the still-running operation task so the caller can + /// bound how many abandoned dials may exist at once and reclaim the slot + /// when the task eventually resolves. + struct DeadlineRaceOutcome: Sendable { + let value: Value? + let abandoned: Task? + } + static func raceAgainstDeadline( nanoseconds: UInt64, _ operation: @escaping @Sendable () async -> Value - ) async -> Value? { - await withCheckedContinuation { (continuation: CheckedContinuation) in + ) async -> DeadlineRaceOutcome { + let operationTask = Task { await operation() } + let value: Value? = await withCheckedContinuation { (continuation: CheckedContinuation) in let once = RaceContinuationOnce(continuation) - let operationTask = Task { - once.finish(await operation()) + Task { + once.finish(await operationTask.value) } Task { try? await Task.sleep(nanoseconds: nanoseconds) @@ -875,6 +914,10 @@ extension MobileShellComposite { once.finish(nil) } } + return DeadlineRaceOutcome( + value: value, + abandoned: value == nil ? operationTask : nil + ) } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index c2bc191fa579..ebb648f2bc5d 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -177,7 +177,19 @@ extension MobileShellComposite { guard stateSyncActive else { return } stateSyncActive = false Task { @MainActor [weak self] in - _ = await self?.reloadWorkspaceListFromMac() + // The missed delta may have been the last event, so this reload + // cannot be fire-and-forget: retry a bounded number of times with + // short pauses. If the connection itself is dead, the recovery + // owner (stream-end/liveness paths) takes over and a successful + // reconnect re-negotiates v2 with a snapshot anyway. + for attempt in 0..<3 { + guard let self, self.remoteClient === client, + self.connectionState == .connected, + !self.stateSyncActive else { return } + if await self.reloadWorkspaceListFromMac() { return } + try? await ContinuousClock().sleep(for: .seconds(2 << attempt)) + } + mobileStateSyncLog.error("legacy fallback reload exhausted retries; awaiting next event or recovery") } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 840464167b55..0ebad9fb6acb 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -781,6 +781,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// Identifies the fetch generation that owns ``stateSyncFetchTask``, so a /// cancelled predecessor's deferred cleanup cannot clear its replacement. var stateSyncFetchGeneration = UUID() + /// Number of deadline-abandoned reconnect dials that have not yet + /// resolved. Bounds automatic retry scheduling (see + /// ``registerAbandonedReconnectDial(_:)``). + var abandonedReconnectDialCount = 0 /// The user pull-to-refresh round-trip, kept on its own handle so the /// event-driven ``workspaceListRefreshTask`` cancel/restart can never truncate /// the spinner the pull is awaiting. Rapid pulls coalesce onto this single task. diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift index 4cd881bbb2d7..3610f66f71c9 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift @@ -16,21 +16,23 @@ extension ReconnectRouteSelectionTests { // The race must not structurally await the losing side: an operation // that never completes AND ignores cancellation (the wedged-FFI-dial // shape) must still let the deadline resolve the race. - let outcome: Int? = await MobileShellComposite.raceAgainstDeadline( + let outcome = await MobileShellComposite.raceAgainstDeadline( nanoseconds: 50_000_000 ) { await withCheckedContinuation { (_: CheckedContinuation) in // Parked forever; no cancellation handler on purpose. } } - #expect(outcome == nil) + #expect(outcome.value == nil) + #expect(outcome.abandoned != nil, "the wedged operation is handed back for bounded tracking") } @Test func deadlineRaceReturnsOperationValueWhenItWins() async { - let outcome: Int? = await MobileShellComposite.raceAgainstDeadline( + let outcome = await MobileShellComposite.raceAgainstDeadline( nanoseconds: 5_000_000_000 ) { 42 } - #expect(outcome == 42) + #expect(outcome.value == 42) + #expect(outcome.abandoned == nil) } @Test func hungRedialSettlesAtDeadlineAndUnfreezesRecovery() async throws { From d23a91394c3cd74661e414d16d7718ff3368e825 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 21:40:57 -0700 Subject: [PATCH 11/21] Address autoreview round 3: subscription-ack sequencing + refresh semantics - v2 negotiation now starts from the mobile.events.subscribe ACKNOWLEDGEMENT instead of racing the handshake, so a fetch snapshot can never miss a change emitted before the Mac registered this connection. - The watchdog's lost-registration recovery repairs the v2 cursor (missed events include missed deltas) instead of no-opping under v2. - The pull-to-refresh/Computers refresh path awaits the v2 cursor fetch and returns its outcome, so the spinner ends with authoritative state and a failed fetch is not reported as success. - Fetch failure handling is gated by owning generation + cancellation, so a cancelled predecessor surfacing as a timeout can no longer disable v2 underneath its successful replacement. Co-Authored-By: Claude Fable 5 --- ...ileShellComposite+ConnectionRecovery.swift | 18 +++---- .../MobileShellComposite+StateSync.swift | 48 ++++++++++++------- .../MobileShellComposite.swift | 29 +++++++---- 3 files changed, 62 insertions(+), 33 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 988578526b9e..68805955fe08 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -826,14 +826,16 @@ extension MobileShellComposite { let response = try MobileSyncWorkspaceListResponse.decode(data) guard remoteClient === client, connectionState == .connected else { return false } if stateSyncActive { - // The round-trip above already proved liveness, which is all - // this path's probe callers need. While state sync v2 owns the - // list, applying this legacy full response would overwrite - // mirror-projected state with a snapshot the next delta then - // contradicts; re-base the mirror through its cursor instead - // (the fetch also refreshes the Mac-side store from truth). - requestStateSyncFetch(client: client) - return true + // The round-trip above already proved liveness. While state + // sync v2 owns the list, applying this legacy full response + // would overwrite mirror-projected state with a snapshot the + // next delta then contradicts; re-base the mirror through its + // cursor instead (the fetch also refreshes the Mac-side store + // from truth). AWAITED, because pull-to-refresh and the + // Computers screen use this path's return as "refresh done": + // the spinner must not end before authoritative state applied, + // and a failed fetch must not report success. + return await performStateSyncFetch(client: client) } applyRemoteWorkspaceList(response, preferActiveTicketTarget: false) syncSelectedTerminalForWorkspace() diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index ebb648f2bc5d..f6d0f86ad4db 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -80,11 +80,18 @@ extension MobileShellComposite { } /// Entry point for sibling composite extensions (liveness probe and - /// pull-to-refresh paths): re-base the mirror through its cursor. + /// event-driven repair paths): re-base the mirror through its cursor. func requestStateSyncFetch(client: MobileCoreRPCClient) { scheduleStateSyncFetch(client: client) } + /// Awaitable variant for user-visible refresh gestures: the spinner must + /// not end before the authoritative fetch applied (or failed). Returns + /// whether the fetch applied cleanly. + func performStateSyncFetch(client: MobileCoreRPCClient) async -> Bool { + await scheduleStateSyncFetch(client: client).value + } + /// Repairs the mirror with a cursor fetch when the current client is v2. private func scheduleStateSyncRepairIfActive() { guard stateSyncActive, let client = remoteClient else { return } @@ -93,11 +100,12 @@ extension MobileShellComposite { /// Single-flight, restart-on-newest cursor fetch (negotiation and gap /// repair share it, mirroring ``workspaceListRefreshTask`` semantics). - private func scheduleStateSyncFetch(client: MobileCoreRPCClient) { + @discardableResult + private func scheduleStateSyncFetch(client: MobileCoreRPCClient) -> Task { stateSyncFetchTask?.cancel() let generation = UUID() stateSyncFetchGeneration = generation - stateSyncFetchTask = Task { @MainActor [weak self] in + let task = Task { @MainActor [weak self] () -> Bool in defer { // Only the generation that still owns the handle may clear // it: a cancelled predecessor's deferred cleanup must not @@ -106,23 +114,29 @@ extension MobileShellComposite { self.stateSyncFetchTask = nil } } - await self?.runStateSyncFetch(client: client) + return await self?.runStateSyncFetch(client: client, generation: generation) ?? false } + stateSyncFetchTask = task + return task } - private func runStateSyncFetch(client: MobileCoreRPCClient) async { + @discardableResult + private func runStateSyncFetch( + client: MobileCoreRPCClient, + generation: UUID + ) async -> Bool { // Currency check BEFORE the send, not only after: a negotiation task // scheduled for a listener generation that has since been replaced // must not touch its stale client at all — `sendRequest` on a // torn-down session would redial that client's route underneath the // replacement connection (an extra transport dial the reconnect // paths never asked for). - guard remoteClient === client, connectionState == .connected, !Task.isCancelled else { return } + guard remoteClient === client, connectionState == .connected, !Task.isCancelled else { return false } let params: [String: Any] do { params = try MobileSyncFrameJSON.jsonObject(from: stateSyncMirror.fetchRequest) } catch { - return + return false } do { let request = try MobileCoreRPCClient.requestData( @@ -133,7 +147,7 @@ extension MobileShellComposite { request, timeoutNanoseconds: runtime?.rpcRequestTimeoutNanoseconds ) - guard remoteClient === client, connectionState == .connected, !Task.isCancelled else { return } + guard remoteClient === client, connectionState == .connected, !Task.isCancelled else { return false } let response = try JSONDecoder().decode(MobileSyncFetchResponse.self, from: data) let result = stateSyncMirror.apply(response: response) stateSyncActive = true @@ -147,22 +161,24 @@ extension MobileShellComposite { // building the response's sections; one repair round covers it. scheduleStateSyncFetch(client: client) } - } catch let error as MobileShellConnectionError { - if case .rpcError(let code, _) = error, code == "method_not_found" { + return true + } catch { + // Failure handling belongs to the OWNING generation only: a + // cancelled predecessor's send can surface as a timeout after its + // replacement already succeeded, and acting on it would disable + // v2 underneath authoritative state. + guard !Task.isCancelled, stateSyncFetchGeneration == generation else { return false } + if case MobileShellConnectionError.rpcError(let code, _) = error, code == "method_not_found" { // Legacy Mac: stay on the workspace.updated refetch loop for // this connection. Not an error. stateSyncActive = false - return + return false } mobileStateSyncLog.error( "state sync fetch failed: \(String(describing: error), privacy: .private)" ) fallBackToLegacyListAfterFetchFailure(client: client) - } catch { - mobileStateSyncLog.error( - "state sync fetch failed: \(String(describing: error), privacy: .private)" - ) - fallBackToLegacyListAfterFetchFailure(client: client) + return false } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 0ebad9fb6acb..ece87899494c 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -776,8 +776,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// `mobile.sync.delta` events own the list. var stateSyncActive = false /// Single-flight handle for negotiation and gap-repair fetches, restart-on- - /// newest like ``workspaceListRefreshTask``. - var stateSyncFetchTask: Task? + /// newest like ``workspaceListRefreshTask``. Bool payload = fetch applied. + var stateSyncFetchTask: Task? /// Identifies the fetch generation that owns ``stateSyncFetchTask``, so a /// cancelled predecessor's deferred cleanup cannot clear its replacement. var stateSyncFetchGeneration = UUID() @@ -6727,12 +6727,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { topics: topics, transport: outputTransport ) - // Probe mobile state sync v2 concurrently with consumption, for the - // same reason as the subscribe handshake above: the fetch must not - // park the consumer loop. Subscribing before fetching means a delta - // racing the fetch either overlaps (idempotent) or gaps (repair - // fetch); no change can be silently lost in between. - self?.beginStateSyncNegotiation(client: client) // Keep the listener alive without keeping the shell store alive. for await event in stream { guard !Task.isCancelled else { return } @@ -6813,6 +6807,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { self.recordSuccessfulTerminalSubscription() self.markMacConnectionHealthy() MobileDebugLog.anchormux("sync.subscribe_ok topics=\(topics.count) transport=\(transport)") + // Negotiate state sync v2 only from the subscription + // ACKNOWLEDGEMENT: the ack proves the Mac registered this + // connection for `mobile.sync.delta`, so a fetch snapshot taken + // now cannot miss a change emitted between fetch and + // registration. (A fetch racing the handshake could snapshot rev + // N, miss N+1 emitted before the server registered us, and stay + // stale until the next unrelated change.) + self.beginStateSyncNegotiation(client: client) self.scheduleNotificationReconcile(client: client) } } @@ -7851,7 +7853,16 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // the `mobile.sync.delta` stream (the Mac emits both on the same tick // for old and new phones); the delta already carried the change, so the // full-list refetch this event used to trigger is pure amplification. - guard !stateSyncActive else { return } + // BUT callers also use this path for "events were missed" recovery + // (the watchdog's lost-registration branch): missed events include + // missed deltas, so under v2 the repair is a cursor fetch, never a + // silent no-op. + if stateSyncActive { + if let client = remoteClient { + requestStateSyncFetch(client: client) + } + return + } // Keep the event path's "latest event wins" semantics: a `workspace.updated` // arriving mid-fetch restarts the fetch so the applied list reflects the // change the Mac pushed *after* this fetch started. This cancels only the From 916fc4053133341960c8dc42483b652a5a79dc0b Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 21:49:19 -0700 Subject: [PATCH 12/21] Address autoreview round 4: register abandoned dials pre-guard, follow superseded fetches - The abandoned-dial handle is registered immediately after the race returns, before cancellation/supersession guards can drop it, so wedged dials from replaced attempts stay inside the accounting ceiling. - performStateSyncFetch follows cancel-and-replace supersessions (bounded) so a user refresh reports the authoritative replacement's outcome instead of a superseded cancel. Co-Authored-By: Claude Fable 5 --- ...bileShellComposite+ConnectionRecovery.swift | 7 ++++++- .../MobileShellComposite+StateSync.swift | 18 +++++++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 68805955fe08..c9efa7af81ff 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -256,6 +256,12 @@ extension MobileShellComposite { refreshBackupBeforeDial: false ) ?? .superseded } + // Account for a wedged dial BEFORE any currency guard: a + // cancelled or superseded attempt whose race still hit the + // deadline would otherwise drop the only handle to a task + // that keeps retaining the client and transport, bypassing + // the abandoned-dial ceiling. + self.registerAbandonedReconnectDial(race.abandoned) guard !Task.isCancelled, self.connectionRecoveryOwner.isCurrent(attempt) else { return } guard let reconnectOutcome = race.value else { @@ -268,7 +274,6 @@ extension MobileShellComposite { self.macConnectionStatus = .unavailable self.clearRemoteConnectionContext() } - self.registerAbandonedReconnectDial(race.abandoned) // Schedule the next automatic try only while the number of // still-wedged abandoned dials is bounded; each dial that // eventually resolves re-arms the retry itself. Manual, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index f6d0f86ad4db..2477eec6b64c 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -86,10 +86,22 @@ extension MobileShellComposite { } /// Awaitable variant for user-visible refresh gestures: the spinner must - /// not end before the authoritative fetch applied (or failed). Returns - /// whether the fetch applied cleanly. + /// not end before the authoritative fetch applied (or failed). The + /// single-flight slot is cancel-and-replace, so a delta-driven repair can + /// supersede this gesture's task mid-flight; in that case the replacement + /// is the authoritative fetch and the gesture follows it (bounded) rather + /// than reporting a superseded cancel as failure. func performStateSyncFetch(client: MobileCoreRPCClient) async -> Bool { - await scheduleStateSyncFetch(client: client).value + var task = scheduleStateSyncFetch(client: client) + for _ in 0..<5 { + let applied = await task.value + if applied { return true } + guard let replacement = stateSyncFetchTask, replacement != task else { + return applied + } + task = replacement + } + return false } /// Repairs the mirror with a cursor fetch when the current client is v2. From b29d7cf85aad9a4c04b46e3d8d0484e6e0479b36 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 22:05:32 -0700 Subject: [PATCH 13/21] Address autoreview round 5: partial-response guard, account-boundary reset, no legacy list under v2 - A fetch response missing a requested collection can no longer activate v2 or project an empty mirror over a valid list; it is treated as a fetch failure. - signOut tears down state sync: mirror wiped (previous account's titles, directories, previews), v2 deactivated, in-flight fetch invalidated by generation so late completions cannot write into the next session. - While v2 is active the legacy full-list request is never built or sent; the cursor fetch is both the liveness probe (caller timeout honored) and the authoritative refresh. Also widens a load-flaky poll window in the hung-redial test. Co-Authored-By: Claude Fable 5 --- ...ileShellComposite+ConnectionRecovery.swift | 21 ++++----- .../MobileShellComposite+StateSync.swift | 45 ++++++++++++++++--- .../MobileShellComposite.swift | 5 +++ .../ReconnectAttemptDeadlineTests.swift | 4 +- 4 files changed, 56 insertions(+), 19 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index c9efa7af81ff..af563ab49928 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -819,6 +819,15 @@ extension MobileShellComposite { timeoutNanoseconds: UInt64? = nil ) async -> Bool { guard let client = remoteClient else { return false } + // While state sync v2 owns the list, do not build/serialize/send the + // legacy full list at all (the Computers screen refreshes through here + // every 10s; paying the full-list cost and discarding it defeats the + // delta protocol). The cursor fetch is both the liveness probe and the + // authoritative refresh, AWAITED so pull-to-refresh cannot report done + // before state applied, with the caller's probe timeout honored. + if stateSyncActive { + return await performStateSyncFetch(client: client, timeoutNanoseconds: timeoutNanoseconds) + } do { let request = try MobileCoreRPCClient.requestData( method: "mobile.workspace.list", @@ -830,18 +839,6 @@ extension MobileShellComposite { ) let response = try MobileSyncWorkspaceListResponse.decode(data) guard remoteClient === client, connectionState == .connected else { return false } - if stateSyncActive { - // The round-trip above already proved liveness. While state - // sync v2 owns the list, applying this legacy full response - // would overwrite mirror-projected state with a snapshot the - // next delta then contradicts; re-base the mirror through its - // cursor instead (the fetch also refreshes the Mac-side store - // from truth). AWAITED, because pull-to-refresh and the - // Computers screen use this path's return as "refresh done": - // the spinner must not end before authoritative state applied, - // and a failed fetch must not report success. - return await performStateSyncFetch(client: client) - } applyRemoteWorkspaceList(response, preferActiveTicketTarget: false) syncSelectedTerminalForWorkspace() return true diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index 2477eec6b64c..2b1759ca293e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -91,8 +91,11 @@ extension MobileShellComposite { /// supersede this gesture's task mid-flight; in that case the replacement /// is the authoritative fetch and the gesture follows it (bounded) rather /// than reporting a superseded cancel as failure. - func performStateSyncFetch(client: MobileCoreRPCClient) async -> Bool { - var task = scheduleStateSyncFetch(client: client) + func performStateSyncFetch( + client: MobileCoreRPCClient, + timeoutNanoseconds: UInt64? = nil + ) async -> Bool { + var task = scheduleStateSyncFetch(client: client, timeoutNanoseconds: timeoutNanoseconds) for _ in 0..<5 { let applied = await task.value if applied { return true } @@ -104,6 +107,18 @@ extension MobileShellComposite { return false } + /// Account-boundary teardown: wipes mirrored records (titles, + /// directories, notification previews from the previous account's Macs), + /// deactivates v2, and invalidates any in-flight fetch so its completion + /// cannot write into the next account's session. + func resetStateSyncForAccountBoundary() { + stateSyncFetchTask?.cancel() + stateSyncFetchTask = nil + stateSyncFetchGeneration = UUID() + stateSyncActive = false + stateSyncMirror.reset() + } + /// Repairs the mirror with a cursor fetch when the current client is v2. private func scheduleStateSyncRepairIfActive() { guard stateSyncActive, let client = remoteClient else { return } @@ -113,7 +128,10 @@ extension MobileShellComposite { /// Single-flight, restart-on-newest cursor fetch (negotiation and gap /// repair share it, mirroring ``workspaceListRefreshTask`` semantics). @discardableResult - private func scheduleStateSyncFetch(client: MobileCoreRPCClient) -> Task { + private func scheduleStateSyncFetch( + client: MobileCoreRPCClient, + timeoutNanoseconds: UInt64? = nil + ) -> Task { stateSyncFetchTask?.cancel() let generation = UUID() stateSyncFetchGeneration = generation @@ -126,7 +144,11 @@ extension MobileShellComposite { self.stateSyncFetchTask = nil } } - return await self?.runStateSyncFetch(client: client, generation: generation) ?? false + return await self?.runStateSyncFetch( + client: client, + generation: generation, + timeoutNanoseconds: timeoutNanoseconds + ) ?? false } stateSyncFetchTask = task return task @@ -135,7 +157,8 @@ extension MobileShellComposite { @discardableResult private func runStateSyncFetch( client: MobileCoreRPCClient, - generation: UUID + generation: UUID, + timeoutNanoseconds: UInt64? = nil ) async -> Bool { // Currency check BEFORE the send, not only after: a negotiation task // scheduled for a listener generation that has since been replaced @@ -157,10 +180,20 @@ extension MobileShellComposite { ) let data = try await client.sendRequest( request, - timeoutNanoseconds: runtime?.rpcRequestTimeoutNanoseconds + timeoutNanoseconds: timeoutNanoseconds ?? runtime?.rpcRequestTimeoutNanoseconds ) guard remoteClient === client, connectionState == .connected, !Task.isCancelled else { return false } let response = try JSONDecoder().decode(MobileSyncFetchResponse.self, from: data) + // The response shape tolerates missing sections for forward + // compatibility, but v2 must never become authoritative on a + // partial answer: projecting an empty workspace mirror would + // clear a valid list. Both requested collections must be present. + guard response.workspaces != nil, response.groups != nil else { + guard !Task.isCancelled, stateSyncFetchGeneration == generation else { return false } + mobileStateSyncLog.error("state sync fetch returned a partial response; staying on legacy") + fallBackToLegacyListAfterFetchFailure(client: client) + return false + } let result = stateSyncMirror.apply(response: response) stateSyncActive = true switch result { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index ece87899494c..ce37648f565e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1178,6 +1178,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } suppressNextConnectionOutageEdge = true clearAutomaticReconnectBackoff() + // The state-sync mirror caches workspace/terminal titles, directories, + // and notification previews from the previous account's Macs; it must + // not survive an account boundary or leak into the next session's + // projections. + resetStateSyncForAccountBoundary() lastPresenceReconnectEvidence = nil connectionRecoveryOwner.cancel() applyConnectionRecoveryOwnerState() diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift index 3610f66f71c9..a7448642bb90 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift @@ -82,7 +82,9 @@ extension ReconnectRouteSelectionTests { factory.setHangingKinds([]) let dialsBeforeManual = factory.attemptedKinds().count await store.reconnectOrRefresh() - let reconnected = try await pollUntil { + // Generous window: this tail runs under full-suite parallel load and + // the manual path awaits several real round-trips. + let reconnected = try await pollUntil(attempts: 1500) { store.connectionState == .connected } #expect(reconnected, "manual retry after a settled deadline must reconnect") From f440923ef1bc8a2e6652adaecb6121558bf94cfe Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 10:51:39 -0700 Subject: [PATCH 14/21] Address autoreview round 6 + fix janitor re-block; harden deadline test - Ordinary workspace.updated events are suppressed under v2 (each pairs with a delta); only the watchdog's lost-registration branch repairs, through the dedicated repairMissedEventWindow (cursor fetch under v2, full refetch under legacy). Removes the per-event fetch RPC and the cancel-storm that could starve a genuine gap repair. - Abandoned-dial janitors no longer record transient backoff on resolution: that write could land mid-manual-retry and re-block the dial the user just requested. They now kick the coalesced recovery entry directly, only when no attempt or scheduled retry is active. (Found via deterministic full-suite reproduction of the hung-redial test.) - The hung-redial test releases parked dials when lifting the hang (eternal hangs were a test artifact racing auto-retry state) and uses starvation-proof poll windows. Full shell suite green 3x consecutively; the suite's residual flakiness on loaded machines reproduces on origin/main (6 issues/run) and predates this branch. Co-Authored-By: Claude Fable 5 --- ...ileShellComposite+ConnectionRecovery.swift | 10 ++++- .../MobileShellComposite+StateSync.swift | 1 + .../MobileShellComposite.swift | 38 ++++++++++++------- .../ReconnectAttemptDeadlineTests.swift | 19 ++++++++-- ...ReconnectRouteSelectionTests+Support.swift | 15 +++++++- 5 files changed, 62 insertions(+), 21 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index af563ab49928..6f2e8250bdaf 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -887,9 +887,15 @@ extension MobileShellComposite { _ = await task.value guard let self else { return } self.abandonedReconnectDialCount = max(0, self.abandonedReconnectDialCount - 1) + // Re-arm the retry loop directly through the coalesced recovery + // entry, NEVER by recording backoff: a backoff write here can land + // mid-manual-retry and re-block the dial the user just requested + // (manual retries clear backoff on entry). Skip when any attempt + // or scheduled retry is already active. guard self.isSignedIn, self.connectionState != .connected, - let accountID = self.identityProvider?.currentUserID else { return } - self.recordTransientAutomaticReconnectBackoff(accountID: accountID) + !self.connectionRecoveryOwner.isRedialingOrValidating, + self.automaticReconnectRetryTask == nil else { return } + self.recoverMobileConnection(trigger: .automaticBackoffExpired) } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index 2b1759ca293e..1ed31dc95336 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -85,6 +85,7 @@ extension MobileShellComposite { scheduleStateSyncFetch(client: client) } + /// Awaitable variant for user-visible refresh gestures: the spinner must /// not end before the authoritative fetch applied (or failed). The /// single-flight slot is cancel-and-replace, so a delta-driven repair can diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index ce37648f565e..e8d82e2512e1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -7022,10 +7022,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { reason: "liveness_probe_repaired" ) } - // The same registration carries `workspace.updated`, so - // workspace create/rename/delete events emitted during the - // gap were missed too; re-fetch the authoritative list. - self.scheduleWorkspaceListRefreshFromEvent() + // The same registration carries `workspace.updated` and + // `mobile.sync.delta`, so list changes emitted during the + // gap were missed too; repair through the mode-appropriate + // authoritative path. + self.repairMissedEventWindow() } else { MobileDebugLog.anchormux("sync.liveness probe_ok silentMs=\(Int(silent * 1000))") } @@ -7852,22 +7853,31 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { markTerminalBytesDelivered(surfaceID: surfaceID, endSeq: endSeq) } - private func scheduleWorkspaceListRefreshFromEvent() { - guard remoteClient != nil else { return } - // With state sync v2 negotiated, `workspace.updated` is redundant with - // the `mobile.sync.delta` stream (the Mac emits both on the same tick - // for old and new phones); the delta already carried the change, so the - // full-list refetch this event used to trigger is pure amplification. - // BUT callers also use this path for "events were missed" recovery - // (the watchdog's lost-registration branch): missed events include - // missed deltas, so under v2 the repair is a cursor fetch, never a - // silent no-op. + /// Dedicated missed-event-window repair (the watchdog's lost-registration + /// branch): events emitted while the host had dropped this connection's + /// registration were lost, deltas included. Under v2, repair is a cursor + /// fetch; under legacy it is the full-list refetch. Ordinary paired + /// `workspace.updated` events never route here. + func repairMissedEventWindow() { if stateSyncActive { if let client = remoteClient { requestStateSyncFetch(client: client) } return } + scheduleWorkspaceListRefreshFromEvent() + } + + private func scheduleWorkspaceListRefreshFromEvent() { + guard remoteClient != nil else { return } + // With state sync v2 negotiated, `workspace.updated` is redundant with + // the `mobile.sync.delta` stream (the Mac emits both on the same tick + // for old and new phones); the delta already carried the change, so + // fetching here would add a per-event RPC and Mac-side rebuild, and + // its cancel-and-replace slot could starve a genuine gap repair. + // "Events were missed" recovery has its own dedicated entry + // (``repairMissedEventWindow``); ordinary paired events stay silent. + guard !stateSyncActive else { return } // Keep the event path's "latest event wins" semantics: a `workspace.updated` // arriving mid-fetch restarts the fetch so the applied list reflects the // change the Mac pushed *after* this fetch started. This cancels only the diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift index a7448642bb90..8443e66a4e05 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift @@ -63,14 +63,21 @@ extension ReconnectRouteSelectionTests { store.recoverDeadConnection(trigger: .eventStreamEnded, expectedClient: client) + // Starvation-proof windows: under full-suite parallel load the + // recovery task may take seconds just to be scheduled (the suite is + // timing-flaky on loaded machines even on main). Generous polls cost + // time only on real failure. + let dialed = try await pollUntil(attempts: 3000) { + factory.attemptedKinds().count > dialsBeforeDrop + } + #expect(dialed, "the hung dial itself was attempted") // Pre-fix: the attempt never settles, isRedialingOrValidating stays // true forever, and this poll times out. Post-fix: the deadline // abandons the hung dial and settles the attempt as failed. - let settled = try await pollUntil { + let settled = try await pollUntil(attempts: 3000) { !store.connectionRecoveryOwner.isRedialingOrValidating } #expect(settled, "a hung dial must settle at the attempt deadline, not hold recovery forever") - #expect(factory.attemptedKinds().count > dialsBeforeDrop, "the hung dial itself was attempted") #expect(store.connectionState != .connected) // The timed-out attempt must feed the automatic retry loop: transient @@ -78,13 +85,17 @@ extension ReconnectRouteSelectionTests { #expect(store.automaticIrohReconnectIsBlocked(accountID: "user-1")) // And the machine is unfrozen: a manual retry (hang lifted, modeling - // the network recovering) dials fresh and connects. + // the network recovering) dials fresh and connects. Release the + // parked dials so abandoned attempts unwind the way real dials + // eventually do; an eternal hang is a test artifact that races the + // auto-retry loop's leftover state. factory.setHangingKinds([]) + await factory.releaseHangingTransports() let dialsBeforeManual = factory.attemptedKinds().count await store.reconnectOrRefresh() // Generous window: this tail runs under full-suite parallel load and // the manual path awaits several real round-trips. - let reconnected = try await pollUntil(attempts: 1500) { + let reconnected = try await pollUntil(attempts: 3000) { store.connectionState == .connected } #expect(reconnected, "manual retry after a settled deadline must reconnect") diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift index ef132dafdce3..ea01b5b9fa04 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift @@ -175,6 +175,7 @@ final class KindRecordingTransportFactory: CmxByteTransportFactory, @unchecked S private var kinds: [CmxAttachTransportKind] = [] private var authorizationModes: [CmxTransportAuthorizationMode] = [] private var hangingKinds: Set = [] + private var hangingTransports: [HangingConnectTransport] = [] /// Route kinds whose transports park forever in `connect()` from now on. /// Models an Iroh dial that neither completes nor fails (relay DNS churn, @@ -183,6 +184,16 @@ final class KindRecordingTransportFactory: CmxByteTransportFactory, @unchecked S lock.withLock { hangingKinds = kinds } } + /// Resolves every parked dial (models the network finally answering), + /// letting abandoned attempts unwind instead of retaining state forever. + func releaseHangingTransports() async { + let parked = lock.withLock { hangingTransports } + for transport in parked { + await transport.close() + } + lock.withLock { hangingTransports = [] } + } + init( router: LivenessHostRouter, box: TransportBox, @@ -215,7 +226,9 @@ final class KindRecordingTransportFactory: CmxByteTransportFactory, @unchecked S throw RouteRecordingTransportError.routeFailed } if lock.withLock({ hangingKinds.contains(route.kind) }) { - return HangingConnectTransport() + let transport = HangingConnectTransport() + lock.withLock { hangingTransports.append(transport) } + return transport } let transport = LivenessTransport(router: router) box.set(transport) From 364c651d7657438b8609b93b5bd1929109e0323f Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 11:07:02 -0700 Subject: [PATCH 15/21] Address autoreview round 7: scope state-sync authority to the owning client Replaces the bare stateSyncActive flag with stateSyncAuthorityClientID: v2 is active only while the client that earned authority (successful mobile.sync.fetch) IS the current remoteClient. This fixes the class the three findings shared: client promotion/replacement implicitly demotes to legacy (no suppressed-invalidation window on the new Mac), deltas are ignored outside the authoritative window (no legacy/v2 concurrent writers after a fallback), and a superseded fetch waiter consults the last settled generation's outcome (a liveness caller can no longer read a replacement's success as failure and tear down a healthy session). Regression test: replacingTheForegroundClientDemotesStateSyncAuthority. Co-Authored-By: Claude Fable 5 --- .../MobileShellComposite+StateSync.swift | 41 +++++++++++++++---- .../MobileShellComposite.swift | 21 ++++++++-- .../MobileShellStateSyncTests.swift | 24 +++++++++++ 3 files changed, 74 insertions(+), 12 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index 1ed31dc95336..b166c10ab79e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -22,7 +22,7 @@ extension MobileShellComposite { /// stream. Runs concurrently with event consumption; a delta racing the /// fetch overlaps idempotently or gaps into a repair fetch. func beginStateSyncNegotiation(client: MobileCoreRPCClient) { - stateSyncActive = false + stateSyncAuthorityClientID = nil scheduleStateSyncFetch(client: client) } @@ -30,6 +30,13 @@ extension MobileShellComposite { /// The caller already proved the event belongs to the current client and a /// connected session. func handleStateSyncDeltaEvent(_ event: MobileEventEnvelope) { + // Deltas are processed only while v2 is authoritative for the CURRENT + // client. Before activation the negotiation fetch covers them; after a + // legacy fallback the list has a legacy writer and mirror projections + // must stop until a new subscription generation renegotiates — + // otherwise legacy responses and v2 projections interleave as + // concurrent writers. + guard stateSyncActive else { return } guard let payload = event.payloadJSON else { scheduleStateSyncRepairIfActive() return @@ -97,13 +104,26 @@ extension MobileShellComposite { timeoutNanoseconds: UInt64? = nil ) async -> Bool { var task = scheduleStateSyncFetch(client: client, timeoutNanoseconds: timeoutNanoseconds) + var followedGeneration = stateSyncFetchGeneration for _ in 0..<5 { let applied = await task.value if applied { return true } - guard let replacement = stateSyncFetchTask, replacement != task else { - return applied + if let replacement = stateSyncFetchTask, replacement != task { + followedGeneration = stateSyncFetchGeneration + task = replacement + continue + } + // A finished replacement can clear the shared handle before this + // waiter's superseded task settles false. If a NEWER generation + // settled successfully, that outcome is the authoritative answer; + // reporting false here would let a liveness caller tear down a + // healthy session. + if let settled = stateSyncLastSettledFetch, + settled.generation != followedGeneration, + settled.applied { + return true } - task = replacement + return applied } return false } @@ -116,7 +136,8 @@ extension MobileShellComposite { stateSyncFetchTask?.cancel() stateSyncFetchTask = nil stateSyncFetchGeneration = UUID() - stateSyncActive = false + stateSyncAuthorityClientID = nil + stateSyncLastSettledFetch = nil stateSyncMirror.reset() } @@ -145,11 +166,13 @@ extension MobileShellComposite { self.stateSyncFetchTask = nil } } - return await self?.runStateSyncFetch( + let applied = await self?.runStateSyncFetch( client: client, generation: generation, timeoutNanoseconds: timeoutNanoseconds ) ?? false + self?.stateSyncLastSettledFetch = (generation, applied) + return applied } stateSyncFetchTask = task return task @@ -196,7 +219,7 @@ extension MobileShellComposite { return false } let result = stateSyncMirror.apply(response: response) - stateSyncActive = true + stateSyncAuthorityClientID = ObjectIdentifier(client) switch result { case .applied: applyStateSyncProjection() @@ -217,7 +240,7 @@ extension MobileShellComposite { if case MobileShellConnectionError.rpcError(let code, _) = error, code == "method_not_found" { // Legacy Mac: stay on the workspace.updated refetch loop for // this connection. Not an error. - stateSyncActive = false + stateSyncAuthorityClientID = nil return false } mobileStateSyncLog.error( @@ -237,7 +260,7 @@ extension MobileShellComposite { private func fallBackToLegacyListAfterFetchFailure(client: MobileCoreRPCClient) { guard remoteClient === client, connectionState == .connected else { return } guard stateSyncActive else { return } - stateSyncActive = false + stateSyncAuthorityClientID = nil Task { @MainActor [weak self] in // The missed delta may have been the last event, so this reload // cannot be fire-and-forget: retry a bounded number of times with diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index e8d82e2512e1..ef83c7c8502d 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -771,10 +771,25 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// Never reset on reconnect; the epoch in every frame invalidates stale /// cursors, so a same-Mac resubscribe catches up with one small delta. let stateSyncMirror = MobileStateSyncMirror() - /// Whether the connected Mac answered `mobile.sync.fetch` this connection. - /// While true, `workspace.updated` no longer schedules full-list refetches; + /// The client that earned state-sync authority by a successful + /// `mobile.sync.fetch`. v2 is active only while this identity matches the + /// CURRENT `remoteClient`, so replacing the client (secondary-to- + /// foreground promotion, reconnect) implicitly demotes to legacy until + /// the new client's own negotiation completes — no explicit hook needed, + /// and a stale client's deltas or fallbacks can never act on its + /// successor's authority. + var stateSyncAuthorityClientID: ObjectIdentifier? + /// Whether state sync v2 owns the list for the CURRENT client. While + /// true, `workspace.updated` no longer schedules full-list refetches; /// `mobile.sync.delta` events own the list. - var stateSyncActive = false + var stateSyncActive: Bool { + guard let stateSyncAuthorityClientID, let remoteClient else { return false } + return stateSyncAuthorityClientID == ObjectIdentifier(remoteClient) + } + /// Outcome of the most recently settled fetch generation, so a waiter + /// whose superseded task lost the race to its finished replacement can + /// still observe that authoritative success. + var stateSyncLastSettledFetch: (generation: UUID, applied: Bool)? /// Single-flight handle for negotiation and gap-repair fetches, restart-on- /// newest like ``workspaceListRefreshTask``. Bool payload = fetch applied. var stateSyncFetchTask: Task? diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift index 8676b8e095f7..fcd7dd751f93 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift @@ -212,6 +212,30 @@ struct MobileShellStateSyncTests { #expect(reloaded, "the fallback must converge with one authoritative legacy reload") } + @Test func replacingTheForegroundClientDemotesStateSyncAuthority() async throws { + let router = LivenessHostRouter() + await router.scriptSyncFetchResult( + jsonData: try syncSnapshotResultData( + epoch: "epoch-1", + rev: 3, + records: [workspaceRecord(id: UUID().uuidString, title: "synced-alpha", sortIndex: 0)] + ) + ) + let box = TransportBox() + let clock = TestClock() + let store = try await makeConnectedStore(router: router, box: box, clock: clock) + let negotiated = try await pollUntil { store.stateSyncActive } + #expect(negotiated) + + // Promoting/replacing the foreground client (secondary-to-foreground, + // reconnect) must implicitly demote v2: the new client's events flow + // through the legacy invalidation path until ITS negotiation grants + // authority, so no window exists where the old Mac's authority + // suppresses the new Mac's updates. + try installFreshLivenessRemoteClient(on: store, router: router, box: box, clock: clock) + #expect(store.stateSyncActive == false) + } + @Test func legacyMacKeepsWorkspaceUpdatedRefetchLoop() async throws { // No scripted sync result: the router answers `method_not_found`, // modeling a released Mac. From b64707c37000d96b5ba5974eaf41c6c8ea6eeec5 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 11:26:33 -0700 Subject: [PATCH 16/21] Address autoreview round 8: single-flight fetch runner with trailing sweep Replaces the fetch slot's cancel-and-replace semantics with the codebase's proven single-flight + follow-up pattern (same shape as scheduleSecondaryRefresh): same-client demand coalesces onto the in-flight runner and requests one trailing sweep; only a different client's demand replaces the runner. This resolves the round-8 class at its root: - gap repairs can no longer be starved by sustained 80ms churn (deltas coalesce instead of cancelling the repair they need); - negotiation-window deltas request a trailing sweep instead of being dropped (a change postdating the fetch snapshot is swept, not lost); - no concurrent fetch generations exist, so a superseded task can neither misreport nor overwrite a replacement's success (the settled-outcome bookkeeping is deleted, not patched). Co-Authored-By: Claude Fable 5 --- .../MobileShellComposite+StateSync.swift | 95 ++++++++++--------- .../MobileShellComposite.swift | 10 +- 2 files changed, 57 insertions(+), 48 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index b166c10ab79e..f855e44f8cc1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -30,13 +30,19 @@ extension MobileShellComposite { /// The caller already proved the event belongs to the current client and a /// connected session. func handleStateSyncDeltaEvent(_ event: MobileEventEnvelope) { - // Deltas are processed only while v2 is authoritative for the CURRENT - // client. Before activation the negotiation fetch covers them; after a - // legacy fallback the list has a legacy writer and mirror projections - // must stop until a new subscription generation renegotiates — - // otherwise legacy responses and v2 projections interleave as - // concurrent writers. - guard stateSyncActive else { return } + // Deltas apply only while v2 is authoritative for the CURRENT client + // (after a legacy fallback the list has a legacy writer, and mirror + // projections must stop until renegotiation). During NEGOTIATION — + // fetch runner in flight for this client — a delta may postdate the + // fetch's snapshot, so it requests one trailing sweep instead of + // being dropped or applied to a non-authoritative mirror. + guard stateSyncActive else { + if stateSyncFetchTask != nil, let client = remoteClient, + stateSyncFetchClientID == ObjectIdentifier(client) { + stateSyncFetchFollowUpRequested = true + } + return + } guard let payload = event.payloadJSON else { scheduleStateSyncRepairIfActive() return @@ -103,29 +109,12 @@ extension MobileShellComposite { client: MobileCoreRPCClient, timeoutNanoseconds: UInt64? = nil ) async -> Bool { - var task = scheduleStateSyncFetch(client: client, timeoutNanoseconds: timeoutNanoseconds) - var followedGeneration = stateSyncFetchGeneration - for _ in 0..<5 { - let applied = await task.value - if applied { return true } - if let replacement = stateSyncFetchTask, replacement != task { - followedGeneration = stateSyncFetchGeneration - task = replacement - continue - } - // A finished replacement can clear the shared handle before this - // waiter's superseded task settles false. If a NEWER generation - // settled successfully, that outcome is the authoritative answer; - // reporting false here would let a liveness caller tear down a - // healthy session. - if let settled = stateSyncLastSettledFetch, - settled.generation != followedGeneration, - settled.applied { - return true - } - return applied - } - return false + // Single-flight: same-client demand coalesces onto the in-flight + // runner, so awaiting the returned task IS awaiting the authoritative + // outcome (a trailing follow-up sweep runs inside the same task). The + // runner is cancelled only on client change or account teardown, where + // false is the correct answer for this client's gesture. + await scheduleStateSyncFetch(client: client, timeoutNanoseconds: timeoutNanoseconds).value } /// Account-boundary teardown: wipes mirrored records (titles, @@ -137,7 +126,8 @@ extension MobileShellComposite { stateSyncFetchTask = nil stateSyncFetchGeneration = UUID() stateSyncAuthorityClientID = nil - stateSyncLastSettledFetch = nil + stateSyncFetchClientID = nil + stateSyncFetchFollowUpRequested = false stateSyncMirror.reset() } @@ -154,24 +144,41 @@ extension MobileShellComposite { client: MobileCoreRPCClient, timeoutNanoseconds: UInt64? = nil ) -> Task { + // Single-flight per client: new demand while a runner is in flight + // requests one trailing sweep and attaches to the runner. Cancelling + // in-flight repairs on every demand starves convergence under + // sustained 80ms churn (each gap-path delta would kill the repair it + // needs); only a DIFFERENT client's demand replaces the runner. + if let running = stateSyncFetchTask, + stateSyncFetchClientID == ObjectIdentifier(client) { + stateSyncFetchFollowUpRequested = true + return running + } stateSyncFetchTask?.cancel() let generation = UUID() stateSyncFetchGeneration = generation + stateSyncFetchClientID = ObjectIdentifier(client) + stateSyncFetchFollowUpRequested = false let task = Task { @MainActor [weak self] () -> Bool in - defer { - // Only the generation that still owns the handle may clear - // it: a cancelled predecessor's deferred cleanup must not - // erase the replacement's cancel handle. - if let self, self.stateSyncFetchGeneration == generation { - self.stateSyncFetchTask = nil - } + var applied = false + while true { + guard let self, !Task.isCancelled, + self.stateSyncFetchGeneration == generation else { return applied } + self.stateSyncFetchFollowUpRequested = false + applied = await self.runStateSyncFetch( + client: client, + generation: generation, + timeoutNanoseconds: timeoutNanoseconds + ) + // One trailing sweep per follow-up request; a failed fetch + // does not loop (the fallback path owns failure recovery). + guard applied, self.stateSyncFetchGeneration == generation, + self.stateSyncFetchFollowUpRequested, !Task.isCancelled else { break } + } + if let self, self.stateSyncFetchGeneration == generation { + self.stateSyncFetchTask = nil + self.stateSyncFetchClientID = nil } - let applied = await self?.runStateSyncFetch( - client: client, - generation: generation, - timeoutNanoseconds: timeoutNanoseconds - ) ?? false - self?.stateSyncLastSettledFetch = (generation, applied) return applied } stateSyncFetchTask = task diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index ef83c7c8502d..5db622b91317 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -786,10 +786,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard let stateSyncAuthorityClientID, let remoteClient else { return false } return stateSyncAuthorityClientID == ObjectIdentifier(remoteClient) } - /// Outcome of the most recently settled fetch generation, so a waiter - /// whose superseded task lost the race to its finished replacement can - /// still observe that authoritative success. - var stateSyncLastSettledFetch: (generation: UUID, applied: Bool)? + /// Identity of the client the in-flight fetch runner serves; demand for + /// the same client coalesces onto the runner instead of cancelling it. + var stateSyncFetchClientID: ObjectIdentifier? + /// Set while a runner is in flight to request one trailing sweep after it + /// settles (a delta arrived that the current fetch's snapshot may miss). + var stateSyncFetchFollowUpRequested = false /// Single-flight handle for negotiation and gap-repair fetches, restart-on- /// newest like ``workspaceListRefreshTask``. Bool payload = fetch applied. var stateSyncFetchTask: Task? From cdc246789c493609817f4e5f7215c62595609da2 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 11:44:16 -0700 Subject: [PATCH 17/21] Address autoreview round 9: bound every reconnect caller; per-waiter fetch deadlines - The per-attempt deadline and abandoned-dial accounting move inside reconnectActiveMacOutcome itself, so startup restore, team-scope restore, and the manual workspace-list fallback are bounded identically to the recovery owner (whose special-case deadline branch is deleted). The raw dial is reconnectActiveMacOutcomeUnbounded. - performStateSyncFetch bounds each WAITER by its own timeout when one is provided (a 3s liveness probe joining a slow fetch reports within its contract); the shared runner is never cancelled by a waiter's deadline and keeps converging in the background. Co-Authored-By: Claude Fable 5 --- ...ileShellComposite+ConnectionRecovery.swift | 59 +++---------------- .../MobileShellComposite+StateSync.swift | 14 ++++- .../MobileShellComposite.swift | 26 ++++++++ 3 files changed, 47 insertions(+), 52 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 6f2e8250bdaf..831aa724b755 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -232,59 +232,16 @@ extension MobileShellComposite { // Recovery uses authenticated local Iroh state first. A stuck // account-backup fetch must not block a known EndpointID from - // dialing; normal launch reconnect still refreshes first. - // - // The redial runs under a hard deadline. An Iroh dial can hang - // far past any per-transport connect timeout (observed: relay - // DNS churn for 15+ minutes), and while this attempt is - // in-flight the recovery owner defers every other trigger, so - // one hung dial used to freeze the entire recovery machine - // with no failure, no backoff retry, and a permanent - // "Disconnected - Tap Reconnect" dead end - // (https://github.com/manaflow-ai/cmux/issues/8531). At the - // deadline the attempt is abandoned (generation guards make a - // late completion harmless: a late success just connects, a - // late failure finds the attempt already settled) and the - // transient backoff owner schedules the next automatic try. - let deadlineNanoseconds = self.runtime?.reconnectAttemptDeadlineNanoseconds - ?? 30_000_000_000 - let race = await Self.raceAgainstDeadline( - nanoseconds: deadlineNanoseconds - ) { [weak self] in - await self?.reconnectActiveMacOutcome( - stackUserID: stackUserID, - refreshBackupBeforeDial: false - ) ?? .superseded - } - // Account for a wedged dial BEFORE any currency guard: a - // cancelled or superseded attempt whose race still hit the - // deadline would otherwise drop the only handle to a task - // that keeps retaining the client and transport, bypassing - // the abandoned-dial ceiling. - self.registerAbandonedReconnectDial(race.abandoned) + // dialing; normal launch reconnect still refreshes first. The + // per-attempt deadline and abandoned-dial accounting live + // inside reconnectActiveMacOutcome, shared by every caller + // (https://github.com/manaflow-ai/cmux/issues/8531). + let reconnectOutcome = await self.reconnectActiveMacOutcome( + stackUserID: stackUserID, + refreshBackupBeforeDial: false + ) guard !Task.isCancelled, self.connectionRecoveryOwner.isCurrent(attempt) else { return } - guard let reconnectOutcome = race.value else { - MobileDebugLog.anchormux( - "connection.recovery redial deadline expired; abandoning attempt \(attempt.id.uuidString)" - ) - guard self.failConnectionRecovery(attempt, failure: .timedOut) else { return } - if self.connectionState == .connected { - self.connectionState = .disconnected - self.macConnectionStatus = .unavailable - self.clearRemoteConnectionContext() - } - // Schedule the next automatic try only while the number of - // still-wedged abandoned dials is bounded; each dial that - // eventually resolves re-arms the retry itself. Manual, - // foreground, and network-change triggers are never gated. - if self.abandonedReconnectDialCount <= Self.maximumAbandonedReconnectDials, - let accountID = stackUserID ?? self.identityProvider?.currentUserID { - self.recordTransientAutomaticReconnectBackoff(accountID: accountID) - } - self.applyConnectionRecoveryOwnerState() - return - } guard self.settleConnectionRecovery( attempt, outcome: reconnectOutcome, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index f855e44f8cc1..7fd36a1ba4c2 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -114,7 +114,19 @@ extension MobileShellComposite { // outcome (a trailing follow-up sweep runs inside the same task). The // runner is cancelled only on client change or account teardown, where // false is the correct answer for this client's gesture. - await scheduleStateSyncFetch(client: client, timeoutNanoseconds: timeoutNanoseconds).value + // + // Each WAITER is bounded by its own deadline: a 3s liveness probe + // joining a slow 30s fetch must report within its contract, not the + // runner's. The runner itself is never cancelled by a waiter's + // deadline; it keeps converging in the background. + let task = scheduleStateSyncFetch(client: client, timeoutNanoseconds: timeoutNanoseconds) + guard let timeoutNanoseconds else { + return await task.value + } + let race = await Self.raceAgainstDeadline(nanoseconds: timeoutNanoseconds) { + await task.value + } + return race.value ?? false } /// Account-boundary teardown: wipes mirrored records (titles, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 5db622b91317..a2efb53f2bfb 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1777,9 +1777,35 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { )).didConnect } + /// Bounded stored-Mac reconnect: EVERY caller (recovery owner, startup + /// restore, team-scope restore, manual fallback) gets the per-attempt + /// deadline, so a cancellation-ignoring dial can wedge none of them. On + /// expiry the dial is abandoned into the bounded accounting and transient + /// backoff arms the automatic retry loop. func reconnectActiveMacOutcome( stackUserID: String?, refreshBackupBeforeDial: Bool = true + ) async -> StoredMacReconnectOutcome { + let deadline = runtime?.reconnectAttemptDeadlineNanoseconds ?? 30_000_000_000 + let race = await Self.raceAgainstDeadline(nanoseconds: deadline) { [weak self] in + await self?.reconnectActiveMacOutcomeUnbounded( + stackUserID: stackUserID, + refreshBackupBeforeDial: refreshBackupBeforeDial + ) ?? .superseded + } + if let outcome = race.value { return outcome } + MobileDebugLog.anchormux("reconnect dial deadline expired; abandoning attempt") + registerAbandonedReconnectDial(race.abandoned) + if abandonedReconnectDialCount <= Self.maximumAbandonedReconnectDials, + let accountID = stackUserID ?? identityProvider?.currentUserID { + recordTransientAutomaticReconnectBackoff(accountID: accountID) + } + return .failed(.timedOut) + } + + func reconnectActiveMacOutcomeUnbounded( + stackUserID: String?, + refreshBackupBeforeDial: Bool = true ) async -> StoredMacReconnectOutcome { lastReconnectStackUserID = stackUserID startObservingNetworkPathChanges() From d437edb027b45951055362c696e8dcc82858eac6 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 11:56:00 -0700 Subject: [PATCH 18/21] Revert blanket reconnect deadline wrapper; keep waiter bounds + cancel forwarding The round-9 blanket wrapper detached every reconnect's synchronous prefix, breaking reconnect serialization semantics (registry-snapshot reuse and initial-connect tests). The per-attempt deadline returns to the recovery owner path (round-8 shape, proven 3x-green); bounding the remaining lifecycle callers (startup restore, team restore, manual fallback) is a consciously deferred follow-up needing per-call-site deadline policy. Kept from round 9: per-waiter timeout bounds on coalesced state-sync fetches, and explicit caller-cancellation forwarding in raceAgainstDeadline. Co-Authored-By: Claude Fable 5 --- ...ileShellComposite+ConnectionRecovery.swift | 83 +++++++++++++++---- .../MobileShellComposite.swift | 26 ------ 2 files changed, 66 insertions(+), 43 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 831aa724b755..e2753ceab6bb 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -232,16 +232,56 @@ extension MobileShellComposite { // Recovery uses authenticated local Iroh state first. A stuck // account-backup fetch must not block a known EndpointID from - // dialing; normal launch reconnect still refreshes first. The - // per-attempt deadline and abandoned-dial accounting live - // inside reconnectActiveMacOutcome, shared by every caller - // (https://github.com/manaflow-ai/cmux/issues/8531). - let reconnectOutcome = await self.reconnectActiveMacOutcome( - stackUserID: stackUserID, - refreshBackupBeforeDial: false - ) + // dialing; normal launch reconnect still refreshes first. + // + // The redial runs under a hard deadline: while an attempt is + // in flight the recovery owner defers every other trigger, so + // one hung dial would otherwise freeze the recovery machine + // (https://github.com/manaflow-ai/cmux/issues/8531). The + // deadline is applied HERE, not inside the shared reconnect + // entry, because a blanket detached wrapper severs the dial's + // synchronous prefix and breaks reconnect serialization for + // lifecycle callers; bounding those callers is tracked as a + // follow-up. + let deadlineNanoseconds = self.runtime?.reconnectAttemptDeadlineNanoseconds + ?? 30_000_000_000 + let race = await Self.raceAgainstDeadline( + nanoseconds: deadlineNanoseconds + ) { [weak self] in + await self?.reconnectActiveMacOutcome( + stackUserID: stackUserID, + refreshBackupBeforeDial: false + ) ?? .superseded + } + // Account for a wedged dial BEFORE any currency guard: a + // cancelled or superseded attempt whose race still hit the + // deadline would otherwise drop the only handle to a task + // that keeps retaining the client and transport, bypassing + // the abandoned-dial ceiling. + self.registerAbandonedReconnectDial(race.abandoned) guard !Task.isCancelled, self.connectionRecoveryOwner.isCurrent(attempt) else { return } + guard let reconnectOutcome = race.value else { + MobileDebugLog.anchormux( + "connection.recovery redial deadline expired; abandoning attempt \(attempt.id.uuidString)" + ) + guard self.failConnectionRecovery(attempt, failure: .timedOut) else { return } + if self.connectionState == .connected { + self.connectionState = .disconnected + self.macConnectionStatus = .unavailable + self.clearRemoteConnectionContext() + } + // Schedule the next automatic try only while the number of + // still-wedged abandoned dials is bounded; each dial that + // eventually resolves re-arms the retry itself. Manual, + // foreground, and network-change triggers are never gated. + if self.abandonedReconnectDialCount <= Self.maximumAbandonedReconnectDials, + let accountID = stackUserID ?? self.identityProvider?.currentUserID { + self.recordTransientAutomaticReconnectBackoff(accountID: accountID) + } + self.applyConnectionRecoveryOwnerState() + return + } guard self.settleConnectionRecovery( attempt, outcome: reconnectOutcome, @@ -870,16 +910,25 @@ extension MobileShellComposite { _ operation: @escaping @Sendable () async -> Value ) async -> DeadlineRaceOutcome { let operationTask = Task { await operation() } - let value: Value? = await withCheckedContinuation { (continuation: CheckedContinuation) in - let once = RaceContinuationOnce(continuation) - Task { - once.finish(await operationTask.value) - } - Task { - try? await Task.sleep(nanoseconds: nanoseconds) - operationTask.cancel() - once.finish(nil) + // The operation runs unstructured (so a cancellation-ignoring dial + // cannot park the race past its deadline), which severs implicit + // cancellation inheritance — forward the caller's cancellation + // explicitly so a superseded recovery attempt still aborts a + // well-behaved dial immediately. + let value: Value? = await withTaskCancellationHandler { + await withCheckedContinuation { (continuation: CheckedContinuation) in + let once = RaceContinuationOnce(continuation) + Task { + once.finish(await operationTask.value) + } + Task { + try? await Task.sleep(nanoseconds: nanoseconds) + operationTask.cancel() + once.finish(nil) + } } + } onCancel: { + operationTask.cancel() } return DeadlineRaceOutcome( value: value, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index a2efb53f2bfb..5db622b91317 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1777,35 +1777,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { )).didConnect } - /// Bounded stored-Mac reconnect: EVERY caller (recovery owner, startup - /// restore, team-scope restore, manual fallback) gets the per-attempt - /// deadline, so a cancellation-ignoring dial can wedge none of them. On - /// expiry the dial is abandoned into the bounded accounting and transient - /// backoff arms the automatic retry loop. func reconnectActiveMacOutcome( stackUserID: String?, refreshBackupBeforeDial: Bool = true - ) async -> StoredMacReconnectOutcome { - let deadline = runtime?.reconnectAttemptDeadlineNanoseconds ?? 30_000_000_000 - let race = await Self.raceAgainstDeadline(nanoseconds: deadline) { [weak self] in - await self?.reconnectActiveMacOutcomeUnbounded( - stackUserID: stackUserID, - refreshBackupBeforeDial: refreshBackupBeforeDial - ) ?? .superseded - } - if let outcome = race.value { return outcome } - MobileDebugLog.anchormux("reconnect dial deadline expired; abandoning attempt") - registerAbandonedReconnectDial(race.abandoned) - if abandonedReconnectDialCount <= Self.maximumAbandonedReconnectDials, - let accountID = stackUserID ?? identityProvider?.currentUserID { - recordTransientAutomaticReconnectBackoff(accountID: accountID) - } - return .failed(.timedOut) - } - - func reconnectActiveMacOutcomeUnbounded( - stackUserID: String?, - refreshBackupBeforeDial: Bool = true ) async -> StoredMacReconnectOutcome { lastReconnectStackUserID = stackUserID startObservingNetworkPathChanges() From 3983726bb5048467b9ab88aff6ed6e6f3a2cea76 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 12:23:53 -0700 Subject: [PATCH 19/21] Policy pass: DocC all public sync symbols, injectable frame coder, clock deadline - Every public symbol in the state-sync package surface carries DocC. - MobileSyncFrameJSON (caseless namespace enum) becomes the injectable MobileSyncFrameCoder instance type; error renamed accordingly. - The deadline race's timer uses ContinuousClock (intentional bounded deadline, cancellation-wired). Remaining P2 policy findings are rejected with named boundaries recorded on the PR: the protocol files each own a closed set of tightly coupled wire DTOs; DeadlineRaceOutcome/RaceContinuationOnce are private helpers co-located with their sole consumer; the once-guard must be callable from the synchronous onCancel handler, which an actor cannot be; the static race helper lives on a heavily stateful owning type, not a namespace. Co-Authored-By: Claude Fable 5 --- .../MobileStateSyncFrames.swift | 49 ++++++++++++++++--- .../MobileStateSyncMirror.swift | 7 +++ .../MobileStateSyncRecords.swift | 33 +++++++++++++ .../CMUXMobileCore/MobileStateSyncStore.swift | 11 +++++ .../MobileStateSyncFrameCodingTests.swift | 18 +++---- .../MobileSyncWorkspaceListResponse.swift | 2 + .../MobileCoreRPCIndependentEventTests.swift | 2 +- ...ileShellComposite+ConnectionRecovery.swift | 6 ++- .../MobileShellComposite+StateSync.swift | 2 +- .../MobileShellStateSyncTests.swift | 2 +- Sources/Mobile/MobileStateSync.swift | 6 +-- 11 files changed, 115 insertions(+), 23 deletions(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift index 22807f3682e4..642cae3d84cd 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift @@ -4,9 +4,12 @@ import Foundation /// while the Mac's `epoch` is unchanged; a cursor from another epoch always /// resolves to a snapshot. public struct MobileSyncCursor: Codable, Equatable, Sendable { + /// The store epoch this revision belongs to. public let epoch: String + /// The last revision the client applied within that epoch. public let rev: UInt64 + /// Creates a cursor from its epoch and revision. public init(epoch: String, rev: UInt64) { self.epoch = epoch self.rev = rev @@ -24,14 +27,18 @@ public enum MobileSyncPayloadMode: String, Codable, Sendable { /// One collection section of a `mobile.sync.fetch` response. public struct MobileSyncCollectionPayload: Codable, Equatable, Sendable { + /// How this section carries its records (snapshot or delta). public let mode: MobileSyncPayloadMode /// Head revision the payload brings the client to. public let rev: UInt64 /// The client revision this delta starts from. Absent for snapshots. public let fromRev: UInt64? + /// Changed (delta) or complete (snapshot) rows. public let records: [Record] + /// Ids removed within the delta span. Empty for snapshots. public let removedIDs: [String] + /// Creates one fetch-response section. public init( mode: MobileSyncPayloadMode, rev: UInt64, @@ -58,11 +65,16 @@ public struct MobileSyncCollectionPayload: Codable, Eq /// The `mobile.sync.fetch` request body: one cursor entry per collection the /// client wants. A missing cursor means cold start (snapshot). public struct MobileSyncFetchRequest: Codable, Equatable, Sendable { + /// One requested collection with the client's cursor, when it has one. public struct Collection: Codable, Equatable, Sendable { + /// The collection being requested. public let id: MobileSyncCollectionID + /// The cursor's epoch; absent on cold start. public let epoch: String? + /// The cursor's revision; absent on cold start. public let rev: UInt64? + /// Creates one request entry. public init(id: MobileSyncCollectionID, epoch: String?, rev: UInt64?) { self.id = id self.epoch = epoch @@ -76,8 +88,10 @@ public struct MobileSyncFetchRequest: Codable, Equatable, Sendable { } } + /// The collections the client wants brought current. public let collections: [Collection] + /// Creates a fetch request. public init(collections: [Collection]) { self.collections = collections } @@ -87,10 +101,14 @@ public struct MobileSyncFetchRequest: Codable, Equatable, Sendable { /// can grow collections without breaking older peers; a client ignores /// sections it did not request and tolerates missing ones. public struct MobileSyncFetchResponse: Codable, Equatable, Sendable { + /// The store's current epoch; cursors are only meaningful within it. public let epoch: String + /// The workspaces section, when requested. public let workspaces: MobileSyncCollectionPayload? + /// The groups section, when requested. public let groups: MobileSyncCollectionPayload? + /// Creates a fetch response. public init( epoch: String, workspaces: MobileSyncCollectionPayload?, @@ -107,13 +125,20 @@ public struct MobileSyncFetchResponse: Codable, Equatable, Sendable { /// (idempotent overlap); `from_rev > local rev` is a gap the client repairs /// with a cursor fetch. public struct MobileSyncDeltaEvent: Codable, Equatable, Sendable { + /// The store epoch the revisions belong to. public let epoch: String + /// The collection this delta mutates. public let collection: MobileSyncCollectionID + /// The head revision before this tick. public let fromRev: UInt64 + /// The head revision after this tick. public let toRev: UInt64 + /// Full rows changed in this tick. public let records: [Record] + /// Ids removed in this tick. public let removedIDs: [String] + /// Creates one delta event. public init( epoch: String, collection: MobileSyncCollectionID, @@ -143,8 +168,10 @@ public struct MobileSyncDeltaEvent: Codable, Equatable /// Collection discriminator decoded before choosing the typed /// `MobileSyncDeltaEvent` record type for a `mobile.sync.delta` payload. public struct MobileSyncDeltaEventHeader: Codable, Equatable, Sendable { + /// The collection the enclosing delta event mutates. public let collection: MobileSyncCollectionID + /// Creates a header (primarily for tests; production decodes it). public init(collection: MobileSyncCollectionID) { self.collection = collection } @@ -153,17 +180,23 @@ public struct MobileSyncDeltaEventHeader: Codable, Equatable, Sendable { /// JSON bridging between the typed frames and the `[String: Any]` payloads the /// mobile RPC envelope carries. One round-trip through `JSONSerialization` per /// frame; frames are small (changed rows only), so this stays off every hot -/// path that matters. -public enum MobileSyncFrameJSON { - public static func jsonObject(from value: some Encodable) throws -> [String: Any] { +/// path that matters. An instance type (not a namespace) so call sites can +/// hold and inject it. +public struct MobileSyncFrameCoder: Sendable { + /// Creates a coder with the standard JSON strategies. + public init() {} + + /// Encodes a typed frame into the RPC envelope's dictionary payload. + public func jsonObject(from value: some Encodable) throws -> [String: Any] { let data = try JSONEncoder().encode(value) guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { - throw MobileSyncFrameJSONError.notAnObject + throw MobileSyncFrameCodingError.notAnObject } return object } - public static func decode( + /// Decodes a typed frame from the RPC envelope's dictionary payload. + public func decode( _ type: Value.Type, fromJSONObject object: [String: Any] ) throws -> Value { @@ -171,7 +204,8 @@ public enum MobileSyncFrameJSON { return try JSONDecoder().decode(type, from: data) } - public static func decode( + /// Decodes a typed frame from a JSON string (tests and fixtures). + public func decode( _ type: Value.Type, fromJSONString string: String ) throws -> Value { @@ -180,6 +214,7 @@ public enum MobileSyncFrameJSON { } /// Failure bridging a sync frame to or from the RPC envelope's JSON container. -public enum MobileSyncFrameJSONError: Error, Equatable, Sendable { +public enum MobileSyncFrameCodingError: Error, Equatable, Sendable { + /// The encoded frame was not a JSON object at the top level. case notAnObject } diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift index 200348c72248..fc691bc8fb36 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift @@ -18,10 +18,13 @@ public enum MobileSyncApplyResult: Equatable, Sendable { /// consumer, the shell state. @MainActor public final class MobileSyncCollectionMirror { + /// The store epoch the mirrored state belongs to; nil before first state. public private(set) var epoch: String? + /// The last revision applied within that epoch. public private(set) var rev: UInt64 = 0 private var recordsByID: [String: Record] = [:] + /// Creates an empty mirror awaiting its first snapshot. public init() {} /// Records in presentation order: `syncSortIndex`, then id for @@ -117,9 +120,12 @@ public final class MobileSyncCollectionMirror { /// cursor plumbing a `mobile.sync.fetch` round-trip needs. @MainActor public final class MobileStateSyncMirror { + /// The workspaces collection mirror. public let workspaces = MobileSyncCollectionMirror() + /// The groups collection mirror. public let groups = MobileSyncCollectionMirror() + /// Creates an empty root mirror awaiting its first fetch. public init() {} /// The fetch request that brings both collections current from their @@ -154,6 +160,7 @@ public final class MobileStateSyncMirror { return .staleIgnored } + /// Drops all state for both collections (sign-out, unpair). public func reset() { workspaces.reset() groups.reset() diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift index 750ed8a3ab1a..1e9a83f23d3f 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift @@ -17,8 +17,10 @@ public protocol MobileSyncRecord: Codable, Equatable, Sendable { /// enum) so an older client can skip frames for collections it does not know /// instead of failing to decode the envelope. public struct MobileSyncCollectionID: RawRepresentable, Codable, Hashable, Sendable { + /// The collection's wire name. public let rawValue: String + /// Creates a collection id from its wire name. public init(rawValue: String) { self.rawValue = rawValue } @@ -35,12 +37,18 @@ public struct MobileSyncCollectionID: RawRepresentable, Codable, Hashable, Senda public struct WorkspaceSyncRecord: MobileSyncRecord { /// One terminal row within a workspace. public struct Terminal: Codable, Equatable, Sendable { + /// Stable terminal identifier. public let id: String + /// User-facing terminal title (custom rename aware). public let title: String + /// The terminal's current working directory, when reported. public let currentDirectory: String? + /// Whether the terminal surface is ready to render. public let isReady: Bool + /// Whether the terminal currently holds focus in its workspace. public let isFocused: Bool + /// Creates a terminal row from its wire fields. public init( id: String, title: String, @@ -64,23 +72,39 @@ public struct WorkspaceSyncRecord: MobileSyncRecord { } } + /// Stable workspace identifier. public let id: String + /// Owning Mac window identifier, when reported. public let windowID: String? + /// User-facing workspace title. public let title: String + /// The workspace's presented working directory, when reported. public let currentDirectory: String? + /// Whether the Mac currently has this workspace selected. public let isSelected: Bool + /// Whether the workspace is pinned on the Mac. public let isPinned: Bool + /// The owning group's identifier; nil for ungrouped workspaces. public let groupID: String? + /// One-line plain-text preview of the latest activity, when any. public let preview: String? + /// Unix epoch seconds of the preview's activity, when any. public let previewAt: Double? + /// Unix epoch seconds of the workspace's last activity. public let lastActivityAt: Double + /// Whether the workspace has unread activity on the Mac. public let hasUnread: Bool + /// Position in the Mac's presented cross-window order. public let sortIndex: Int + /// Terminal rows belonging to this workspace, in spatial order. public let terminals: [Terminal] + /// ``MobileSyncRecord`` identity: the workspace id. public var syncID: String { id } + /// ``MobileSyncRecord`` ordering key: the presented list position. public var syncSortIndex: Int { sortIndex } + /// Creates a workspace row from its wire fields. public init( id: String, windowID: String?, @@ -133,16 +157,25 @@ public struct WorkspaceSyncRecord: MobileSyncRecord { /// `group_id` in workspace order, exactly as the legacy list is consumed, so /// this record intentionally carries no member array to invalidate. public struct GroupSyncRecord: MobileSyncRecord { + /// Stable group identifier. public let id: String + /// User-facing group name (section header label). public let name: String + /// Whether the group is collapsed on the Mac. public let isCollapsed: Bool + /// Whether the group is pinned on the Mac. public let isPinned: Bool + /// The anchor workspace that owns this group. public let anchorWorkspaceID: String + /// Position in the Mac's presented section order. public let sortIndex: Int + /// ``MobileSyncRecord`` identity: the group id. public var syncID: String { id } + /// ``MobileSyncRecord`` ordering key: the presented section position. public var syncSortIndex: Int { sortIndex } + /// Creates a group row from its wire fields. public init( id: String, name: String, diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift index 27e8bfa23beb..709449646eee 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift @@ -4,9 +4,13 @@ import Foundation /// embedding in a `mobile.sync.delta` event. `nil` change means the tick was a /// no-op and nothing travels. public struct MobileSyncCollectionChange: Equatable, Sendable { + /// The head revision before this tick. public let fromRev: UInt64 + /// The head revision after this tick. public let toRev: UInt64 + /// Full rows changed in this tick. public let records: [Record] + /// Ids removed in this tick. public let removedIDs: [String] } @@ -37,6 +41,7 @@ public final class MobileSyncCollectionStore { /// workspace-churn rate; the bound exists so memory never tracks history. private let maximumTombstoneCount: Int + /// The collection's current head revision (monotonic within the epoch). public private(set) var headRev: UInt64 = 0 private var stampedByID: [String: Stamped] = [:] private var tombstones: [Tombstone] = [] @@ -46,6 +51,8 @@ public final class MobileSyncCollectionStore { /// oldest retained tombstone (which may be a partial batch). private var discardedTombstoneRevBound: UInt64 = 0 + /// Creates a store retaining at most `maximumTombstoneCount` removal + /// tombstones before old cursors are forced to snapshot. public init(maximumTombstoneCount: Int = 1024) { self.maximumTombstoneCount = maximumTombstoneCount } @@ -152,10 +159,14 @@ public final class MobileSyncCollectionStore { /// invalidates every client cursor from a previous run. @MainActor public final class MobileStateSyncStore { + /// The epoch every cursor from this store is scoped to (fresh each run). public let epoch: String + /// The workspaces collection store. public let workspaces: MobileSyncCollectionStore + /// The groups collection store. public let groups: MobileSyncCollectionStore + /// Creates a root store; a fresh epoch invalidates every prior cursor. public init(epoch: String = UUID().uuidString) { self.epoch = epoch self.workspaces = MobileSyncCollectionStore() diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift index 05ca85c45838..100141b1f31f 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift @@ -31,7 +31,7 @@ struct MobileStateSyncFrameCodingTests { } @Test func workspaceRecordUsesLegacyWireKeys() throws { - let object = try MobileSyncFrameJSON.jsonObject(from: workspace) + let object = try MobileSyncFrameCoder().jsonObject(from: workspace) #expect(object["id"] as? String == "ws-1") #expect(object["window_id"] as? String == "win-1") #expect(object["current_directory"] as? String == "/repo") @@ -56,12 +56,12 @@ struct MobileStateSyncFrameCodingTests { records: [workspace], removedIDs: ["ws-9"] ) - let object = try MobileSyncFrameJSON.jsonObject(from: event) + let object = try MobileSyncFrameCoder().jsonObject(from: event) #expect(object["from_rev"] as? UInt64 == 41) #expect(object["to_rev"] as? UInt64 == 42) #expect(object["removed_ids"] as? [String] == ["ws-9"]) - let decoded = try MobileSyncFrameJSON.decode( + let decoded = try MobileSyncFrameCoder().decode( MobileSyncDeltaEvent.self, fromJSONObject: object ) @@ -77,8 +77,8 @@ struct MobileStateSyncFrameCodingTests { records: [], removedIDs: [] ) - let object = try MobileSyncFrameJSON.jsonObject(from: event) - let header = try MobileSyncFrameJSON.decode(MobileSyncDeltaEventHeader.self, fromJSONObject: object) + let object = try MobileSyncFrameCoder().jsonObject(from: event) + let header = try MobileSyncFrameCoder().decode(MobileSyncDeltaEventHeader.self, fromJSONObject: object) #expect(header.collection == .groups) } @@ -90,7 +90,7 @@ struct MobileStateSyncFrameCodingTests { ["id": "future_collection", "epoch": "e1", "rev": 3], ] ] - let request = try MobileSyncFrameJSON.decode(MobileSyncFetchRequest.self, fromJSONObject: params) + let request = try MobileSyncFrameCoder().decode(MobileSyncFetchRequest.self, fromJSONObject: params) #expect(request.collections.count == 3) #expect(request.collections[0].cursor == MobileSyncCursor(epoch: "e1", rev: 12)) #expect(request.collections[1].cursor == nil) @@ -109,18 +109,18 @@ struct MobileStateSyncFrameCodingTests { ), groups: nil ) - let object = try MobileSyncFrameJSON.jsonObject(from: response) + let object = try MobileSyncFrameCoder().jsonObject(from: response) #expect(object["groups"] == nil) let section = object["workspaces"] as? [String: Any] #expect(section?["mode"] as? String == "snapshot") #expect(section?["from_rev"] == nil) - let decoded = try MobileSyncFrameJSON.decode(MobileSyncFetchResponse.self, fromJSONObject: object) + let decoded = try MobileSyncFrameCoder().decode(MobileSyncFetchResponse.self, fromJSONObject: object) #expect(decoded == response) } @Test func unknownCollectionIDDecodesInsteadOfFailing() throws { - let decoded = try MobileSyncFrameJSON.decode( + let decoded = try MobileSyncFrameCoder().decode( MobileSyncDeltaEventHeader.self, fromJSONString: #"{"collection":"records_from_the_future"}"# ) diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift index da0634baf428..e23e29d854d4 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift @@ -214,6 +214,8 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { // already-synced local source (mobile state sync v2 projects its record mirror // through the same apply path the decoded wire response uses). extension MobileSyncWorkspaceListResponse { + /// Memberwise construction for locally-synced sources (state sync v2 + /// projects its record mirror through the same apply path). public init( workspaces: [Workspace], groups: [Group], diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift index 41c91ae00668..19b3697aef4a 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift @@ -182,7 +182,7 @@ struct MobileCoreRPCIndependentEventTests { let envelope = try JSONSerialization.data(withJSONObject: [ "kind": "event", "topic": "mobile.sync.delta", - "payload": try MobileSyncFrameJSON.jsonObject(from: delta), + "payload": try MobileSyncFrameCoder().jsonObject(from: delta), ]) await source.yield(try MobileSyncFrameCodec.encodeFrame(envelope)) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index e2753ceab6bb..98a609dca2c1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -922,7 +922,11 @@ extension MobileShellComposite { once.finish(await operationTask.value) } Task { - try? await Task.sleep(nanoseconds: nanoseconds) + // Intentional bounded deadline timer (not a polling wait); + // cancellation of the race cancels the operation via the + // handler above, and this timer resolves the race at the + // bound either way. + try? await ContinuousClock().sleep(for: .nanoseconds(Int64(nanoseconds))) operationTask.cancel() once.finish(nil) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index 7fd36a1ba4c2..c0c82c199373 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -212,7 +212,7 @@ extension MobileShellComposite { guard remoteClient === client, connectionState == .connected, !Task.isCancelled else { return false } let params: [String: Any] do { - params = try MobileSyncFrameJSON.jsonObject(from: stateSyncMirror.fetchRequest) + params = try MobileSyncFrameCoder().jsonObject(from: stateSyncMirror.fetchRequest) } catch { return false } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift index fcd7dd751f93..b26193fe55c6 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift @@ -77,7 +77,7 @@ private func syncDeltaEventFrame( let envelope: [String: Any] = [ "kind": "event", "topic": "mobile.sync.delta", - "payload": try MobileSyncFrameJSON.jsonObject(from: event), + "payload": try MobileSyncFrameCoder().jsonObject(from: event), ] return try MobileSyncFrameCodec.encodeFrame(JSONSerialization.data(withJSONObject: envelope)) } diff --git a/Sources/Mobile/MobileStateSync.swift b/Sources/Mobile/MobileStateSync.swift index 72d7dc4b5eaf..b8804563f1e6 100644 --- a/Sources/Mobile/MobileStateSync.swift +++ b/Sources/Mobile/MobileStateSync.swift @@ -45,7 +45,7 @@ final class MobileStateSyncHost { func fetch(params: [String: Any]) -> TerminalController.V2CallResult { let request: MobileSyncFetchRequest do { - request = try MobileSyncFrameJSON.decode(MobileSyncFetchRequest.self, fromJSONObject: params) + request = try MobileSyncFrameCoder().decode(MobileSyncFetchRequest.self, fromJSONObject: params) } catch { return .err(code: "invalid_params", message: "Missing or invalid collections", data: nil) } @@ -54,7 +54,7 @@ final class MobileStateSyncHost { } refreshAndBroadcast() let response = store.fetchResponse(for: request) - guard let payload = try? MobileSyncFrameJSON.jsonObject(from: response) else { + guard let payload = try? MobileSyncFrameCoder().jsonObject(from: response) else { return .err(code: "internal_error", message: "Failed to encode sync response", data: nil) } return .ok(payload) @@ -84,7 +84,7 @@ final class MobileStateSyncHost { records: change.records, removedIDs: change.removedIDs ) - guard let payload = try? MobileSyncFrameJSON.jsonObject(from: event) else { return } + guard let payload = try? MobileSyncFrameCoder().jsonObject(from: event) else { return } MobileHostService.shared.emitEvent(topic: Self.deltaTopic, payload: payload) } From 2d4571e04802fcf71b42ead0de458bd13b5e5515 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 12:42:32 -0700 Subject: [PATCH 20/21] Address final review finding: fallback reload unconditional on transient failure Renegotiation clears authority before the fetch, so the fallback's guard on current authority skipped exactly the recovery it exists for: a transient negotiation-fetch failure after a same-client resubscribe left events missed in the subscription gap unrecovered. The bounded legacy reload now runs on every transient fetch failure regardless of authority (currency-guarded per iteration). Adds trace lines on the fallback path and a regression test (transientNegotiationFailureStillRunsTheLegacyReload). Co-Authored-By: Claude Fable 5 --- .../MobileShellComposite+StateSync.swift | 15 ++++++++++-- .../MobileShellStateSyncTests.swift | 23 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index c0c82c199373..170138209fb1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -1,4 +1,5 @@ import CMUXMobileCore +import CmuxMobileDiagnostics import CmuxMobileRPC import Foundation internal import OSLog @@ -265,6 +266,7 @@ extension MobileShellComposite { mobileStateSyncLog.error( "state sync fetch failed: \(String(describing: error), privacy: .private)" ) + MobileDebugLog.anchormux("sync.v2 fetch failed; falling back") fallBackToLegacyListAfterFetchFailure(client: client) return false } @@ -278,8 +280,13 @@ extension MobileShellComposite { /// next event-listener generation re-negotiates v2. private func fallBackToLegacyListAfterFetchFailure(client: MobileCoreRPCClient) { guard remoteClient === client, connectionState == .connected else { return } - guard stateSyncActive else { return } + // Unconditional on transient failure: during renegotiation the + // authority was already cleared before the fetch, and events missed + // in the subscription gap still need the authoritative reload — a + // guard on current authority here would skip exactly the recovery + // this exists for. stateSyncAuthorityClientID = nil + MobileDebugLog.anchormux("sync.v2 fallback to legacy after fetch failure") Task { @MainActor [weak self] in // The missed delta may have been the last event, so this reload // cannot be fire-and-forget: retry a bounded number of times with @@ -289,7 +296,11 @@ extension MobileShellComposite { for attempt in 0..<3 { guard let self, self.remoteClient === client, self.connectionState == .connected, - !self.stateSyncActive else { return } + !self.stateSyncActive else { + MobileDebugLog.anchormux("sync.v2 fallback loop guard exited") + return + } + MobileDebugLog.anchormux("sync.v2 fallback reload attempt \(attempt)") if await self.reloadWorkspaceListFromMac() { return } try? await ContinuousClock().sleep(for: .seconds(2 << attempt)) } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift index b26193fe55c6..c5e19acf4837 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift @@ -236,6 +236,29 @@ struct MobileShellStateSyncTests { #expect(store.stateSyncActive == false) } + @Test func transientNegotiationFailureStillRunsTheLegacyReload() async throws { + // The negotiation fetch itself fails transiently (not method_not_found). + // Events missed in the subscription gap must still be recovered by the + // authoritative legacy reload even though authority was never granted. + let router = LivenessHostRouter() + await router.scriptSyncFetchTransientError() + let box = TransportBox() + let clock = TestClock() + let store = try await makeConnectedStore(router: router, box: box, clock: clock) + + let probed = try await pollUntil { + await router.count(of: "mobile.sync.fetch") >= 1 + } + #expect(probed) + #expect(store.stateSyncActive == false) + // The connect flow's route binding uses "workspace.list"; only the + // fallback reload issues "mobile.workspace.list" here. + let reloaded = try await pollUntil { + await router.count(of: "mobile.workspace.list") >= 1 + } + #expect(reloaded, "a transient negotiation failure must trigger the authoritative legacy reload") + } + @Test func legacyMacKeepsWorkspaceUpdatedRefetchLoop() async throws { // No scripted sync result: the router answers `method_not_found`, // modeling a released Mac. From 11a7e9e35c656fac6abb3d22506088f173764346 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 12:49:11 -0700 Subject: [PATCH 21/21] Re-check v2 authority after the legacy list await Negotiation can grant v2 while a legacy full-list request is in flight; applying the captured response then would overwrite newer mirror state. The legacy path now re-checks authority after the await and reports liveness success without applying when v2 took ownership. Co-Authored-By: Claude Fable 5 --- .../MobileShellComposite+ConnectionRecovery.swift | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 98a609dca2c1..04f07dc90b1f 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -836,6 +836,12 @@ extension MobileShellComposite { ) let response = try MobileSyncWorkspaceListResponse.decode(data) guard remoteClient === client, connectionState == .connected else { return false } + // Re-check authority AFTER the await: negotiation can grant v2 in + // the window while this legacy request was in flight, and applying + // the captured full list then would overwrite newer mirror state. + // The round-trip already proved liveness; the v2 mirror owns the + // list, so report success without applying. + if stateSyncActive { return true } applyRemoteWorkspaceList(response, preferActiveTicketTarget: false) syncSelectedTerminalForWorkspace() return true