// THE CONTRACT, in one file: every method name this app asks for and every // event payload it reads. // // The ABI is six C functions and no seventh, so a capability is a METHOD NAME // inside `cotton_call` — which means the names ARE the surface between the two // halves of sub-step 4b, and a typo in one of them is an `unknown_method` at // runtime rather than a compile error. // // **Every shape below is read off the Rust worktree, not off the brief.** The // first cut of this file was written to the design note; the two disagreed in // six places and the app was wrong in all six — a paired phone never left Join, // the digits pane was unreachable, and Home painted over a replica that did not // exist. So the rule from here is the one the code already implies: where the // brief and `crates/cotton-ffi` disagree, the crate wins and // the comments here say the REAL shape. `BoundaryContractTests` reads those // files by path and fails loudly, so this file cannot drift back. // // The tables, as the crate declares them // (`methods.rs::CLIENT_METHODS`, `phone/commands.rs`, // `phone/reads.rs`): // // | Method | Answers | Called by | // |---|---|---| // | `read.boot` | `{paired, stage, ownerId, workspaceId, serverUrl, serverName, refusal}` — the FILES, never an attach | the gate's first question | // | `read.syncStatus` | the sync surface, through the controller — `connected` IS the gate's "is there a file?", and `loop` is what the sync loop is doing | `SyncModel`, and the gate's SECOND question | // | `read.devices` | `{devices, thisDevice}` — every device admitted, off the FILE (`SettingsMethods.swift`) | `DevicesModel`, Home's device line | // | `sync.now` | a WHOLE cycle: `{pushed, pulled, behind, pending, lastPullAt}` | pull-to-refresh | // | `sync.foreground` / `.background` | `{socket, sync}` / `{socket:"off"}` | the scene phase | // | `workspace.startLocal` | `{workspaceId, ownerId, deviceId, mode, state}` — a database on THIS device | the first screen's Start | // | `bootstrap.start` | `{started:true, alreadyRunning}` AT ONCE — never the outcome | the gate | // | `bootstrap.status` | `{running, ready, bytesWritten?, totalBytes?, failed?}` | the gate | // | `migrate.status` | the ladder's plan, or `{running:false}` | the gate | // | `write` | `{answer, rail, queued, tables, tool}` — queued, never pushed: the push is the sync loop's | every screen that writes | // | `routes.list` | `{routes, count, pushTypes, pushTypesUnmapped}` | `RouteTableTests` | // // **Decoding is deliberately generous.** Every field below is optional or has a // default, and nothing throws on a shape it does not recognise: the crate may // land a field before this app reads it, and an app that refused to boot on an // unknown key would be a phone bricked by a core it links in the same binary. // What is NOT generous is the codes — a refusal code is a wire string a screen // keys on, and an unrecognised one is surfaced, never smoothed. And generosity // is exactly why the by-path guard exists: a renamed field degrades to a // default here, silently, which is how the six defects above were invisible. import Foundation /// Every method name, said once. /// /// `BoundaryContractTests` holds each of these against the crate's own tables, /// so a name here that no build answers is a red test rather than a runtime /// `unknown_method`. There are no exceptions left: both Rust halves have /// landed, and every name below is one the crate answers today. public enum CottonMethod { public static let usageRecord = "usage.record" /// Cotton Keys' passkey provider, drained by the app (`PasskeyArrivals`): /// a registration sealed into a row, a use counted, the rows as /// identities, and the scalars of rows this phone's keychain lacks. public static let passkeyRegister = "passkey.register" public static let passkeyUsed = "passkey.used" public static let passkeyIdentities = "passkey.identities" public static let passkeyMirror = "passkey.mirror" /// A Credential Exchange export handed over by another app (`PasskeyImport`). public static let passkeyImportCxf = "passkey.importCxf" /// Cotton Keys' passwords (`phone::passwords`): the list without values, /// a reveal on an open vault, add, change, remove, the generator and /// Apple Passwords' CSV; and for its provider (`PasswordArrivals`) a /// site's save, a fill's use, and the keychain copy kept fresh. public static let passwordList = "password.list" public static let passwordReveal = "password.reveal" public static let passwordAdd = "password.add" public static let passwordChange = "password.change" public static let passwordRemove = "password.remove" public static let passwordGenerate = "password.generate" public static let passwordImportCsv = "password.importCsv" public static let passwordSave = "password.save" public static let passwordUsed = "password.used" public static let passwordMirror = "password.mirror" public static let readRecentVisits = "read.recentVisits" public static let recordsList = "records.list" /// `shell.fan {chosen, tool, timezone}` — everything the fan draws: its /// tiles in its order, each with its views in the ring's order (the /// tile the fan stands on counted), where it opens and its first tier. public static let shellFan = "shell.fan" /// `shell.stream {table, query?, ink?, standing?}` — an app whose face is /// one stream of its conversations (Cotton Messages): the chats in the /// stream's order (unread first, then newest), the unread count's line, /// each chat's mark, which take a reply, and what the top button holds. public static let shellStream = "shell.stream" /// `shell.deck {table, view?, where?, cursor?, limit?, ink?, visitor?, /// holding?, timezone}` — a page of the deck, answered whole: the cards /// in the view's order, each worn, filled, placed and tap-mapped, with the /// view's head, the empty words, the hand and what Plus does. public static let shellDeck = "shell.deck" /// `shell.list {table, view?, where?, query?, archived?, section?, pick?, /// cursor?, limit?, timezone, today?}` — a page of a scrolling list, /// answered whole: its sections and rows with their words, acts, menu, /// links, groups, index, filter, empty words, clear and Select. public static let shellList = "shell.list" /// `shell.plus {table, view?}` — what a table's "+" does: its doors, its /// act at the object, its route, or a blank record. public static let shellPlus = "shell.plus" /// `shell.draft {table, values} | {id, stage}` — a card not yet made, /// kept by the core until its one create lands: every choice staged on /// it, and the card it wears, resolved from its values as a made one's is. public static let shellDraft = "shell.draft" /// `shell.input {op: ask | commit, …}` — what an input writes: the editor /// a write stands in and its words, then what a commit wrote, or why not. public static let shellInput = "shell.input" /// `tools.act {tool, act, account?}` — one of a tool's own acts, offered /// on its held cards (`shell.opened`, kind `tool`): Connect Google /// Calendar answers `{opens}`, the page the phone opens in the browser. public static let toolsAct = "tools.act" /// `tools.acts {table}` — `{actions}`, the acts of the tools owning the /// table that stand now, as `shell.opened` ranks them among a card's: /// a deck holding no card offers them on its empty placeholder's fan. public static let toolsActs = "tools.acts" /// `shell.opened {table, id | draft, view?, face?, step?}` — the held /// card answered whole: `{acts}`, ranked and flagged, or with `step` /// that step's `{step: {kind, rows}}` (No date and the days, the times, /// the repeats, the statuses). The shell draws it and decides none of it. public static let shellOpened = "shell.opened" /// `send.*` — Send, a copy of a record to one of the person's people /// (`crates/cotton-ffi/src/phone/cotton_send.rs`): the object decides /// what goes, to whom and what fits; each answer carries the words its /// card says (`shows`). `send.make {table, id, thread}` → `{id, receipt}`. public static let sendMake = "send.make" /// `send.inbox {}` → `{in, out, landed}`: what arrived and what was sent, each kept as its thread's item. public static let sendInbox = "send.inbox" /// `send.keep {id}` → `{state: kept|keeping, landed?, copied?, shows}`. public static let sendKeep = "send.keep" /// `send.decline {id}` → `{ok}`: the offer goes, and its thread item. public static let sendDecline = "send.decline" /// `send.undo {id}` → `{removed, state?, shows}`: a send made is taken back; one kept has what it brought removed. public static let sendUndo = "send.undo" /// `send.trust {number, trusted}` → `{ok}`: every send from them is kept as it arrives. public static let sendTrust = "send.trust" /// `send.picture {id, key, dir}` → `{path}`: a picture an offer names, fetched before Keep. public static let sendPicture = "send.picture" /// `shell.reader {book, at?, dark?}` — the open book answered whole: its /// file and format, where it opens, the bar's words, the face worn and /// the knobs, the fan's tiers, the highlights, or the line said in its /// place (a locked book). The reader draws it and decides none of it. public static let shellReader = "shell.reader" /// `shell.player {op?, table?, id?, at_s?, rate?, minutes?, settings?, /// face?, listened?}` — the one player answered whole: `now` (a song, its /// file and gain; an episode or a film, what it plays from, where it /// starts, its skip, its report cadence, its tracks), the `queue` after /// it, `at`, the seconds past which a play is `played_after_s`, the /// `settings`, the `face` worn and the hand's `faces`, the `words` drawn /// when nothing plays, and a `refusal`. The instrument plays it and /// decides none of it. public static let shellPlayer = "shell.player" /// `reader.moved {book, at?, page_label?, contents?, active, closing?}` — /// where the page stands; the core writes the place when its rule says /// (`{at, progress_words, wrote, again_ms}`). public static let readerMoved = "reader.moved" /// `reader.highlight {book, at, pencil?, words, note?} | {id, pencil?, /// note?} | {id, remove}` — a highlight made, changed or removed. public static let readerHighlight = "reader.highlight" /// `reader.settings {face | knob + value, dark?}` — a face or a knob /// chosen, written to the reader's face choice: `{settings, fan}`. public static let readerSettings = "reader.settings" /// `reader.seek {book}` — the seek line at the page's edge: `{here, ticks, /// pages, back, words, steps}`. public static let readerSeek = "reader.seek" /// `reader.seek.say {book, at}` — the slip's words for a dragged place. public static let readerSeekSay = "reader.seek.say" /// `reader.seek.go {book, at, width?} | {book, tick}` — a jump: the /// Locator to go to and the Back it leaves. public static let readerSeekGo = "reader.seek.go" /// `reader.seek.back {book}` — the Back place's Locator; Back is cleared. public static let readerSeekBack = "reader.seek.back" public static let cardsRepeat = "cards.repeat" /// The one write of a card's when that keeps the half it is not given /// (lane package, e57b88262; `DeckEditor.writeWhen`). public static let cardsWhen = "cards.when" /// `definitions.theme` — what a database wears: `{definition, /// passed_over}`, the shipped `paper` when it has no row of its own. public static let definitionsTheme = "definitions.theme" /// `definitions.catalogue` — every definition a database draws, as the /// core resolved and decoded them: `{shape, revision, tables, refused, /// fell_back, kept_as_rows, boards, theme, themes, database}` — only the tables its /// definition rows describe, a row with no face named in `kept_as_rows` /// instead; `{shipped: true}` answers the last resort, this build's /// boards and themes and no table (`DefinitionCatalogues`). public static let definitionsCatalogue = "definitions.catalogue" /// The app's own words, one set at a time (`ShellLines`). public static let shellLines = "shell.lines" /// A count as the core says it (`CountLines`). public static let countWords = "count.words" public static let cardsPages = "cards.pages" /// The birthdays coming round today and in the days after, soonest first /// (`cards.birthdays`, package row 8). public static let cardsBirthdays = "cards.birthdays" /// The money due in the same days: expected transactions on their day, /// active subscriptions on their next charge (`cards.moneyDue`). public static let cardsMoneyDue = "cards.moneyDue" /// `definitions.passedOver` — a board part this build does not draw, filed /// as ONE Feedback row per (database, board, part), ever: /// `{board, part, databaseId, databaseName}` → `{filed}`. A person method: /// it writes the personal database whichever database is named. public static let definitionsPassedOver = "definitions.passedOver" /// `definitions.saveTheme {definition}` — the database wears this theme: /// written as its own row, refused when this build cannot draw it, /// answered with the receipt and the undo that puts back what was worn. public static let definitionsSaveTheme = "definitions.saveTheme" /// `definitions.saveTable {table, : value, …}` — a table edited from /// its tool's page: its own columns (shipped ones hidden, never retyped), /// its look, its acts and its stacks. It is `update_definition`, answered /// with the receipt and the undo that puts back what was drawn. public static let definitionsSaveTable = "definitions.saveTable" /// `records.summarize` — a table's tile figures, computed by the core. public static let recordsSummarize = "records.summarize" public static let recordsGet = "records.get" /// `records.undo {change_id}` — a change taken back, a receipt's Undo. public static let recordsUndo = "records.undo" /// `groups.*` — a table's hand-picked groups (Spec 6): listed with the top /// of each, made, changed one thing at a time, and deleted. public static let groupsList = "groups.list" public static let groupsCreate = "groups.create" public static let groupsUpdate = "groups.update" public static let groupsDelete = "groups.delete" /// Cinemas' streaming screens (assets/design/cinemas/CONTRACT-2.md; crates/cotton-ffi/src/phone/cinemas_home.rs). public static let cinemasHome = "cinemas.home" public static let cinemasRow = "cinemas.row" public static let cinemasTitle = "cinemas.title" public static let cinemasSeason = "cinemas.season" public static let cinemasSearch = "cinemas.search" public static let cinemasKind = "cinemas.kind" public static let cinemasGroups = "cinemas.groups" public static let cinemasGroupsOrder = "cinemas.groupsOrder" public static let cinemasOnPhone = "cinemas.onPhone" public static let cinemasSubtitles = "cinemas.subtitles" public static let cinemasPreparing = "cinemas.preparing" public static let cinemasRemote = "cinemas.remote" public static let cinemasToEpisode = "cinemas.toEpisode" public static let cinemasBin = "cinemas.bin" public static let cinemasYou = "cinemas.you" /// Hidden (CONTRACT-2 HIDDEN): hide a category or stop; the hidden place; the core's unlock, asked only after the /// phone's lock passed, and its lock. public static let cinemasHide = "cinemas.hide" public static let cinemasHidden = "cinemas.hidden" public static let cinemasUnlock = "cinemas.unlock" public static let cinemasLock = "cinemas.lock" public static let cinemasSetting = "cinemas.setting" public static let cinemasRestore = "cinemas.restore" public static let filmsSubtitleFile = "films.subtitleFile" /// `phrase.parse` — the one input's words read by the core's phrase /// parser (`CorePhraseParser`). public static let phraseParse = "phrase.parse" public static let readBoot = "read.boot" public static let readSyncStatus = "read.syncStatus" public static let syncNow = "sync.now" public static let syncForeground = "sync.foreground" public static let syncBackground = "sync.background" /// `sync.compact` — the copy's one whole compaction after a trim, run in /// a processing task's time (`{ budgetMs }`) or stopped (`{ stop: true }`). public static let syncCompact = "sync.compact" /// `sync.rejected` — the writes a peer made that this device would not /// fold, parked rather than dropped. public static let syncRejected = "sync.rejected" /// `sync.retryRejected` — offer the parked writes to the fold again. public static let syncRetryRejected = "sync.retryRejected" /// `workspace.startLocal {name?, deviceName?, platform?, appVersion?}` → /// `{workspaceId, ownerId, deviceId, mode, state}`. /// /// **Start, the other half of the first screen.** A fresh phone used to /// have one verb — Join — because a database was born on a Mac and iOS /// links no server, so nothing could be written down until there was a Mac /// in the room. This mints the workspace on THIS phone: a replica, the /// store's birth rows, this device in its own device list, and a /// connection record in `local` mode. /// /// **Nothing listens.** No server, no registry, no address — the answer's /// `state` is `noServerYet`, which the app renders as "No Mac yet", and it /// ends when a Mac joins. `already_started` is the refusal over a database /// this phone is already holding. /// /// The crate emits the same `{phase:"bootstrap", stage:"ready"}` frame a /// download ends with, because it is the same fact: there is a file and /// the app may open on it. public static let workspaceStartLocal = "workspace.startLocal" public static let write = "write" public static let routesList = "routes.list" } /// `read.boot` — the gate's FIRST question, answered BEFORE any replica exists. /// /// A `Controller` read: a phone with no server, no file and no device key still /// has to draw something, and "not connected" is a fact rather than an error. /// The source is `client/connection.json` and `client/refusal.json` — **never /// the network and never the replica**, so a phone with no server reaches Join /// in one frame and a phone WITH one leaves Join in one frame. /// /// **It no longer answers `open`, and that is the repair.** It used to ask /// `sync_status`, which attaches — a SQLite open, and after a force-quit an /// open that pays the whole write-ahead log's recovery on a boundary that /// answers one call at a time. `BootModel` read it under a five-second ceiling /// and, past the ceiling, resolved "nobody is here": the Join screen, on a /// phone whose server still listed it as approved. Whether the file is open is /// `read.syncStatus`'s `connected`, asked separately and waited for as long as /// it takes. /// /// `phone/reads.rs::boot` is the whole shape and every field here is one of /// its. `stage` is the crate's own name for what the FILES resolved, and the /// app maps it to a screen: the core names no route. public struct BootRead: Decodable, Equatable, Sendable { /// `connection.json` names a workspace. THE gate signal — everything else /// is downstream of it, which is why the crate puts it first too. /// /// `ownerId` is NOT this question: a stored connection can carry a null /// owner id, and gating on it would leave a paired phone in Join for ever. public var paired: Bool /// What the core resolved FROM THE FILES, as a NAME rather than a route: /// `"refused"` · `"pairing"` · `"joined"`. /// /// `"ready"` and `"bootstrap"` are not among them on purpose: they are the /// OPEN's two words, and the open is `read.syncStatus`'s `connected` to /// answer. public var stage: String /// The `ownerId` of the cached `/v1/me` answer, or `nil` when the join /// stored none. Shown, never gated on. public var ownerId: String? public var workspaceId: String? /// The address this phone learned by joining, for a refusal's pre-fill. /// `connection.json`'s `base_url`. public var serverUrl: String? /// The short relay name that address stands for, when it is a relay one. /// `cotton_core::device::pairing::relay_name_of`, never sliced in Swift. public var serverName: String? /// A terminal device refusal the transport is already standing on. public var refusal: BootRefusal? /// `{code, sentence, serverUrl, serverName, at, erase}` — the crate builds /// the sentence too (`connection::terminal_device_sentence`); this app keeps /// its own copy for the screen and reads only the code, the address and the /// flag below. public struct BootRefusal: Decodable, Equatable, Sendable { public var code: String public var sentence: String? public var serverUrl: String? public var serverName: String? public var at: String? /// Did the server ask this device to ERASE ITSELF rather than to stop? /// /// `DELETE /v1/devices/approved/{id}` with `{"erase": true}` files the /// row as erased, and the chokepoint's `403 device_revoked` then carries /// `erase: true` — so the first request this device makes after somebody /// wiped it from another device is the request that tells it. /// /// It changes what a screen OFFERS, not what it decides: `false` draws /// two verbs and asks, `true` takes the second one without asking, /// because the owner already answered on the device they revoked this /// one from. **Absent reads as `false`, because the safe reading is the /// one that asks.** public var erase: Bool? public init( code: String, sentence: String? = nil, serverUrl: String? = nil, serverName: String? = nil, at: String? = nil, erase: Bool? = nil ) { self.code = code self.sentence = sentence self.serverUrl = serverUrl self.serverName = serverName self.at = at self.erase = erase } } public init( paired: Bool = false, stage: String = "pairing", ownerId: String? = nil, workspaceId: String? = nil, serverUrl: String? = nil, serverName: String? = nil, refusal: BootRefusal? = nil ) { self.paired = paired self.stage = stage self.ownerId = ownerId self.workspaceId = workspaceId self.serverUrl = serverUrl self.serverName = serverName self.refusal = refusal } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) paired = (try? container.decode(Bool.self, forKey: .paired)) ?? false stage = (try? container.decode(String.self, forKey: .stage)) ?? "pairing" ownerId = try? container.decode(String.self, forKey: .ownerId) workspaceId = try? container.decode(String.self, forKey: .workspaceId) serverUrl = try? container.decode(String.self, forKey: .serverUrl) serverName = try? container.decode(String.self, forKey: .serverName) refusal = try? container.decode(BootRefusal.self, forKey: .refusal) } /// The address this phone joined. `connection.json`'s `base_url`, and the /// only copy that survives a leave. public var address: String? { serverUrl } private enum CodingKeys: String, CodingKey { case paired, stage, ownerId, workspaceId, serverUrl, serverName, refusal } } public struct SyncStatusRead: Decodable, Equatable, Sendable { public var connected: Bool /// A sentence, when there is no file. Shown as written, never mapped to a /// refusal code — the controller does not put one here. public var reason: String? public var workspaceId: String? /// `"remote"` on a phone, always. `embedded` is the Mac's. public var mode: String? public var baseUrl: String? /// Where the file is. For the transparency line, never opened in Swift. public var replica: String? /// Local writes that have not reached the server: the queue and the /// writes held for the Mac's time alike. public var pending: Int /// Of `pending`, the writes made before this device had the Mac's time /// this launch, held until an answer gives it. public var heldWrites: Int? /// Whether a transport exists at all. `NO_TRANSPORT` must be impossible on /// a phone that has joined. public var canReachServer: Bool /// ISO-8601 UTC. `nil` until a pass has actually reached the server. public var lastPullAt: String? /// `"joined"` or `"noServerYet"` — is there anything to sync WITH. /// /// **Absent only on the `{connected: false, reason}` shape**, which /// carries no state because there is no file to have one. A /// device that pressed *Start* holds a database of its own and no server /// has joined it (Cotton note "Server address — how a device knows which server holds its data"); the crate answers /// `noServerYet` and the app renders it as "No Mac yet". Whether a pass is /// in flight right now is the `cycle` event's business — this answers the /// question before it. public var state: String? /// The `_media` ledger — THIS device's, never the workspace's — because /// "Sync & backup" draws two cards and the second one is bytes. /// /// Extended here by 4h rather than added as a second read: `SyncModel` /// already derives the live banner from this one answer, and two reads /// would be two chances to disagree about one banner. `nil` on the /// `{connected:false}` shape, which carries no ledger at all. The shape /// itself is `Boundary+4h.swift`'s. public var media: MediaActivityRead? /// What the sync LOOP is doing right now, for a reader that was not /// listening when it last said so — the same object the `client` stream /// carries as `phase: "sync"` (`SyncLoopRead`). /// /// `nil` while no loop runs: a local database, the served Mac, a /// controller that has not attached one yet. **`nil` is "nothing in /// flight", never "reachable"** — `connected` says the FILE is open, and /// only a pass that reached the server says the server is there /// (`SyncModel.live`). public var loop: SyncLoopRead? /// How far THIS file's mail search index is filled while it fills in the /// background (mailsearch, v122); `nil` once it is whole, and on a file /// that cannot say. public var searchIndex: SearchIndexFill? /// Where this database's sync stands, in the engine's words /// (`DatabaseSyncLine`) — what the page's top and the device row say; /// `nil` on the `{connected:false}` shape. public var sync: DatabaseSyncLine? /// The same for every database a pass has reported on, by database id — /// what the Databases sheet's caps start from before a pass ends. public var syncs: [String: DatabaseSyncLine] /// The way this device last reached its Mac, in the engine's words — /// "home network", "Tailscale", "over the relay"; `nil` before any /// request has got through, and on a Mac that serves. public var route: String? /// The one quiet line every app's home draws about its sync /// (`shell_account::seen_of`, the line `shell.home` gives Android). public var seen: SyncSeenRead? public init( connected: Bool = false, reason: String? = nil, workspaceId: String? = nil, mode: String? = nil, baseUrl: String? = nil, replica: String? = nil, pending: Int = 0, canReachServer: Bool = false, lastPullAt: String? = nil, state: String? = nil, media: MediaActivityRead? = nil, loop: SyncLoopRead? = nil, searchIndex: SearchIndexFill? = nil, sync: DatabaseSyncLine? = nil, syncs: [String: DatabaseSyncLine] = [:], route: String? = nil, seen: SyncSeenRead? = nil ) { self.connected = connected self.reason = reason self.workspaceId = workspaceId self.mode = mode self.baseUrl = baseUrl self.replica = replica self.pending = pending self.canReachServer = canReachServer self.lastPullAt = lastPullAt self.state = state self.media = media self.loop = loop self.searchIndex = searchIndex self.sync = sync self.syncs = syncs self.route = route self.seen = seen } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) connected = (try? container.decode(Bool.self, forKey: .connected)) ?? false reason = try? container.decode(String.self, forKey: .reason) workspaceId = try? container.decode(String.self, forKey: .workspaceId) mode = try? container.decode(String.self, forKey: .mode) baseUrl = try? container.decode(String.self, forKey: .baseUrl) replica = try? container.decode(String.self, forKey: .replica) pending = (try? container.decode(Int.self, forKey: .pending)) ?? 0 canReachServer = (try? container.decode(Bool.self, forKey: .canReachServer)) ?? false lastPullAt = try? container.decode(String.self, forKey: .lastPullAt) state = try? container.decode(String.self, forKey: .state) media = try? container.decode(MediaActivityRead.self, forKey: .media) loop = try? container.decode(SyncLoopRead.self, forKey: .loop) searchIndex = try? container.decode(SearchIndexFill.self, forKey: .searchIndex) sync = try? container.decode(DatabaseSyncLine.self, forKey: .sync) syncs = (try? container.decode([String: DatabaseSyncLine].self, forKey: .syncs)) ?? [:] route = try? container.decode(String.self, forKey: .route) seen = try? container.decode(SyncSeenRead.self, forKey: .seen) } private enum CodingKeys: String, CodingKey { case connected, reason, workspaceId, mode, baseUrl, replica, pending, canReachServer case lastPullAt, state, media, loop, searchIndex, sync, syncs, route, seen } } /// `sync.status`'s `seen` (`shell_account::seen_of`): the state, its line in the /// shell's words, what VoiceOver says once when it changes, and how long a /// pass must have run (`since`) before catching up is shown. public struct SyncSeenRead: Decodable, Equatable, Sendable { /// `signed_out`, `alone`, `offline`, `copy_coming`, `catching_up`, /// `sending`, `up_to_date` or `not_yet`. public var state: String public var line: String public var spoken: String public var showAfterMs: Int /// When the pass on the wire began, epoch ms, while one runs. public var since: Double? public var percent: Int? public init(state: String, line: String, spoken: String, showAfterMs: Int = 1_000, since: Double? = nil, percent: Int? = nil) { self.state = state self.line = line self.spoken = spoken self.showAfterMs = showAfterMs self.since = since self.percent = percent } /// A pass is running and the line counts it as catching up. public var catchingUp: Bool { state == "catching_up" || state == "copy_coming" } } /// `read.syncStatus`'s `searchIndex`: `{filled, total}` mail rows of the /// search index this file is filling a slice at a time. public struct SearchIndexFill: Decodable, Equatable, Sendable { public var filled: Int public var total: Int public init(filled: Int, total: Int) { self.filled = filled self.total = total } } /// The sync loop's own status — `cotton_client::sync::SyncStatus`, exactly. /// /// It reaches the app two ways and this is the one shape for both: on the /// `client` stream tagged `phase: "sync"` (`ClientEvent.sync`), every time the /// loop publishes — a pass starting, a pass finishing, a backoff scheduled, a /// terminal refusal — and under `read.syncStatus`'s `loop` for a cold read. /// /// **`state` is the crate's word and is kept as a string**, decoded /// generously like every other field here; `SyncModel` is what turns it into /// a phase, and an unknown word there reads as "nothing in flight" rather /// than as an error. The four today are `idle`, `syncing`, `waiting` (a /// backoff, not an idle) and `stopped`. /// /// `lastError` is the crate's own sentence about the last failure and is /// shown as written. `nextAttemptAt` is ISO-8601, present while the loop is /// waiting AND while a pass is in flight (the ceiling's own promise). /// `stoppedReason` is present only when the loop stopped on its own — a /// refusal of this device no retry can change — and never after a person's /// own stop. public struct SyncLoopRead: Decodable, Equatable, Sendable { public var state: String public var pending: Int public var lastPullAt: String? public var lastPushAt: String? public var lastError: String? /// Consecutive failures — what the backoff ladder is climbing. public var failures: Int public var nextAttemptAt: String? public var stoppedReason: String? /// The server's code behind `stoppedReason` — `device_revoked` and its /// siblings — so the boot gate can place the refusal (wall or banner) /// without parsing a sentence. public var stoppedCode: String? /// Which side is on the older schema, while one is — the crate's word /// (`phoneBehind`, `serverBehind`), kept as a string like `state` and /// turned into a case by `SyncModel`. Absent when the two builds agree. /// Never a stop: the file is open, writes land here and queue, and the /// loop keeps trying; this is the ONE fact Home's update slip is drawn /// off. public var schema: String? /// How many changes the serving Mac said still wait for this device after /// the last pass that reached it — what remains, never what moved, and /// counted in full. The device row's figure; the home says a percent of /// it in the engine's words. Absent until a Mac that counts has answered. public var behindBy: Int? /// Why the serving Mac could not wake this device the last time it tried /// (the catch-up wake), in the Mac's own sentence. Absent once a wake /// went, or when none was needed. public var wakeRefusal: String? public init( state: String, pending: Int = 0, lastPullAt: String? = nil, lastPushAt: String? = nil, lastError: String? = nil, failures: Int = 0, nextAttemptAt: String? = nil, stoppedReason: String? = nil, stoppedCode: String? = nil, schema: String? = nil, behindBy: Int? = nil, wakeRefusal: String? = nil ) { self.state = state self.pending = pending self.lastPullAt = lastPullAt self.lastPushAt = lastPushAt self.lastError = lastError self.failures = failures self.nextAttemptAt = nextAttemptAt self.stoppedReason = stoppedReason self.stoppedCode = stoppedCode self.schema = schema self.behindBy = behindBy self.wakeRefusal = wakeRefusal } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) // The one field that HAS to be there: a status with no state word is // not a status, and decoding it as one would paint "idle" over a frame // that said nothing. state = try container.decode(String.self, forKey: .state) pending = (try? container.decode(Int.self, forKey: .pending)) ?? 0 lastPullAt = try? container.decode(String.self, forKey: .lastPullAt) lastPushAt = try? container.decode(String.self, forKey: .lastPushAt) lastError = try? container.decode(String.self, forKey: .lastError) failures = (try? container.decode(Int.self, forKey: .failures)) ?? 0 nextAttemptAt = try? container.decode(String.self, forKey: .nextAttemptAt) stoppedReason = try? container.decode(String.self, forKey: .stoppedReason) stoppedCode = try? container.decode(String.self, forKey: .stoppedCode) schema = try? container.decode(String.self, forKey: .schema) behindBy = try? container.decode(Int.self, forKey: .behindBy) wakeRefusal = try? container.decode(String.self, forKey: .wakeRefusal) } /// Off an event payload, by the same rule as the decoder above: no /// `state`, no status. public static func of(_ payload: JSONValue) -> SyncLoopRead? { guard let state = payload["state"]?.string, !state.isEmpty else { return nil } return SyncLoopRead( state: state, pending: payload["pending"]?.int ?? 0, lastPullAt: payload["lastPullAt"]?.string, lastPushAt: payload["lastPushAt"]?.string, lastError: payload["lastError"]?.string, failures: payload["failures"]?.int ?? 0, nextAttemptAt: payload["nextAttemptAt"]?.string, stoppedReason: payload["stoppedReason"]?.string, stoppedCode: payload["stoppedCode"]?.string, schema: payload["schema"]?.string, behindBy: payload["behindBy"]?.int, wakeRefusal: payload["wakeRefusal"]?.string ) } private enum CodingKeys: String, CodingKey { case state, pending, lastPullAt, lastPushAt, lastError, failures, nextAttemptAt case stoppedReason, stoppedCode, schema, behindBy, wakeRefusal } } /// What a `client` or `data` event is saying. /// /// One channel carries the download's figure, the /// migration's steps and the cycle's counts, keyed by `phase` — except the /// cycle, which carries none. An event with a `phase` this app does not know is /// DROPPED: the core may be one build ahead, and an unknown frame has never /// been a reason to stop. public enum ClientEvent: Equatable, Sendable { /// `{phase:"migrate", stage:"start"|"step"|"done"|"failed", …}` — /// `migration_json`, plus the `failed` frame the bootstrap thread emits /// when the ladder is what refused. **`done` is the LADDER's terminal /// word** — the bootstrap's is `ready`, one case below. case migrate(stage: String, from: Int?, to: Int?, index: Int?, total: Int?, version: Int?, message: String?) /// `{phase:"bootstrap", stage:"ready"|"failed", …}`. /// /// **The terminal stage is `ready`, and `done` is the MIGRATE phase's.** /// `bootstrap.start` returns AT ONCE, so its return cannot be the /// completion — this event is, and it is the only thing that opens the /// gate. The two words are one letter apart in a screen's mind and a whole /// boot apart in behaviour: a gate keyed on `done` never opens, because the /// bootstrap thread never says it. `bootstrap.status` answers `ready: true` /// for the same fact, for a screen that missed the event. case bootstrap(stage: String, workspaceId: String?, code: String?, message: String?, retryable: Bool?) /// `{phase:"personal", stage:"signed_out", code, message}` — the owner's /// personal object answered a sync 401: it no longer takes this phone's /// credential (`crates/cotton-ffi/src/phone/personal_object.rs`). Said /// once per credential; the copy stays. case personalSignedOut(code: String) /// `{phase:"personal", stage:"signed_out", code:"account_deleted", deleted:true, words:{heading, line}}` — the /// account was deleted from another phone or cottondb.com/delete (a 410 at this phone's pass): nothing of it /// stays here (assets/design/shared/DELETE_ACCOUNT.md "Deleted elsewhere"). `line` is said once. case personalDeleted(line: String?) /// `{phase:"personal", stage:"adopted"|"adopt_failed", code?}` — the /// adopt bringing a used local database into the object ended /// (`crates/cotton-ffi/src/phone/adopt.rs`); `personal.adoptStatus` /// says how. case personalAdoptEnded /// `{phase: home}` — the gate moved: the open ended (`opened`), or the /// once-a-second tick while it waits (`tick`). Ask `shell.home` again. case home(stage: String) /// `{phase:"arrival", stage, workspaceId, bytesWritten?, totalBytes?, /// reason?}` — where one listed database's arrival on this device stands, /// from each fill pass (`ClientController::fill_listed`), which downloads /// the body in the core. case arrival(stage: String, database: String, bytesWritten: Int?, totalBytes: Int?, reason: String?) /// `{phase:"databaseSync", workspaceId, sync, …}` — where one database's /// sync stands as a pass ended (or a file copy moved), in the engine's /// own words (`DatabaseSyncLine`); `nil` from a core that says none. /// Never said as a pass starts. The counts the frame also carries are /// not read here: the device row reads its own off `sync.status`. case databaseSync(database: String, sync: DatabaseSyncLine?) /// `{phase:"removed", workspaceId}` — this device was removed from a /// database another person's Mac serves, and the core has just written it /// down (`ClientController::sync_joined_pass`): its copy is in this /// device's Bin and the held list no longer holds it. The frame carries /// no sentence; the list is read again on it, and a window that showed /// it goes back to Personal. case removed(database: String) /// `{workspaceId, tables:[…], origin:"write"|"pull"}` — the `data` event, /// which is the whole of invalidation. There is no sequence number: sync is /// one symmetric exchange over per-author cursors, and the tables that /// moved are the only thing a screen needs to hear — with the database /// they moved in (`workspaceId` on the wire), so a window showing another /// database is not re-read for them. `nil` when the event names none, /// which reaches every window. case data(tables: [String], origin: String?, database: String? = nil) /// A finished cycle: `{pushed, pulled, behind, behindBy, pending, /// lastPullAt}`, on the `client` stream with NO `phase`. /// `ClientController::sync_now` emits it, so the pending count and the /// "last checked" stamp both move without anybody asking for them again. /// `behind` here is the frame's `behindBy` — how many changes the serving /// Mac said still wait, `nil` unsaid — never the frame's page-cap flag. case cycle(pushed: Int, pulled: Int, behind: Int?, pending: Int, lastPullAt: String?) /// `{phase:"sync", state, pending, lastError, nextAttemptAt, failures, /// stoppedReason, lastPullAt, lastPushAt}` — the loop's own status, every /// time it publishes (`shell/client.rs::sync_status_event`). /// /// **Tagged, because the media drain's status is a phase-less frame with /// the same two keys and overlapping state words.** Before the tag this /// frame was dropped by the `.none` arm below — it carries no `pushed` — /// so a pass in flight, a backoff and a terminal refusal all reached /// nobody, and "Connected" on the settings row meant only that the file /// was open. `SyncModel` derives its phase from this. case sync(SyncLoopRead) /// The `origin` of a `data` event whose cause was BYTES landing on or /// leaving THIS device — the thumbnail sweep's tick, a tap's /// `media.ensure`, the budget's eviction (`crates/cotton-ffi/src/phone/ /// media.rs`, `MEDIA_EVENT_ORIGIN`). No row changed. Such an event reaches /// the `.storage` family only, and the consumers that act on every `data` /// event without reading its tables skip it: an origin-`media` event once /// re-read every mounted `.core` screen, ran the capture drain and ran a /// notifications pass — sixty times an hour /// while a library's thumbnails came down. public static let localMediaOrigin = "media" /// The `origin` of a `data` event that says a background move is DONE — /// the computed index rebuilt after the open, mail's search index filled /// (`shell/client.rs`, `MOVES_DONE_ORIGIN`). The tables it names are in /// step again: a read that answered `could_not_read` `moving` over them /// is read again on it, never on a timer or a pull (passivemove rule 3). public static let movesDoneOrigin = "moved" /// A background move of these tables is done. public var isMovesDone: Bool { if case .data(_, let origin, _) = self, origin == ClientEvent.movesDoneOrigin { return true } return false } /// Bytes moved on this device and nothing else did. public var isLocalMediaArrival: Bool { if case .data(_, let origin, _) = self, origin == ClientEvent.localMediaOrigin { return true } return false } /// Read one off the stream. `nil` for anything this build does not know. public static func from(_ event: CottonEvent) -> ClientEvent? { if event.kind == "data" { return .data( tables: event.payload["tables"]?.strings ?? [], origin: event.payload["origin"]?.string, database: event.payload["workspaceId"]?.string ) } guard event.kind == "client" else { return nil } switch event.payload["phase"]?.string { case "home": return .home(stage: event.payload["stage"]?.string ?? "") case "bootstrap": return .bootstrap( stage: event.payload["stage"]?.string ?? "", workspaceId: event.payload["workspaceId"]?.string, code: event.payload["code"]?.string, message: event.payload["message"]?.string, retryable: event.payload["retryable"]?.bool ) case "personal": switch event.payload["stage"]?.string { case "signed_out": if event.payload["deleted"]?.bool == true { return .personalDeleted(line: event.payload["words"]?["line"]?.string) } guard let code = event.payload["code"]?.string else { return nil } return .personalSignedOut(code: code) case "adopted", "adopt_failed": return .personalAdoptEnded default: return nil } case "arrival": guard let database = event.payload["workspaceId"]?.string else { return nil } return .arrival( stage: event.payload["stage"]?.string ?? "", database: database, bytesWritten: event.payload["bytesWritten"]?.int, totalBytes: event.payload["totalBytes"]?.int, reason: event.payload["reason"]?.string ) case "databaseSync": guard let database = event.payload["workspaceId"]?.string else { return nil } return .databaseSync(database: database, sync: DatabaseSyncLine(event.payload["sync"])) case "removed": guard let database = event.payload["workspaceId"]?.string else { return nil } return .removed(database: database) case "migrate": return .migrate( stage: event.payload["stage"]?.string ?? "", from: event.payload["from"]?.int, to: event.payload["to"]?.int, index: event.payload["index"]?.int, total: event.payload["total"]?.int, version: event.payload["version"]?.int, message: event.payload["message"]?.string ) case "sync": // A tagged frame with no state word is dropped rather than read // as idle — the same rule as the cycle below. return SyncLoopRead.of(event.payload).map(ClientEvent.sync) case .none: // The cycle report. Recognised by `pushed` and `pending` rather // than by a phase, because it has none — and by BOTH, so a future // phase-less frame carrying only one of them is dropped rather // than read as a cycle that pushed nothing. guard let pushed = event.payload["pushed"]?.int, let pending = event.payload["pending"]?.int else { return nil } return .cycle( pushed: pushed, pulled: event.payload["pulled"]?.int ?? 0, behind: event.payload["behindBy"]?.int, pending: pending, lastPullAt: event.payload["lastPullAt"]?.string ) default: return nil } } } /// `write`'s request: `{"tool":"","args":{…}}`. public struct WriteRequest: Encodable, Sendable { public var tool: String public var args: JSONValue public init(tool: String, args: JSONValue = .object([:])) { self.tool = tool self.args = args } } /// `write`'s answer — `authoring.rs::queued_answer`, plus the phone's `tool`. /// /// **`answer` is the TOOL's own answer, nested rather than merged**, and it is /// a whole JSON value: a handler that one day answers a `queued` of its own /// must not silently overwrite the outbox's report of the same name. `tables` /// IS the invalidation (design P5). /// /// **There is no `pushed` and no `notPushed`.** A write commits to the file, /// queues its op and returns; the sync loop pushes, off the screen's thread. /// Whether the op has left is `SyncStatusRead.pending`'s to say, and a screen /// that wants to show "waiting for the Mac" reads it there — never off a /// write's answer, which cannot know. public struct WriteAnswer: Decodable, Equatable, Sendable { /// Whatever the tool answered. Shape per tool, so it stays a tree. public var answer: JSONValue? /// `"client"` on the phone, always. public var rail: String? public var queued: Int? public var tables: [String]? public var tool: String? public init( answer: JSONValue? = nil, rail: String? = nil, queued: Int? = nil, tables: [String]? = nil, tool: String? = nil ) { self.answer = answer self.rail = rail self.queued = queued self.tables = tables self.tool = tool } } // MARK: - The media half of the sync status // // From `Boundary+4h.swift`, which went with I3: `SyncStatusRead` above carries // it, and the boot gate is the one file where typed decoding stays. /// What this device still owes the server in BYTES. /// /// `shell/client.rs::media_activity`, exactly. Device-local and never synced: /// the `_media` ledger is this phone's queue, not the workspace's. /// /// **A ledger that cannot be read answers `null` with the reason beside it /// rather than zeros.** A card saying "nothing to back up" because a query /// failed is the silent fallback this repo bans outright, so there are three /// shapes and the screen must tell them apart: `{counts, failed}` when both /// reads worked, `{counts: null, failed: null, unreadable}` when the counts /// failed, and `{counts, failed: null, unreadable}` when only the failed-rows /// read did. public struct MediaActivityRead: Decodable, Equatable, Sendable { /// `nil` when the counts themselves could not be read — never zeros. public var counts: Counts? /// The failed uploads, capped at twenty by the crate (`FAILED_MEDIA_LIMIT`, /// the screen's number and not a default of the ledger's). /// `nil` when that read failed, which is not the same as an empty list. public var failed: [FailedUpload]? /// Why one of the two reads answered nothing. Present only then. /// /// PORT GAP: [sync-media-unreadable-undrawn] **decoded and drawn nowhere.** `useSyncActivity` has no such /// field and `settings/sync.tsx` draws no sentence for it, so under /// "move everything as it is" no screen shows it — the card falls to /// "Checking…" on a `nil` `counts`, which is what the Expo card does with /// its own `media?.counts ?? null`. It is decoded rather than dropped /// because it is the only thing that can ever say WHICH of the two reads /// failed, and a reader of this file should find the reason waiting rather /// than have to go back to the crate for it. Ledger row: same class as /// the Bin's `note`. public var unreadable: String? public struct Counts: Decodable, Equatable, Sendable { public var pending: Int public var synced: Int public var failed: Int public var deletePending: Int public init(pending: Int = 0, synced: Int = 0, failed: Int = 0, deletePending: Int = 0) { self.pending = pending self.synced = synced self.failed = failed self.deletePending = deletePending } /// **The four are decoded STRICTLY, and that is the exception to this /// file's generosity rule.** /// /// Everywhere else a missing key falls back, because the crate may land /// a field before this app reads it and a phone bricked by its own core /// is the worse failure. These four are the opposite case: they are the /// COUNTS, and a `{"counts": {}}` decoded generously is `0/0/0/0`, /// which the card draws as "Nothing to back up yet" — a query that /// failed, said out loud as good news. That is the silent fallback the /// type's own doc comment above bans. /// /// Throwing here loses nothing, because the OUTER decode is the /// generous one: `counts` is `try?`-decoded, so a malformed object /// lands on `nil` and the card draws "Checking…" — the honest state for /// a ledger nobody could read. Generosity is kept where it belongs and /// removed where it lies. public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) pending = try container.decode(Int.self, forKey: .pending) synced = try container.decode(Int.self, forKey: .synced) failed = try container.decode(Int.self, forKey: .failed) deletePending = try container.decode(Int.self, forKey: .deletePending) } private enum CodingKeys: String, CodingKey { case pending, synced, failed, deletePending } } /// One upload that did not go. /// /// `key` is the OBJECT key, not a path — the card draws its last segment, /// and where the bytes are is `read.mediaPath`'s question. public struct FailedUpload: Decodable, Equatable, Sendable { public var key: String public var lastError: String? public var updatedAt: String? public init(key: String = "", lastError: String? = nil, updatedAt: String? = nil) { self.key = key self.lastError = lastError self.updatedAt = updatedAt } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) key = (try? container.decode(String.self, forKey: .key)) ?? "" lastError = try? container.decode(String.self, forKey: .lastError) updatedAt = try? container.decode(String.self, forKey: .updatedAt) } private enum CodingKeys: String, CodingKey { case key, lastError, updatedAt } } public init( counts: Counts? = nil, failed: [FailedUpload]? = nil, unreadable: String? = nil ) { self.counts = counts self.failed = failed self.unreadable = unreadable } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) counts = try? container.decode(Counts.self, forKey: .counts) failed = try? container.decode([FailedUpload].self, forKey: .failed) unreadable = try? container.decode(String.self, forKey: .unreadable) } private enum CodingKeys: String, CodingKey { case counts, failed, unreadable } }