Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
30c424c
Mobile state sync v2: per-record deltas replace invalidate-and-refetch
Jul 16, 2026
2f11b0f
Merge remote-tracking branch 'origin/main' into feat-mobile-sync-v2
Jul 17, 2026
f5d513d
Merge main (iOS reconnect/build isolation fix) and guard stale sync f…
Jul 17, 2026
4788fd7
Use explicit self in sidebar row tint closure for newer toolchains
Jul 17, 2026
8038b6f
Merge remote-tracking branch 'origin/main' into feat-mobile-sync-v2
Jul 20, 2026
c9f8079
Adopt main's sidebar tint-closure fix verbatim
Jul 20, 2026
e04e006
Prove mobile.sync.delta rides the independent Iroh server-events lane
Jul 20, 2026
1546b8c
Regression test: hung redial must settle and unfreeze recovery
Jul 21, 2026
a2f59a3
Bound reconnect attempts with a hard deadline; manual retry clears ba…
Jul 21, 2026
751ff50
Merge remote-tracking branch 'origin/main' into feat-mobile-sync-v2
Jul 21, 2026
f7bcc0d
Address review findings: sync integrity guards + fetch handle race
Jul 21, 2026
defc6eb
Address autoreview round 1: unstructured deadline race, repair fallba…
Jul 21, 2026
ffdc47e
Address autoreview round 2: bounded abandoned dials + fallback reload…
Jul 21, 2026
d23a913
Address autoreview round 3: subscription-ack sequencing + refresh sem…
Jul 21, 2026
916fc40
Address autoreview round 4: register abandoned dials pre-guard, follo…
Jul 21, 2026
b29d7cf
Address autoreview round 5: partial-response guard, account-boundary …
Jul 21, 2026
f440923
Address autoreview round 6 + fix janitor re-block; harden deadline test
Jul 21, 2026
364c651
Address autoreview round 7: scope state-sync authority to the owning …
Jul 21, 2026
b64707c
Address autoreview round 8: single-flight fetch runner with trailing …
Jul 21, 2026
cdc2467
Address autoreview round 9: bound every reconnect caller; per-waiter …
Jul 21, 2026
d437edb
Revert blanket reconnect deadline wrapper; keep waiter bounds + cance…
Jul 21, 2026
3983726
Policy pass: DocC all public sync symbols, injectable frame coder, cl…
Jul 21, 2026
2d4571e
Address final review finding: fallback reload unconditional on transi…
Jul 21, 2026
11a7e9e
Re-check v2 authority after the legacy list await
Jul 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import Foundation

/// Client-held position in one collection's revision stream. Only meaningful
/// while the Mac's `epoch` is unchanged; a cursor from another epoch always
/// resolves to a snapshot.
public struct MobileSyncCursor: Codable, Equatable, Sendable {
public let epoch: String
public let rev: UInt64

public init(epoch: String, rev: UInt64) {
self.epoch = epoch
self.rev = rev
}
}

/// How a fetch response section carries its records.
public enum MobileSyncPayloadMode: String, Codable, Sendable {
/// `records` is the full row set; replace local state.
case snapshot
/// `records`/`removed_ids` are changes in `(from_rev, rev]`; apply over
/// local state at `from_rev` or newer.
case delta
}

/// One collection section of a `mobile.sync.fetch` response.
public struct MobileSyncCollectionPayload<Record: MobileSyncRecord>: Codable, Equatable, Sendable {
public let mode: MobileSyncPayloadMode
/// Head revision the payload brings the client to.
public let rev: UInt64
/// The client revision this delta starts from. Absent for snapshots.
public let fromRev: UInt64?
public let records: [Record]
public let removedIDs: [String]

public init(
mode: MobileSyncPayloadMode,
rev: UInt64,
fromRev: UInt64?,
records: [Record],
removedIDs: [String]
) {
self.mode = mode
self.rev = rev
self.fromRev = fromRev
self.records = records
self.removedIDs = removedIDs
}

private enum CodingKeys: String, CodingKey {
case mode
case rev
case fromRev = "from_rev"
case records
case removedIDs = "removed_ids"
}
}

/// The `mobile.sync.fetch` request body: one cursor entry per collection the
/// client wants. A missing cursor means cold start (snapshot).
public struct MobileSyncFetchRequest: Codable, Equatable, Sendable {
public struct Collection: Codable, Equatable, Sendable {
public let id: MobileSyncCollectionID
public let epoch: String?
public let rev: UInt64?

public init(id: MobileSyncCollectionID, epoch: String?, rev: UInt64?) {
self.id = id
self.epoch = epoch
self.rev = rev
}

/// The cursor this entry carries, when it carries a complete one.
public var cursor: MobileSyncCursor? {
guard let epoch, let rev else { return nil }
return MobileSyncCursor(epoch: epoch, rev: rev)
}
}

public let collections: [Collection]

public init(collections: [Collection]) {
self.collections = collections
}
}

/// The `mobile.sync.fetch` response body. Sections are optional so the shape
/// can grow collections without breaking older peers; a client ignores
/// sections it did not request and tolerates missing ones.
public struct MobileSyncFetchResponse: Codable, Equatable, Sendable {
public let epoch: String
public let workspaces: MobileSyncCollectionPayload<WorkspaceSyncRecord>?
public let groups: MobileSyncCollectionPayload<GroupSyncRecord>?

public init(
epoch: String,
workspaces: MobileSyncCollectionPayload<WorkspaceSyncRecord>?,
groups: MobileSyncCollectionPayload<GroupSyncRecord>?
) {
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<Record: MobileSyncRecord>: Codable, Equatable, Sendable {
public let epoch: String
public let collection: MobileSyncCollectionID
public let fromRev: UInt64
public let toRev: UInt64
public let records: [Record]
public let removedIDs: [String]

public init(
epoch: String,
collection: MobileSyncCollectionID,
fromRev: UInt64,
toRev: UInt64,
records: [Record],
removedIDs: [String]
) {
self.epoch = epoch
self.collection = collection
self.fromRev = fromRev
self.toRev = toRev
self.records = records
self.removedIDs = removedIDs
}

private enum CodingKeys: String, CodingKey {
case epoch
case collection
case fromRev = "from_rev"
case toRev = "to_rev"
case records
case removedIDs = "removed_ids"
}
}

/// Collection discriminator decoded before choosing the typed
/// `MobileSyncDeltaEvent` record type for a `mobile.sync.delta` payload.
public struct MobileSyncDeltaEventHeader: Codable, Equatable, Sendable {
public let collection: MobileSyncCollectionID

public init(collection: MobileSyncCollectionID) {
self.collection = collection
}
}

/// JSON bridging between the typed frames and the `[String: Any]` payloads the
/// mobile RPC envelope carries. One round-trip through `JSONSerialization` per
/// frame; frames are small (changed rows only), so this stays off every hot
/// path that matters.
public enum MobileSyncFrameJSON {
public static func jsonObject(from value: some Encodable) throws -> [String: Any] {
let data = try JSONEncoder().encode(value)
guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw MobileSyncFrameJSONError.notAnObject
}
return object
}

public static func decode<Value: Decodable>(
_ type: Value.Type,
fromJSONObject object: [String: Any]
) throws -> Value {
let data = try JSONSerialization.data(withJSONObject: object)
return try JSONDecoder().decode(type, from: data)
}

public static func decode<Value: Decodable>(
_ type: Value.Type,
fromJSONString string: String
) throws -> Value {
try JSONDecoder().decode(type, from: Data(string.utf8))
}
}

/// Failure bridging a sync frame to or from the RPC envelope's JSON container.
public enum MobileSyncFrameJSONError: Error, Equatable, Sendable {
case notAnObject
}
Comment on lines +169 to +220

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Caseless enum used purely as a static-function namespace

MobileSyncFrameJSON has no cases and exposes only static funcs — this is the static-namespace anti-pattern the cmux-no-ambient-global-state rule flags. The preferred shape is a private/fileprivate file-scope helper (not exported) or, since this needs to be public, a struct with a private init() to prevent accidental instantiation while keeping the type system honest. As a public enum with no cases Swift will warn callers that exhaustive switches are trivially satisfied, and the enum form gives no semantic benefit over a namespace struct.

Rule Used: Flag new ambient global state in production Swift:... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/// 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<Record: MobileSyncRecord> {
public private(set) var epoch: String?
public private(set) var rev: UInt64 = 0
private var recordsByID: [String: Record] = [:]

public init() {}

/// Records in presentation order: `syncSortIndex`, then id for
/// determinism when a delta lands between two rows' index updates.
public var orderedRecords: [Record] {
recordsByID.values.sorted {
($0.syncSortIndex, $0.syncID) < ($1.syncSortIndex, $1.syncID)
}
Comment on lines +32 to +35

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

Avoid sorting the full mirror on every projection read.

This performs an O(n log n) sort after sync updates over a collection expected to scale toward roughly 1000 workspaces. Maintain an ordered ID snapshot and only rebuild it when additions, removals, or syncSortIndex changes affect ordering.

As per path instructions, production paths over scalable user data must avoid repeated hot-path sorting.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncMirror.swift`
around lines 29 - 32, Update MobileStateSyncMirror’s orderedRecords projection
to avoid sorting recordsByID.values on every read. Maintain a cached ordered-ID
snapshot, rebuild it only when records are added, removed, or their
syncSortIndex changes affect ordering, and have orderedRecords resolve records
through that snapshot while preserving syncSortIndex/syncID ordering.

Source: Path instructions

}

/// 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<Record>, 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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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<Record>) -> 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 {
public let workspaces = MobileSyncCollectionMirror<WorkspaceSyncRecord>()
public let groups = MobileSyncCollectionMirror<GroupSyncRecord>()

public init() {}

/// The fetch request that brings both collections current from their
/// respective cursors (snapshots on cold start).
public var fetchRequest: MobileSyncFetchRequest {
MobileSyncFetchRequest(collections: [
MobileSyncFetchRequest.Collection(
id: .workspaces,
epoch: workspaces.cursor?.epoch,
rev: workspaces.cursor?.rev
),
MobileSyncFetchRequest.Collection(
id: .groups,
epoch: groups.cursor?.epoch,
rev: groups.cursor?.rev
),
])
}

/// Applies a fetch response to both collections. Returns `.gap` if either
/// section gapped (caller re-fetches), `.applied` if anything advanced.
public func apply(response: MobileSyncFetchResponse) -> MobileSyncApplyResult {
var results: [MobileSyncApplyResult] = []
if let payload = response.workspaces {
results.append(workspaces.apply(payload: payload, epoch: response.epoch))
}
if let payload = response.groups {
results.append(groups.apply(payload: payload, epoch: response.epoch))
}
if results.contains(.gap) { return .gap }
if results.contains(.applied) { return .applied }
return .staleIgnored
}

public func reset() {
workspaces.reset()
groups.reset()
}
}
Loading