// Sync state, for the one Settings row that shows it, the quiet second line on // a list, and anything that wants to say "saved" honestly. // // The number that matters is `pendingOps`: how many local writes have not reached the server. // Zero means the phone and the server agree. Non-zero is NOT an error state — // it is the normal condition on a train — so nothing here is rendered as a // warning. A device refusal is the opposite: the server said no in a way the // person has to act on, and it must be shown. // // Fed by `read.syncStatus` at open, by the `cycle` event a finished pass emits, // and by the `data` event after — which is the same signal the screens // invalidate on, so the number stays honest without a timer. // // **What this model does NOT read.** `read.syncStatus` answers // `{connected:false, reason}` where `reason` is a SENTENCE the controller wrote // (`NOT_CONNECTED`, `NO_TRANSPORT`) — never a refusal code. Mapping it to one // was silently always `nil`: every refusal the person had to act on went // unpainted. A terminal refusal reaches the app through `read.boot`'s own // `refusal` field, and `RootView` hands it here. // // `lastPullAt` IS real: an ISO-8601 stamp of the last pass that actually reached // the server, ABSENT before the first (never a zero, which a banner reads as // 1970). It rides both `read.syncStatus` and the `cycle` event, so the line // moves without a second round trip for the same fact. // // **What the loop is doing, as one word, is the core's** (`shell.home`'s // `sync.state`, boundary review move 5): this model keeps the loop's last // status for the facts a screen reads off it (the schema standing, the last // failure's sentence) and decides no phase of its own. import CottonKit import CottonValues import Foundation import SwiftUI /// Who is behind, when the two builds on a sync disagree about the schema — /// the crate's `SchemaStanding`, spelled as the `sync` event carries it. public enum SchemaStanding: String, Equatable, Sendable { /// This build is older than the file: update the phone. case phoneBehind /// The Mac's build is older than this one: update the Mac. case serverBehind } /// Is there anything to sync WITH — `read.syncStatus`'s `state`. /// /// **A device that pressed *Start* holds a database and no server has joined /// it** (Cotton note "Server address — how a device knows which server holds its data"). That is a STATE, not a failure /// and not an absence: the file is open, every write lands, and there is /// simply nobody on the other end of the loop. Before this the app read it as /// "connecting" for ever, which is a phone telling somebody their data is on /// its way somewhere it is not. /// /// The word is the crate's and this enum is total over it; anything a later /// core grows reads as `joined`, because the phone that cannot name a state /// must not invent "no server" about a database that has one. public enum SyncServerState: String, Equatable, Sendable { case joined case noServerYet } @MainActor @Observable public final class SyncModel { /// Local writes not yet accepted by the server. public private(set) var pendingOps = 0 /// A refusal the person must act on, or `nil`. Handed down from the boot /// read — see the file header. public private(set) var refusal: ServerRefusal? /// Whether this phone can reach its server at all. After 4b this is TRUE on /// a joined phone — `NO_TRANSPORT` must be impossible on a phone that has /// joined, and the smoke test asserts exactly that. public private(set) var canReachServer = false public private(set) var connected = false /// Whether a Mac has joined this database at all. See `SyncServerState`. public private(set) var serverState: SyncServerState = .joined /// The reading every screen wants: is there a server to sync with. public var hasServer: Bool { serverState != .noServerYet } /// The controller's own sentence when there is no file. Prose, shown as /// written; never a code. public private(set) var notConnectedReason: String? /// When a pass last actually reached the server, ISO-8601 as the core wrote /// it. `nil` until one has — the "last checked" line then says nothing /// rather than a date. public private(set) var lastPullAt: String? /// The loop's last word, as the `sync` event or the cold read carried it. /// `nil` while no loop runs. public private(set) var loop: SyncLoopRead? /// A pass is on the wire: the loop's own word (`syncing`). public var passing: Bool { loop?.state == "syncing" } /// The crate's own sentence about the last failed pass, while the loop is /// waiting to try again. Shown as written, never rewritten here. public var lastError: String? { loop?.lastError } /// When the loop will try again, ISO-8601, while it is waiting. public var nextAttemptAt: String? { loop?.nextAttemptAt } /// The `_media` ledger, as "Sync & backup"'s second card reads it. /// /// It rides `read.syncStatus` rather than a read of its own (4h): this /// model already derives the live banner from that one answer, and two /// reads would be two chances to disagree about one screen. `nil` before /// the first status read and on the `{connected:false}` shape, which /// carries no ledger at all — which is NOT "nothing to back up", and the /// card says so. public private(set) var media: MediaActivityRead? /// The one quiet line every app's home draws about its sync /// (`shell_account::seen_of`, as Android has it), as the last status read said it. `nil` before the /// first read. `SyncSeenLine` draws it. public private(set) var seen: SyncSeenRead? /// A status read asked for a moment after a loop event, so a burst of /// events is one read. @ObservationIgnored private var seenRead: Task? /// Which screen families the last `data` event invalidated. A screen /// observes this rather than the table list, so a redraw is one comparison /// rather than a set intersection per screen. public private(set) var invalidated: [ScreenFamily] = [] /// The databases the last announcement's tables moved in, set with /// `invalidated` — `nil` when any event in it named none, which reaches /// every window. One database is shown per window (several-databases P8), /// so a pass over an idle project database re-reads nothing in a window /// showing another: see ``reaches(shown:acrossDatabases:)``. public private(set) var invalidatedDatabases: Set? /// How many times `invalidated` has been ANSWERED, ever — a counter that /// only goes up. /// /// **`invalidated` alone cannot drive a re-read, and this is the reason.** /// A screen watches it with `onChange`, and `onChange` fires on a change of /// VALUE: two folds in a row that both touch `cotton_photos` set the same /// two-element list (`[.photos, .storage]`) twice, the second is not a /// change, and the grid keeps /// drawing the library as it was before the second import. That is not a /// rare shape — it is what a burst of writes to one tool looks like, which /// is most of them. /// /// So a screen watches `revision` and reads `invalidated` when it moves. /// The pair is one fact said two ways: WHAT moved, and that it moved AGAIN. /// A counter is used rather than a stamp for the reason the rest of this /// tree gives — there is no clock in a library here, and a monotone `Int` /// needs none. public private(set) var revision = 0 /// How many `data` events this device's OWN writes raised, ever; a /// board's `list` part reads again when it moves. public private(set) var localWrites = 0 /// The families this device's last own write moved, set with `localWrites` /// (Home re-reads only when one of them is a tile's: architect 2335 item 6). public private(set) var localWrote: Set = [] /// How many times something moved that this device did not write (a /// pull, another device): what re-reads a screen that follows its own /// writes by table. public private(set) var foreignRevision = 0 /// Package discovery follows definition mutations, not every record write. public private(set) var toolPackagesRevision = 0 /// How many times BYTES have moved on this device — the `_media` ledger's /// own counter, bumped whenever a `data` event names the `.storage` /// family: the sweep landed thumbnails, a tap's `media.ensure` landed an /// original, or the budget took one off the disk. /// /// **The ONE place a picture learns to ask again.** Every renderer that /// answered `absent` watches this through `.onMediaArrival` rather than /// each model keeping an epoch of its own (`PhotosGridModel.bytesEpoch` /// was the first, and the second would have disagreed with it). A picture /// that is `.ready` never re-asks — a re-decode over a drawn picture is a /// flicker — so the counter is a doorbell for the absent, not a redraw. public private(set) var mediaEpoch = 0 /// Told the families every announcement names, BEFORE the screens are: /// the session's `AnswerCache` drops the answers those families cover, so /// a screen off the stack cannot be seeded with an answer older than this /// event. Set once by `RootView`; `nil` in a session with no cache. public var invalidating: (@MainActor ([ScreenFamily]) -> Void)? /// The resting state: no file, nothing to sync, and nothing to ASK. /// /// Not a fallback and not a default — it is the honest answer for a world /// with no database in it, and it is what the signed-out branch is wrapped /// in rather than a bare tree. "Signed out" is also the first frame AFTER a /// leave, when a screen that reads sync status may still be mounted; with /// no answer around it that was a crash on every sign-out. /// /// It is a distinct STATE rather than a fresh model with the same fields: /// a resting model's `syncNow()` and `refresh()` are no-ops, because a /// pull-to-refresh on a phone that has left its server would ask a core /// with no connection for a cycle and paint whatever it refused with. private let resting: Bool private let core: any CottonCalling private let clock: CoalesceClock /// Tables that arrived inside the coalescing window and have not been told /// to the screens yet. /// FAMILIES, not tables: the origin is read once, at arrival, and a /// pooled `_media` from the sweep must not come back out of the window as /// `.core` beside a write's tables. private var pooled: Set = [] private var pooledToolPackages = false private var pooledForeign = false /// The databases pooled in the window; `nil` once an event named none. private var pooledDatabases: Set? = [] /// A `data` event arrived inside the window: the trailing edge tells the /// screens even when its tables map to no family (a kit table's rows, a /// Goodreads import's books), as the leading edge does. private var pooledMoved = false /// The origin of a `data` event this device's own write raised. static let writeOrigin = "write" private var trailing = false public init( core: any CottonCalling, clock: CoalesceClock = .real ) { self.core = core self.clock = clock resting = false } private init(resting core: any CottonCalling) { self.core = core clock = .real resting = true } /// The resting facts, as a model. public static func atRest(core: any CottonCalling) -> SyncModel { SyncModel(resting: core) } /// Read the status now. Called at open and after every `data` event. public func refresh() async { guard !resting else { return } guard let status = try? await core.call(CottonMethod.readSyncStatus, as: SyncStatusRead.self) else { return } apply(status) } func apply(_ status: SyncStatusRead) { connected = status.connected pendingOps = status.pending canReachServer = status.canReachServer // The not-connected answer carries no state at all, and a database with // no server is the rarer of the two — so an absent word reads as // `joined`, which is what every phone that joined a Mac has always been. serverState = status.state.flatMap(SyncServerState.init(rawValue:)) ?? .joined notConnectedReason = status.connected ? nil : status.reason // Only ever moved FORWARD by an answer that has one: a status read on a // phone that has not synced since launch carries no stamp, and letting // it clear the one a cycle just set would blank the line it wrote. if let stamp = status.lastPullAt { lastPullAt = stamp } // Taken as answered, INCLUDING a nil: a disconnected status carries no // ledger and the card draws "Checking…" for that. Holding the last one // would be a figure about a file this device can no longer read. media = status.media // The loop's slot, taken as answered for the same reason: `nil` is // "no loop is running", which a phone that just left its server or // never joined one IS, and holding an old status over it would be a // phase about a loop that is gone. loop = status.loop seen = status.seen } /// Read the status again a moment from now: the loop said something, and /// the seen line is the core's to say. Several events in that moment are /// one read. public func readSeenSoon() { seenRead?.cancel() seenRead = Task { [weak self] in try? await Task.sleep(for: .milliseconds(150)) guard !Task.isCancelled else { return } await self?.refresh() } } /// The refusal the boot read is standing on, handed down by whoever owns /// the gate. `nil` clears it — a retry that succeeded must not leave the /// banner up. public func note(_ refusal: ServerRefusal?) { self.refusal = refusal } /// Which side is on the older schema, while one is — the loop's own word, /// off the `sync` event and the cold status read. `nil` while the two /// builds agree, and `nil` with no loop at all. public var schema: SchemaStanding? { loop?.schema.flatMap(SchemaStanding.init(rawValue:)) } /// The server refuses this build's exchanges (426) because its schema is /// older than the file's: nothing moves in EITHER direction — the ops it /// would fold name columns this build cannot — until the app is updated. /// What is added still saves on this phone and queues. The one sync state /// that IS worth a warning, read as the boolean the Home banner wants: /// the loop's word first, and the boot's standing refusal for a phone /// with no file whose download was refused for the same reason. public var upgradeRequired: Bool { schema == .phoneBehind || refusal?.code == "upgrade_required" } /// The other direction: the Mac's build is older than this one, so it /// holds every write this phone offers (they queue here and go the moment /// the Mac updates) while its own writes still come down. The Home banner /// says "update the Mac" off this. public var macBehind: Bool { schema == .serverBehind } /// Run a cycle now — pull to refresh, or the button on the sync row. /// /// An explicit ask resets the failure count, because an explicit ask is not /// a retry (`sync.now`'s own rule in Rust). A RESTING model does nothing at /// all: there is no server to ask. public func syncNow() async { guard !resting else { return } _ = try? await core.call(CottonMethod.syncNow, as: JSONValue.self) await refresh() } /// The boot gate's screen changed. `.ready` — and only `.ready` — starts /// the connection. /// /// **A cold launch used to run no pull and hold no socket at all.** /// `sync.foreground` was called from ONE place: the root's /// `.onChange(of: scenePhase)`, on a view mounted after the core had been /// opened asynchronously — by which time the `.active` edge had already /// gone past. So the app ran its backoff ladder from wherever it was, held /// no live channel, and looked exactly like a phone that had lost its /// server until somebody backgrounded it and came back. /// /// The decision lives HERE rather than in the root's closure so it is one a /// test can drive: a screen becoming `.ready` is the moment there is a file /// to sync, and nothing else about the scene says that. /// /// Safe to call again — `sync.foreground` is idempotent in the crate: the /// ladder reset is a counter, and the live thread answers `running` when it /// is already up rather than starting a second one. public func bootScreenChanged(to screen: BootModel.Screen) async { guard case .ready = screen else { return } await foreground() } /// The app came forward: reset the failure count, wake the loop, open the /// socket. /// /// **Not `try?`.** `sync.foreground` and `sync.background` are the phone's /// alone and a core that does not answer them is a core this app should not /// have shipped against — a swallowed `unknown_method` here is a socket /// that never opens and a loop that never wakes, with nothing anywhere /// saying so. public func foreground() async { guard !resting else { return } await scenePhase(CottonMethod.syncForeground) await refresh() } /// The app went away: close the socket. The timer stays — iOS suspends the /// process anyway, and a socket that "survives" is one the server has /// already dropped. /// /// `budgetMs` is what is left of the time iOS gives the app in the back: /// the core's time box closes there, so the pass on the wire stops between /// pages before the freeze and is cut when the time is gone — never frozen /// mid-read to wake as a straggler. `0` cuts it now. public func background(budgetMs: Int? = nil) async { guard !resting else { return } await scenePhase(CottonMethod.syncBackground, BackgroundTime(budgetMs: budgetMs)) } /// **A complaint here is a programmer error, and it is REPORTED rather than /// asserted.** /// /// The two halves of that, decided from what can actually produce one: /// `sync.foreground` and `sync.background` answer unconditionally in Rust /// (`phone/commands.rs` — `background` cannot fail at all, and `foreground` /// only assembles what `start_live` already answered as a WORD: `off`, /// `blocked`, `running`). So the only refusal either can produce is /// `unknown_method` — this build asking a core that does not answer them — /// and the only other error is the boundary handing back something Swift /// could not decode. Neither is a runtime state a person can be in; both are /// a build that should not have shipped. /// /// Which is exactly why `assertionFailure` was the wrong tool for it. It /// crashes a DEBUG run — a simulator walk, an XCTest host — on the one class /// of fault the Release build then survives in silence, so the two builds /// disagree about the same fact and the shipping one says nothing at all. /// `Reporting` inverts that: every build behaves the same, and the build /// that matters is the one that files the event. private func scenePhase(_ method: String, _ request: BackgroundTime = BackgroundTime(budgetMs: nil)) async { do { _ = try await core.call(method, request, as: JSONValue.self) } catch let refusal as CottonCallError { let complaint = "\(method) was refused: \(refusal.code) — \(refusal.message)" Reporting.report( Report( kind: .unexpectedRefusal, message: complaint, context: ["method": method, "code": refusal.code] ) ) Log.write(complaint) } catch { let complaint = "\(method) failed: \(String(describing: error))" Reporting.report( Report( kind: .unreadableAnswer, message: complaint, context: ["method": method] ) ) Log.write(complaint) } } // MARK: - The event fan-out /// A connected or adopted copy replaces every row, including definitions. func copyReplaced() { DefinitionCatalogues.shared.invalidate(database: nil) announce(Array(ScreenFamily.allCases), toolPackages: true) } /// One event, from the app's single subscriber. public func receive(_ event: ClientEvent) { switch event { case .data(let tables, let origin, let database): if origin == Self.writeOrigin, !tables.isEmpty { localWrote = Set(InvalidationMap.families(for: tables, origin: origin)) localWrites &+= 1 // An edit of this device's own is unsent until a pass takes it: the seen line says so. readSeenSoon() } moved(tables: tables, origin: origin, database: database) case .cycle(_, _, _, let pending, let stamp): // A finished cycle already counted the outbox and stamped the // clock, so both move without a second round trip for the same // facts. pendingOps = pending if let stamp { lastPullAt = stamp } readSeenSoon() case .sync(let status): // The loop said what it is doing. Taken whole: the phase is // derived from this one object, and `pending` rides it because the // loop counts the outbox after every pass. The stamp moves forward // only, for `apply`'s reason. loop = status pendingOps = status.pending if let stamp = status.lastPullAt { lastPullAt = stamp } readSeenSoon() case .personalSignedOut, .bootstrap, .home, .arrival, .databaseSync, .personalDeleted, .personalAdoptEnded: // Signed in or out, a file opened or a copy arriving: the seen line says so now, not at its next look. readSeenSoon() case .migrate, .removed: break } } /// The `data` event moved these tables: pool them, and tell the screens /// once the window closes. /// /// **Leading AND trailing, over `COALESCE_WINDOW_MS`.** Leading, because /// the first write of a burst is the one the person is watching and a /// screen that waited 250 ms for it would feel slow. Trailing, because an /// import writes three thousand rows in a second and a redraw per batch is /// a phone that cannot be scrolled — the window collects the rest and /// tells the screens once more at the end, so nothing that moved is missed. func moved(tables: [String], origin: String? = nil, database: String? = nil) { guard !tables.isEmpty else { return } let families = InvalidationMap.families(for: tables, origin: origin) let packagesChanged = tables.contains { $0 == "cotton_tool_definitions" || $0 == "cotton_table_definitions" } // A definitions row moved: that database's catalogue is asked again at // its next read (`DefinitionCatalogues`), before any screen redraws. if tables.contains(where: DefinitionCatalogues.tables.contains) { DefinitionCatalogues.shared.invalidate(database: database) } // Rows moved that this device did not write: neither its own write // nor bytes arriving for rows it already holds. let foreign = origin != Self.writeOrigin && origin != ClientEvent.localMediaOrigin let databases: Set? = database.map { [$0] } if trailing { pooledMoved = true pooled.formUnion(families) pooledToolPackages = pooledToolPackages || packagesChanged pooledForeign = pooledForeign || foreign pooledDatabases = Self.union(pooledDatabases, databases) return } // Leading: this one goes out now. trailing = true announce(families, toolPackages: packagesChanged, foreign: foreign, databases: databases) Task { @MainActor in await clock.wait(COALESCE_WINDOW_MS) self.trailing = false let waiting = self.pooled let packages = self.pooledToolPackages let foreign = self.pooledForeign let databases = self.pooledDatabases let moved = self.pooledMoved self.pooled = [] self.pooledToolPackages = false self.pooledForeign = false self.pooledDatabases = [] self.pooledMoved = false // Rows moved inside the window: said, whatever families they // reach. A burst's tail whose tables map to none (an import's // books landing 40 ms after the write that opened the window) // was dropped, and the fan's tile counts, read again only on // `revision`, stood stale while the deck showed the books (Books // 1.0.0 (3) and (4) walks, 7 Nov 2026). guard moved else { return } self.announce(Array(waiting), toolPackages: packages, foreign: foreign, databases: databases) await self.refresh() } } /// Two sets of databases pooled together; `nil` (every database) wins. private static func union(_ a: Set?, _ b: Set?) -> Set? { guard let a, let b else { return nil } return a.union(b) } /// Whether the last announcement concerns a window showing `shown`. /// /// One database is shown per window, and an event names the database its /// tables moved in: a window showing another is not re-read for it. A /// screen that reads ACROSS databases (Today, search, "Asked of you"), a /// window whose database is not known yet, and an event that named none /// are always reached — a missed re-read draws stale rows, an extra one /// costs a read. public func reaches(shown: String?, acrossDatabases: Bool = false) -> Bool { guard !acrossDatabases, let shown, let databases = invalidatedDatabases else { return true } return databases.contains(shown) } /// Re-read `model` for the last announcement, if it reaches the window /// showing `shown` — the one call `.rereading` makes. @discardableResult public func reread( _ model: some Rereadable, in shown: String?, acrossDatabases: Bool = false ) -> Task? { guard reaches(shown: shown, acrossDatabases: acrossDatabases) else { return nil } return model.reread(invalidated) } /// Say what moved, and say that it moved. /// /// The ONE writer of both fields, so they can never disagree: a screen that /// woke on `revision` and read a stale `invalidated` would re-read the /// wrong families, which is worse than not waking at all. private func announce( _ families: [ScreenFamily], toolPackages: Bool = false, foreign: Bool = true, databases: Set? = nil ) { invalidating?(families) invalidatedDatabases = databases invalidated = families revision &+= 1 if foreign { foreignRevision &+= 1 } if toolPackages { toolPackagesRevision &+= 1 } if families.contains(.storage) { mediaEpoch &+= 1 } } } /// The coalescing window's own clock, injected. /// /// The repo's rule is dates through a seam and never the wall clock; a delay is /// the same rule. `.instant` is what lets a test assert that the window /// COLLECTS rather than that it takes a quarter of a second. public struct CoalesceClock: Sendable { public var wait: @Sendable (Int) async -> Void public init(wait: @escaping @Sendable (Int) async -> Void) { self.wait = wait } public static let real = CoalesceClock { milliseconds in try? await Task.sleep(nanoseconds: UInt64(max(0, milliseconds)) * 1_000_000) } public static let instant = CoalesceClock { _ in await Task.yield() } } // MARK: - Handed down to the screens that re-read on a fold /// The sync model a pushed screen watches. /// /// A screen with a `noticed(_:)` seam has to be TOLD when a fold landed, and it /// cannot be on `RootView`'s subscribe fan-out the way `HomeModel` and the two /// reconcilers are: those live as long as the app and a screen is pushed and /// popped. So the model is handed down and the screen watches `revision`. /// /// **`revision`, never `invalidated`.** `onChange` fires on a change of VALUE, /// so two folds carrying the same tables set the same list twice and the second /// wakes nothing. The counter moves either way, and `invalidated` is read when /// it does. /// /// Optional, with no default to fall back to: a screen rendered outside the app /// — a preview, a gallery specimen — has no sync loop, and inventing an empty /// one would be a model that reports "nothing has changed" for ever, which is a /// lie a screen cannot tell apart from the truth. private struct CottonSyncKey: EnvironmentKey { static let defaultValue: SyncModel? = nil } extension EnvironmentValues { public var cottonSync: SyncModel? { get { self[CottonSyncKey.self] } set { self[CottonSyncKey.self] = newValue } } } /// What `sync.background` is told: the background time left, if the platform /// says (`sync.foreground` is sent it empty). struct BackgroundTime: Encodable, Sendable { let budgetMs: Int? }