// The databases this device holds, at the boundary.//// A person has ONE personal database — made at first run, nobody else can// enter, the default — and any number of project databases, each its own file// (owner decision 3 Oct 2026, Cotton notes 174779b2 and 0a22168c). The app// shows one at a time; only Today, search and "Asked of you" read across.//// This file is the Swift half of that: the row a held database is, the order// the Databases screen draws them in, the name rule, the toolkits// "What is it for?" offers, and the wrapper that names the shown database on// every call. `DatabasesCalling` is the seam and `CoreDatabases` answers it// over the core's own `read.databases`, `databases.show` / `databases.hide`// and `databases.create`.importFoundation/// One database this device holds.publicstructHeldDatabase: Codable, Equatable, Hashable, Identifiable, Sendable {publicenumKind: String, Codable, Sendable {case personalcase shared }/// What this person may do in a database.publicenumRights: String, Codable, Sendable {case ownercase admincase member }publiclet databaseId: Stringpublicvar name: Stringpublicvar kind: Kind/// Who else is in it, by first name; empty is "only you".publicvar people: [String]/// This person's rights in it. The switcher refreshes these from the/// live membership; a list without rights never grants administration.publicvar rights: Rights/// The cap colour the people in it chose, by its name (`CapColour`'s raw/// value), or `nil` for the one the app assigns from the held ids.publicvar colour: String?/// Where this database's copy stands on this device when it is not here/// yet (`read.databases`' `arrival`); `nil` once it has arrived.publicvar arrival: DatabaseArrival?/// Joined at ANOTHER PERSON'S Mac (`read.databases`' `theirs`): this/// device holds no name for the Mac that serves it, so its page says/// "their Mac not reachable" and never a name.publicvar theirs: Bool/// Why this device could not read its own copy just now/// (`read.databases`' `unreadable`); `nil` when it reads. The row stays/// on the sheet and says so — 12 Oct 2026, one unreadable file emptied/// the owner's whole sheet.publicvar unreadable: String?publicvar id: String { databaseId }/// Its copy is on its way: nothing in it can be read yet, and the screen/// says so on the cap rather than as an error.publicvar isArriving: Bool { arrival != nil }publicvar isPersonal: Bool { kind == .personal }/// Admit a person is offered only on a shared database, to its owner or/// an admin — never on the personal one.publicvar canAdmit: Bool { kind == .shared && rights != .member }publicinit( databaseId: String, name: String, kind: Kind, people: [String] = [], rights: Rights = .owner, colour: String? = nil, arrival: DatabaseArrival? = nil, theirs: Bool = false, unreadable: String? = nil ) {self.databaseId = databaseIdself.name = nameself.kind = kindself.people = peopleself.rights = rightsself.colour = colourself.arrival = arrivalself.theirs = theirsself.unreadable = unreadable }publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self) databaseId = try container.decode(String.self, forKey: .databaseId) name = try container.decode(String.self, forKey: .name) kind = try container.decodeIfPresent(Kind.self, forKey: .kind) ?? .shared people = try container.decodeIfPresent([String].self, forKey: .people) ?? [] rights = try container.decodeIfPresent(Rights.self, forKey: .rights) ?? .member colour = try container.decodeIfPresent(String.self, forKey: .colour) arrival = try container.decodeIfPresent(DatabaseArrival.self, forKey: .arrival) theirs = try container.decodeIfPresent(Bool.self, forKey: .theirs) ?? false unreadable = try container.decodeIfPresent(String.self, forKey: .unreadable) }/// The quiet line under a database's name: the cap, the board head and/// the Settings row all read this one line. A database this device was/// removed from is never a row here — `read.databases` leaves it out, and/// its copy is in the Bin on this device (architect's ruling, 16 Oct 2026).publicvar peopleLine: String {iflet arrival { return arrival.line }iflet unreadable { return"can't be read: " + unreadable }return people.isEmpty ? "only you" : "with " + people.joined(separator: ", ") }}/// Where a held database's copy stands while it is not on this device yet —/// a state the cap draws, never an error.publicstructDatabaseArrival: Codable, Equatable, Hashable, Sendable {publicenumState: String, Codable, Sendable {/// Listed, and no byte of it has moved yet.case waiting/// Its body is coming: `bytesWritten` of `totalBytes`.case arriving/// The last try stopped; the next starts by itself.case failed }publicvar state: Statepublicvar bytesWritten: Int?publicvar totalBytes: Int?publicvar reason: String?publicinit(state: State, bytesWritten: Int? = nil, totalBytes: Int? = nil, reason: String? = nil) {self.state = stateself.bytesWritten = bytesWrittenself.totalBytes = totalBytesself.reason = reason }/// Bytes have moved: never back, and a figure with a whole beats one without.publicfunc moved(written: Int, total: Int?) -> DatabaseArrival {let whole = total ?? totalByteslet kept = whole == totalBytes ? max(written, bytesWritten ?? 0) : writtenreturnDatabaseArrival(state: .arriving, bytesWritten: kept, totalBytes: whole) }/// The line under the cap: "9 of 11 MB" while it comes.publicvar line: String {switch state {case .waiting: return"arriving"case .failed: return"arriving — trying again"case .arriving:let written = Self.megabytes(bytesWritten ?? 0)guardlet totalBytes else { return"\(written) MB so far" }return"\(written) of \(Self.megabytes(totalBytes)) MB" } }/// The one calm sentence a page of it shows in place of its contents.publicfunc sentence(name: String) -> String {switch state {case .arriving where totalBytes != nil:return"\(name) is arriving — \(line)."default:return"\(name) is arriving on this device. It opens here when its copy has come." } }privatestaticfunc megabytes(_ bytes: Int) -> Int { (bytes + 1_048_575) / 1_048_576 }}/// A database the person joined on ANOTHER of their devices that this device/// does not hold — `read.databases`' `elsewhere`, from the synced/// `cotton_joined_places`. The switcher offers each, and `databases.present`/// fetches it here as another device of the same person.publicstructElsewhereDatabase: Decodable, Equatable, Hashable, Identifiable, Sendable {publiclet databaseId: Stringpubliclet name: String/// The serving Mac's address, as the device that joined recorded it.publiclet origin: Stringpubliclet serverDeviceId: Stringpublicvar id: String { databaseId }publicinit(databaseId: String, name: String, origin: String = "", serverDeviceId: String = "") {self.databaseId = databaseIdself.name = nameself.origin = originself.serverDeviceId = serverDeviceId }publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self) databaseId = try container.decode(String.self, forKey: .databaseId) name = try container.decodeIfPresent(String.self, forKey: .name) ?? "" origin = try container.decodeIfPresent(String.self, forKey: .origin) ?? "" serverDeviceId = try container.decodeIfPresent(String.self, forKey: .serverDeviceId) ?? "" }privateenumCodingKeys: String, CodingKey { case databaseId, name, origin, serverDeviceId }/// The quiet line under its cap.publicstaticlet capLine = "on your other device — tap to get it here"}/// The whole `read.databases` answer: what this device holds, what its/// windows pin, and what the person holds on another device only. `shown`/// and `elsewhere` may be absent (an older core): both read as empty.publicstructDatabasesListing: Decodable, Equatable, Sendable {publicvar databases: [HeldDatabase]publicvar shown: [String]publicvar elsewhere: [ElsewhereDatabase]publicinit(databases: [HeldDatabase], shown: [String] = [], elsewhere: [ElsewhereDatabase] = []) {self.databases = databasesself.shown = shownself.elsewhere = elsewhere }publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self) databases = try container.decode([HeldDatabase].self, forKey: .databases) shown = try container.decodeIfPresent([String].self, forKey: .shown) ?? [] elsewhere = try container.decodeIfPresent([ElsewhereDatabase].self, forKey: .elsewhere) ?? [] }privateenumCodingKeys: String, CodingKey { case databases, shown, elsewhere }}/// What `databases.present` answers: the database is joined here. A copy that/// did not arrive yet says `copyPending` with the reason in `message`; the/// next pass over the joined databases fetches it.publicstructPresentedDatabase: Decodable, Equatable, Sendable {publiclet databaseId: Stringpubliclet joined: Boolpubliclet written: Boolpubliclet copyPending: Boolpubliclet message: String?publicinit(databaseId: String, joined: Bool = true, written: Bool = true, copyPending: Bool = false, message: String? = nil) {self.databaseId = databaseIdself.joined = joinedself.written = writtenself.copyPending = copyPendingself.message = message }publicinit(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self) databaseId = try container.decode(String.self, forKey: .databaseId) joined = try container.decodeIfPresent(Bool.self, forKey: .joined) ?? true written = try container.decodeIfPresent(Bool.self, forKey: .written) ?? true copyPending = try container.decodeIfPresent(Bool.self, forKey: .copyPending) ?? false message = try container.decodeIfPresent(String.self, forKey: .message) }privateenumCodingKeys: String, CodingKey { case databaseId, joined, written, copyPending, message }}/// The order every surface draws databases in: the personal one first, then/// the project databases in the order they were given (the owner's own).publicenumDatabaseOrder {publicstaticfunc shown(_ databases: [HeldDatabase]) -> [HeldDatabase] { databases.filter(\.isPersonal) + databases.filter { !$0.isPersonal } }/// The database to open on: the last one opened if it is still held,/// else the personal one.publicstaticfunc opening(last: String?, in databases: [HeldDatabase]) -> HeldDatabase? {let order = shown(databases)return order.first { $0.databaseId == last } ?? order.first }}/// The name a new database may take.publicenumDatabaseName {/// The personal database's name, reserved: the server refuses it at make/// and at adoption, and the phone refuses it before either.publicstaticlet personal = "Personal"/// Why this name cannot be used, or nil when it can.publicstaticfunc refusal(_ name: String, held: [HeldDatabase] = []) -> String? {let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)if trimmed.isEmpty { return"Give the database a name." }let taken = [personal] + held.filter(\.isPersonal).map(\.name)if taken.contains(where: { $0.caseInsensitiveCompare(trimmed) == .orderedSame }) {return"\(trimmed) is your own database's name. Choose another." }returnnil }}/// What "What is it for?" offers. A toolkit is a template, not a kind: it only/// decides which tools the new database starts with, and two databases may be/// made from one toolkit.publicstructDatabaseToolkit: Decodable, Equatable, Hashable, Identifiable, Sendable {publiclet id: Stringpubliclet name: Stringpubliclet startingTools: [String]publicinit(id: String, name: String, startingTools: [String] = []) {self.id = id; self.name = name; self.startingTools = startingTools }publicstaticlet all: [DatabaseToolkit] = [DatabaseToolkit(id: "family", name: "Family"),DatabaseToolkit(id: "partner", name: "Me & partner"),DatabaseToolkit(id: "friends", name: "Friends"),DatabaseToolkit(id: "tech-team", name: "Tech team"),DatabaseToolkit(id: "yoga-studio", name: "Yoga studio"),DatabaseToolkit(id: "yoga-trainer", name: "Yoga trainer"),DatabaseToolkit(id: "teaching", name: "Teaching"),DatabaseToolkit(id: "blank", name: "Blank"), ]}extensionCottonMethod {/// The databases this device holds, personal first. Read off the/// connection record: listing opens no file.publicstaticlet readDatabases = "read.databases"publicstaticlet readDatabase = "read.database"/// What every device of the person keeps of one database (Spec 10.5).publicstaticlet readDatabaseStorage = "read.databaseStorage"/// One window starts drawing a database. The pin is COUNTED: one `show`/// per window, undone by one `hide`.publicstaticlet databasesShow = "databases.show"/// One window stopped drawing a database.publicstaticlet databasesHide = "databases.hide"/// Make a database beside the personal one. The serving Mac makes it on/// its server; every other device mints the file itself, with no network.publicstaticlet databasesCreate = "databases.create"publicstaticlet databasesToolkits = "databases.toolkits"}/// The calls the Databases screen makes.publicprotocolDatabasesCalling: Sendable {/// Every database this device holds.func databases() asyncthrows -> [HeldDatabase]func toolkits() asyncthrows -> [DatabaseToolkit]/// One window starts drawing this database: pin it, so no pass closes it.func show(_ databaseId: String) asyncthrows/// One window stopped drawing this database: undo that window's pin.func hide(_ databaseId: String) asyncthrows/// Make a database, here and now, from a toolkit.func create(name: String, toolkit: DatabaseToolkit) asyncthrows -> HeldDatabase/// `read.database` — the database page's facts (Spec 10.2).func page(_ databaseId: String) asyncthrows -> DatabasePage/// `read.databaseStorage` — what each device keeps of the database (Spec 10.5).func storage(_ databaseId: String) asyncthrows -> DatabaseStorage/// The whole `read.databases` answer, with what the person holds on/// another device only.func listing() asyncthrows -> DatabasesListing/// `databases.leave` — this device forgets a shared database and tells/// the Mac that served it; answers whether that Mac has been told now.func leave(_ databaseId: String) asyncthrows -> Bool/// `databases.present` — fetch a database the person joined on another/// device, as another device of the same person.func present(_ databaseId: String) asyncthrows -> PresentedDatabase}extensionDatabasesCalling {publicfunc toolkits() asyncthrows -> [DatabaseToolkit] { DatabaseToolkit.all }/// A source that knows only what it holds holds nothing elsewhere.publicfunc listing() asyncthrows -> DatabasesListing { DatabasesListing(databases: tryawait databases()) }publicfunc present(_ databaseId: String) asyncthrows -> PresentedDatabase {throwCottonCallError(code: "unknown_method", message: CottonCallError.notOnThisDevice) }publicfunc leave(_ databaseId: String) asyncthrows -> Bool {throwCottonCallError(code: "unknown_method", message: CottonCallError.notOnThisDevice) }publicfunc page(_ databaseId: String) asyncthrows -> DatabasePage {throwCottonCallError(code: "unknown_method", message: CottonCallError.notOnThisDevice) }publicfunc storage(_ databaseId: String) asyncthrows -> DatabaseStorage {throwCottonCallError(code: "unknown_method", message: CottonCallError.notOnThisDevice) }}/// The core's own answers.publicstructCoreDatabases: DatabasesCalling {privatelet core: any CottonCalling/// What this device is called, sent with `databases.present` so the/// serving Mac's device list names it.privatelet deviceName: String?privatelet publicKey: @Sendable () asyncthrows -> String?privatelet privateKey: @Sendable () asyncthrows -> Stringprivatelet pause: @Sendable () asyncthrows -> Voidpublicinit( core: any CottonCalling, deviceName: String? = nil, publicKey: @escaping @Sendable () asyncthrows -> String? = {tryawaitTask.detached { tryVaultKeyring().publicKey() }.value }, privateKey: @escaping @Sendable () asyncthrows -> String = {tryawaitTask.detached { tryVaultKeyring().privateKey() }.value }, pause: @escaping @Sendable () asyncthrows -> Void = {tryawaitTask.sleep(for: .seconds(1)) } ) {self.core = coreself.deviceName = deviceNameself.publicKey = publicKeyself.privateKey = privateKeyself.pause = pause }privatestructPresent: Encodable {let databaseId: Stringlet name: String?let platform: String }/// The platform `databases.present` names this device by. #if os(macOS)staticlet platform = "mac" #elsestaticlet platform = "ios" #endifprivatestructPin: Encodable {let databaseId: String }privatestructMake: Encodable {let name: Stringlet toolkit: String }privatestructMade: Decodable {let id: Stringlet name: String }privatestructKits: Decodable { let toolkits: [DatabaseToolkit] }publicfunc toolkits() asyncthrows -> [DatabaseToolkit] {tryawait core.call(CottonMethod.databasesToolkits, as: Kits.self).toolkits }publicfunc page(_ databaseId: String) asyncthrows -> DatabasePage {tryawait core.call(CottonMethod.readDatabase, PageOf(databaseId: databaseId), as: DatabasePage.self) }privatestructPageOf: Encodable { let databaseId: String }publicfunc storage(_ databaseId: String) asyncthrows -> DatabaseStorage {tryawait core.call(CottonMethod.readDatabaseStorage, StorageOf(database: databaseId), as: DatabaseStorage.self) }privatestructStorageOf: Encodable { let database: String }publicfunc databases() asyncthrows -> [HeldDatabase] {tryawait listing().databases }publicfunc listing() asyncthrows -> DatabasesListing {tryawait core.call(CottonMethod.readDatabases, as: DatabasesListing.self) }publicfunc present(_ databaseId: String) asyncthrows -> PresentedDatabase {let name = deviceName?.trimmingCharacters(in: .whitespacesAndNewlines)func ask() asyncthrows -> PresentedDatabase {tryawait core.call(CottonMethod.databasesPresent,Present(databaseId: databaseId, name: name?.isEmpty == false ? name : nil, platform: Self.platform),as: PresentedDatabase.self ) }do { returntryawait ask() }catchlet error asCottonCallErrorwhere ["vault_locked", "vault_key_unpublished", "no_person_key"].contains(error.code) {// The person key signs the device statement only while the vault// is unlocked: the same publish-and-unlock a make and a join run,// then the one second ask.tryawait unlockVault(or: error)returntryawait ask() } }/// Leave a shared database: the Mac that served it is told by a removal/// the person key signs, so the vault is unlocked the way `present` does/// when the core says it is locked — nothing is forgotten until then.publicfunc leave(_ databaseId: String) asyncthrows -> Bool {structLeft: Decodable { let serverTold: Bool }func ask() asyncthrows -> Bool {tryawait core.call(CottonMethod.databasesLeave, Pin(databaseId: databaseId), as: Left.self).serverTold }do { returntryawait ask() }catchlet error asCottonCallErrorwhere ["vault_locked", "vault_key_unpublished", "no_person_key"].contains(error.code) {tryawait unlockVault(or: error)returntryawait ask() } }/// Publish this device's vault key and unlock the vault behind Keychain/// presence, as a make and a join do; `error` stands when there is no key.privatefunc unlockVault(or error: CottonCallError) asyncthrows {structPublicKey: Encodable { let publicKey: String }guardlet publicKey = tryawait publicKey(), !publicKey.isEmpty else { throw error }tryTask.checkCancellation() _ = tryawait core.callJSON("vault.publishKey", PublicKey(publicKey: publicKey))let secret = tryawait privateKey()tryTask.checkCancellation()tryawaitPersonalSigner.unlock(core: core, privateKey: secret, pause: pause) }publicfunc show(_ databaseId: String) asyncthrows { _ = tryawait core.callJSON(CottonMethod.databasesShow, Pin(databaseId: databaseId)) }publicfunc hide(_ databaseId: String) asyncthrows { _ = tryawait core.callJSON(CottonMethod.databasesHide, Pin(databaseId: databaseId)) }publicfunc create(name: String, toolkit: DatabaseToolkit) asyncthrows -> HeldDatabase {func make() asyncthrows -> Made {tryawait core.call(CottonMethod.databasesCreate, Make(name: name, toolkit: toolkit.id), as: Made.self) }let made: Madedo { made = tryawait make() }catchlet error asCottonCallErrorwhere ["creator_identity_unavailable", "vault_locked", "no_person_key"].contains(error.code) {// Creating a database signs its owner's membership. The private// vault key stays behind Keychain presence, as it does for Reveal.tryawait unlockVault(or: error) made = tryawait make() }returnHeldDatabase(databaseId: made.id, name: made.name, kind: .shared) }}/// The database one window's screens are reading, as its calls see it: the/// shown project database's id, or nil for the personal one. One per window,/// set by that window's scene when it turns to another database.publicfinalclassShownDatabase: @unchecked Sendable {privatelet lock = NSLock()privatevar shown: String?publicinit(_ id: String? = nil) { shown = id }publicvar id: String? { get { lock.withLock { shown } } set { lock.withLock { shown = newValue } } }}/// The shown database, reaching every call: `database` beside the screen's own/// arguments, for every method, when the shown database is not the device's/// own. The personal database is the attachment and needs no name.publicstructDatabaseScopedCore: CottonCalling {privatelet underlying: any CottonCallingprivatelet shown: ShownDatabase/// - Parameter database: the shown project database, or nil for the/// personal one.publicinit(underlying: any CottonCalling, database: String?) {self.init(underlying: underlying, shown: ShownDatabase(database)) }/// One window's calls: each names the database the window shows at the/// moment it is made.publicinit(underlying: any CottonCalling, shown: ShownDatabase) {self.underlying = underlyingself.shown = shown }/// The core under the scope, and the database the scope names now — what/// a database's definitions are cached by (`DefinitionCatalogues`).publicvar unscoped: any CottonCalling { underlying }publicvar databaseID: String? { shown.id }publicfunc callRaw(_ method: String, requestJSON: String) asyncthrows -> String {tryawait underlying.callRaw(method, requestJSON: Self.request(requestJSON, database: shown.id)) }publicfunc subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {await underlying.subscribe(handler) }publicfunc close() async {await underlying.close() }/// The request with `database` at its top level. Unchanged for the/// personal database, for a request that already names one — at its top/// level or in its `args`, where a scaffolded read carries its arguments/// (a feed reading `"all"`, a link opening a record in its own database) —/// and for a body that is not a JSON object.publicstaticfunc request(_ json: String, database: String?) -> String {guardlet database,let parsed = try? JSONSerialization.jsonObject(with: Data(json.utf8)),var object = parsed as? [String: Any], object["database"] == nil, (object["args"] as? [String: Any])?["database"] == nilelse { return json } object["database"] = databaseguardlet data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) else {return json }returnString(decoding: data, as: UTF8.self) }}/// `read.databaseStorage {database}` (Spec 10.5): what each of the person's/// devices keeps of one database — this one measured now, another as it last/// reported. A device that never measured answers `nil`, never zero.publicstructDatabaseStorage: Decodable, Equatable, Sendable {publiclet devices: [Device]publicstructDevice: Decodable, Equatable, Sendable {publiclet deviceId: Stringpubliclet name: Stringpubliclet thisDevice: Boolpubliclet keptBytes: Int?publiclet freeableBytes: Int?publicinit(deviceId: String, name: String, thisDevice: Bool, keptBytes: Int? = nil, freeableBytes: Int? = nil) {self.deviceId = deviceIdself.name = nameself.thisDevice = thisDeviceself.keptBytes = keptBytesself.freeableBytes = freeableBytes } }publicinit(devices: [Device]) { self.devices = devices }}/// `read.database {databaseId}` (Spec 10.2): one database's page in one read.publicstructDatabasePage: Decodable, Equatable, Sendable {publiclet databaseId: Stringpubliclet name: Stringpubliclet colour: String?publiclet personal: Boolpubliclet canLeave: Bool/// What THIS device keeps of it; `nil` while the storage rules have not measured it.publiclet keptHere: KeptHere?publicstructKeptHere: Decodable, Equatable, Sendable {publiclet heldBytes: Intpubliclet freeableBytes: Intpubliclet heldCount: Intpublicinit(heldBytes: Int, freeableBytes: Int, heldCount: Int) {self.heldBytes = heldBytesself.freeableBytes = freeableBytesself.heldCount = heldCount } }publicinit(databaseId: String, name: String, colour: String? = nil, personal: Bool, canLeave: Bool, keptHere: KeptHere? = nil) {self.databaseId = databaseIdself.name = nameself.colour = colourself.personal = personalself.canLeave = canLeaveself.keptHere = keptHere }}