diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift new file mode 100644 index 000000000000..642cae3d84cd --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncFrames.swift @@ -0,0 +1,220 @@ +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 { + /// 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 + } +} + +/// 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 { + /// 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, + 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 { + /// 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 + 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) + } + } + + /// The collections the client wants brought current. + public let collections: [Collection] + + /// Creates a fetch request. + 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 { + /// 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?, + 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 { + /// 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, + 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 { + /// 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 + } +} + +/// 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. 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 MobileSyncFrameCodingError.notAnObject + } + return object + } + + /// Decodes a typed frame from the RPC envelope's dictionary payload. + public 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) + } + + /// Decodes a typed frame from a JSON string (tests and fixtures). + public 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 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 new file mode 100644 index 000000000000..fc691bc8fb36 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift @@ -0,0 +1,168 @@ +/// 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 { + /// 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 + /// 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: + // 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 } + ) + 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 } + // 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 + } + + /// 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 { + /// 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 + /// 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 + } + + /// 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 new file mode 100644 index 000000000000..1e9a83f23d3f --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift @@ -0,0 +1,203 @@ +/// 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 { + /// The collection's wire name. + public let rawValue: String + + /// Creates a collection id from its wire name. + 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 { + /// 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, + 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" + } + } + + /// 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?, + 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 { + /// 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, + 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..709449646eee --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncStore.swift @@ -0,0 +1,199 @@ +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 { + /// 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] +} + +/// 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 + + /// 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] = [] + /// 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 + + /// Creates a store retaining at most `maximumTombstoneCount` removal + /// tombstones before old cursors are forced to snapshot. + 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 { + 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, + 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. 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 } + return rev >= discardedTombstoneRevBound + } + + /// 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) + // 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, + 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 { + /// 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() + 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..100141b1f31f --- /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 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") + #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 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 MobileSyncFrameCoder().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 MobileSyncFrameCoder().jsonObject(from: event) + let header = try MobileSyncFrameCoder().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 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) + #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 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 MobileSyncFrameCoder().decode(MobileSyncFetchResponse.self, fromJSONObject: object) + #expect(decoded == response) + } + + @Test func unknownCollectionIDDecodesInsteadOfFailing() throws { + let decoded = try MobileSyncFrameCoder().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..71be7ba2895d --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncMirrorTests.swift @@ -0,0 +1,184 @@ +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 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") + #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..3d89b9409c72 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift @@ -0,0 +1,222 @@ +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 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 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")]) + 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/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/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift index 73a2da2ca417..e23e29d854d4 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,25 @@ 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 { + /// Memberwise construction for locally-synced sources (state sync v2 + /// projects its record mirror through the same apply path). + 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/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCIndependentEventTests.swift index 64b94d95e781..19b3697aef4a 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 MobileSyncFrameCoder().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") diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 0e1c1ebbe624..04f07dc90b1f 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -233,12 +233,55 @@ 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: 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, @@ -773,6 +816,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", @@ -784,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 @@ -803,4 +861,108 @@ 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. + /// + /// 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. + /// 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) + // 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, + !self.connectionRecoveryOwner.isRedialingOrValidating, + self.automaticReconnectRetryTask == nil else { return } + self.recoverMobileConnection(trigger: .automaticBackoffExpired) + } + } + + /// 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 -> DeadlineRaceOutcome { + let operationTask = Task { await operation() } + // 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 { + // 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) + } + } + } onCancel: { + operationTask.cancel() + } + return DeadlineRaceOutcome( + value: value, + abandoned: value == nil ? operationTask : nil + ) + } +} + +/// 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 new file mode 100644 index 000000000000..170138209fb1 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -0,0 +1,359 @@ +import CMUXMobileCore +import CmuxMobileDiagnostics +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) { + stateSyncAuthorityClientID = nil + 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) { + // 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 + } + guard let header = try? JSONDecoder().decode(MobileSyncDeltaEventHeader.self, from: payload) else { + scheduleStateSyncRepairIfActive() + return + } + let result: MobileSyncApplyResult + switch header.collection { + case .workspaces: + guard let delta = try? JSONDecoder().decode( + MobileSyncDeltaEvent.self, from: payload + ) 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 { + scheduleStateSyncRepairIfActive() + 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) + } + } + } + + /// Entry point for sibling composite extensions (liveness probe and + /// 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). 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, + timeoutNanoseconds: UInt64? = nil + ) async -> Bool { + // 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. + // + // 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, + /// 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() + stateSyncAuthorityClientID = nil + stateSyncFetchClientID = nil + stateSyncFetchFollowUpRequested = 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 } + scheduleStateSyncFetch(client: client) + } + + /// Single-flight, restart-on-newest cursor fetch (negotiation and gap + /// repair share it, mirroring ``workspaceListRefreshTask`` semantics). + @discardableResult + private func scheduleStateSyncFetch( + 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 + 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 + } + return applied + } + stateSyncFetchTask = task + return task + } + + @discardableResult + private func runStateSyncFetch( + client: MobileCoreRPCClient, + 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 + // 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 false } + let params: [String: Any] + do { + params = try MobileSyncFrameCoder().jsonObject(from: stateSyncMirror.fetchRequest) + } catch { + return false + } + do { + let request = try MobileCoreRPCClient.requestData( + method: "mobile.sync.fetch", + params: params + ) + let data = try await client.sendRequest( + request, + 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) + stateSyncAuthorityClientID = ObjectIdentifier(client) + 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) + } + 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. + stateSyncAuthorityClientID = nil + return false + } + mobileStateSyncLog.error( + "state sync fetch failed: \(String(describing: error), privacy: .private)" + ) + MobileDebugLog.anchormux("sync.v2 fetch failed; falling back") + fallBackToLegacyListAfterFetchFailure(client: client) + return false + } + } + + /// 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 } + // 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 + // 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 { + 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)) + } + mobileStateSyncLog.error("legacy fallback reload exhausted retries; awaiting next event or recovery") + } + } + + /// 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+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 diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index b3c2a5d1e36c..5db622b91317 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", "notification.feed.changed"] + return ["workspace.updated", "mobile.sync.delta", "terminal.bytes", "terminal.render_grid", "terminal.set_font", "notification.dismissed", "notification.badge", "notification.feed.changed"] case .renderGrid: - return ["workspace.updated", "terminal.render_grid", "terminal.set_font", "notification.dismissed", "notification.badge", "notification.feed.changed"] + return ["workspace.updated", "mobile.sync.delta", "terminal.render_grid", "terminal.set_font", "notification.dismissed", "notification.badge", "notification.feed.changed"] case .rawBytes: - return ["workspace.updated", "terminal.bytes", "terminal.set_font", "notification.dismissed", "notification.badge", "notification.feed.changed"] + return ["workspace.updated", "mobile.sync.delta", "terminal.bytes", "terminal.set_font", "notification.dismissed", "notification.badge", "notification.feed.changed"] } } @@ -766,6 +766,42 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { var createWorkspaceTaskSpec: MobileWorkspaceCreateSpec? 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() + /// 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: Bool { + guard let stateSyncAuthorityClientID, let remoteClient else { return false } + return stateSyncAuthorityClientID == ObjectIdentifier(remoteClient) + } + /// 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? + /// 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. @@ -1159,6 +1195,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() @@ -6719,6 +6760,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" { @@ -6786,6 +6829,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) } } @@ -6988,10 +7039,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))") } @@ -7818,8 +7870,31 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { markTerminalBytesDelivered(surfaceID: surfaceID, endSeq: endSeq) } + /// 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/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/MobileShellRenderGridLivenessTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift index 18760ef2b79a..89deffa87fae 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift @@ -55,11 +55,29 @@ 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) + } + + /// 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, @@ -371,6 +389,18 @@ 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") + } + 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) { @@ -407,11 +437,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..c5e19acf4837 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift @@ -0,0 +1,284 @@ +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 MobileSyncFrameCoder().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 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 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 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. + 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/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift new file mode 100644 index 000000000000..8443e66a4e05 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectAttemptDeadlineTests.swift @@ -0,0 +1,104 @@ +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 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 = await MobileShellComposite.raceAgainstDeadline( + nanoseconds: 50_000_000 + ) { + await withCheckedContinuation { (_: CheckedContinuation) in + // Parked forever; no cancellation handler on purpose. + } + } + #expect(outcome.value == nil) + #expect(outcome.abandoned != nil, "the wedged operation is handed back for bounded tracking") + } + + @Test func deadlineRaceReturnsOperationValueWhenItWins() async { + let outcome = await MobileShellComposite.raceAgainstDeadline( + nanoseconds: 5_000_000_000 + ) { 42 } + #expect(outcome.value == 42) + #expect(outcome.abandoned == nil) + } + + @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) + + // 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(attempts: 3000) { + !store.connectionRecoveryOwner.isRedialingOrValidating + } + #expect(settled, "a hung dial must settle at the attempt deadline, not hold recovery forever") + #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. 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: 3000) { + 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..ea01b5b9fa04 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests+Support.swift @@ -174,6 +174,25 @@ final class KindRecordingTransportFactory: CmxByteTransportFactory, @unchecked S private let lock = NSLock() 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, + /// hole-punch stall) so tests can prove recovery attempts stay bounded. + func setHangingKinds(_ kinds: Set) { + 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, @@ -206,6 +225,11 @@ final class KindRecordingTransportFactory: CmxByteTransportFactory, @unchecked S if failingKinds.contains(route.kind) { throw RouteRecordingTransportError.routeFailed } + if lock.withLock({ hangingKinds.contains(route.kind) }) { + let transport = HangingConnectTransport() + lock.withLock { hangingTransports.append(transport) } + return transport + } let transport = LivenessTransport(router: router) box.set(transport) return transport @@ -219,3 +243,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() + } + } +} diff --git a/Sources/Mobile/MobileHostService+TicketAuthorization.swift b/Sources/Mobile/MobileHostService+TicketAuthorization.swift index fe30a4c3c989..e534e69033ec 100644 --- a/Sources/Mobile/MobileHostService+TicketAuthorization.swift +++ b/Sources/Mobile/MobileHostService+TicketAuthorization.swift @@ -41,6 +41,10 @@ extension MobileHostService { case "mobile.workspace.list", "workspace.list", "mobile.directory.list", "mobile.directory.search": 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..b8804563f1e6 --- /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 MobileSyncFrameCoder().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? MobileSyncFrameCoder().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? MobileSyncFrameCoder().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 77878a4a6369..c0061f1a9191 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -13886,6 +13886,8 @@ class TerminalController { result = v2MobileNotificationFeedMarkAllRead(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 0fc9edb814dc..589fd5373a2d 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1103,6 +1103,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 */; }; D1B800000000000000000001 /* MobileTaskDirectoryListItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1B800000000000000000011 /* MobileTaskDirectoryListItem.swift */; }; D1B800000000000000000002 /* MobileTaskDirectoryListPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1B800000000000000000012 /* MobileTaskDirectoryListPage.swift */; }; D1B800000000000000000003 /* MobileTaskDirectoryListService.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1B800000000000000000013 /* MobileTaskDirectoryListService.swift */; }; @@ -3215,6 +3216,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 = ""; }; D1B800000000000000000011 /* MobileTaskDirectoryListItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileTaskDirectoryListItem.swift; sourceTree = ""; }; D1B800000000000000000012 /* MobileTaskDirectoryListPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileTaskDirectoryListPage.swift; sourceTree = ""; }; D1B800000000000000000013 /* MobileTaskDirectoryListService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileTaskDirectoryListService.swift; sourceTree = ""; }; @@ -4444,6 +4446,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 */, @@ -7544,6 +7547,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 */, D1B800000000000000000001 /* MobileTaskDirectoryListItem.swift in Sources */, D1B800000000000000000002 /* MobileTaskDirectoryListPage.swift in Sources */, D1B800000000000000000003 /* MobileTaskDirectoryListService.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..6b54746937ec --- /dev/null +++ b/docs/mobile-state-sync-v2.md @@ -0,0 +1,105 @@ +# 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 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.