// The databases this app holds, and the one each window shows. // // TWO OWNERS, on purpose (owner decision 3 Oct 2026, Cotton note 9e51c505): // the LIST of held databases is the app's — one `DatabasesModel`, built with // the root — and the database a window SHOWS is that window's — one // `DatabaseScene` per scene: the phone's one scene, and each Mac window's // `MacWindowState`. There is no app-wide "current database", because two Mac // windows may show two databases. "Last opened" is remembered between // launches only to SEED a window that has not chosen yet; it is never read as // the live value. // // The calls go through `DatabasesCalling` (`CottonKit/Databases.swift`), which // `CoreDatabases` answers over the core. import CottonKit import Foundation import Observation /// The held databases, in the order every surface draws them, and the one /// make. Shared by every window of the app. @MainActor @Observable final class DatabasesModel { /// Every database this device holds, as the source gave them. private(set) var held: [HeldDatabase] = [] /// The databases the person joined on another device that this one does /// not hold, from the same read: the switcher offers each to fetch here. private(set) var elsewhere: [ElsewhereDatabase] = [] /// The one of them being fetched here now. private(set) var presenting: String? private(set) var ownerName: String? private(set) var toolkits: [DatabaseToolkit] = [] private(set) var toolkitsRefusal: String? func loadToolkits() async { do { toolkits = try await source.toolkits(); toolkitsRefusal = nil } catch { toolkitsRefusal = CouldNotRead.line(for: error) } } private(set) var readRefusal: String? /// The held list has been asked for at least once, and answered or /// refused: until then, no personal database is not yet a fact. private(set) var listed = false /// Why the last make was refused, in the sentence the name screen shows. private(set) var refusal: String? /// A make is on its way. private(set) var creating = false /// The joiners waiting on the databases this person may admit to. private(set) var claims: [DatabaseClaim] = [] /// Why the last invite, admit or refuse was refused. private(set) var membersRefusal: String? @ObservationIgnored private let source: any DatabasesCalling @ObservationIgnored private let invites: any InvitesCalling @ObservationIgnored private let members: (any MembersCalling)? @ObservationIgnored private let readOwnerName: @Sendable () async throws -> String? /// The status read's `syncs`: where every database's sync stands. @ObservationIgnored private let readSyncs: @Sendable () async throws -> [String: DatabaseSyncLine] @ObservationIgnored private let defaults: UserDefaults /// Where the last database opened is remembered, to seed a new window. static let lastOpenedKey = "cotton.databases.lastOpened" private static let openedOrderKey = "cotton.databases.openedOrder" init( source: any DatabasesCalling, invites: any InvitesCalling = PendingInvites(), members: (any MembersCalling)? = nil, readOwnerName: @escaping @Sendable () async throws -> String? = { nil }, readSyncs: @escaping @Sendable () async throws -> [String: DatabaseSyncLine] = { [:] }, defaults: UserDefaults = .standard ) { self.source = source self.invites = invites self.members = members self.readOwnerName = readOwnerName self.readSyncs = readSyncs self.defaults = defaults } /// The held databases in the order the Databases screen draws them: the /// personal one first. var ordered: [HeldDatabase] { DatabaseOrder.shown(held) } /// RULE: a cap is named by its database's own name, never the owner's; renaming the owner renames no cap. func capName(_ database: HeldDatabase) -> String { database.name } func refreshOwnerName() async { do { ownerName = try await readOwnerName() } catch { Log.write("databases: the owner's name could not be read — \(error)") } } /// Each database's cap: the colour its theme's cap names (`databases.list` /// composes it from each database's theme row, which MCP alone writes), /// else the one assigned from its id — the same set of ids is the same /// caps on every launch and every device. var colours: [String: CapColour] { var colours = CapColour.assign(held.map(\.databaseId)) for database in held { if let chosen = database.colour.flatMap(CapColour.init(rawValue:)) { colours[database.databaseId] = chosen } } return colours } /// `read.database` for one held database (Spec 10.2). func page(_ databaseId: String) async throws -> DatabasePage { try await source.page(databaseId) } /// `read.databaseStorage` for one held database (Spec 10.5). func storage(_ databaseId: String) async throws -> DatabaseStorage { try await source.storage(databaseId) } /// The database this id names, if this device holds it. func database(_ id: String?) -> HeldDatabase? { held.first { $0.databaseId == id } } /// The last database opened in any window, by id. var copyOrder: [String] { held.filter(\.isPersonal).map(\.databaseId) + (defaults.stringArray(forKey: Self.openedOrderKey) ?? lastOpened.map { [$0] } ?? []) } var lastOpened: String? { defaults.string(forKey: Self.lastOpenedKey) } /// The database a window that has not chosen opens on: the last one /// opened if it is still held, else the personal one. var opening: HeldDatabase? { DatabaseOrder.opening(last: lastOpened, in: held) } /// A household leave ends this list's identity. What comes after reads /// fresh rows even when its first frame precedes the network's next answer. func resetAfterLeaving() { held = [] elsewhere = [] ownerName = nil readRefusal = nil claims = [] membersRefusal = nil defaults.removeObject(forKey: Self.lastOpenedKey) defaults.removeObject(forKey: Self.openedOrderKey) } /// Read the held list again, then what is said around it. func refresh() async { let shown = await refreshList() await refreshAround(shown: shown) } /// The held list alone — what a window needs to know which database it /// shows. Home's fan waits on the window's database, so a launch seeds it /// from this and reads the rest after (`refreshAround`): seeded after the /// sync lines, the owner and every roster, the fan stood on Me and Tools /// for ~10 s on the owner's Personal at a cold launch while `read.home` had /// answered in 233 ms (290 walk, 16 Oct 2026; readpool). @discardableResult func refreshList() async -> Set { var shown: Set = [] do { let listing = try await source.listing() // The list arrives with no people on any row. A roster already // read stays on its row across a re-listing: an unread roster // is not "only you". let read = Dictionary(held.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) held = listing.databases.map { listed in guard let was = read[listed.id] else { return listed } var kept = listed if listed.people.isEmpty { kept.people = was.people } kept.rights = was.rights // The app's own figure of a body in flight is ahead of the // bytes on disk the core lists. if let listedArrival = listed.arrival, let held = was.arrival?.bytesWritten, listedArrival.state == .arriving { kept.arrival = listedArrival.moved(written: held, total: listedArrival.totalBytes) } return kept } shown = Set(listing.shown) elsewhere = listing.elsewhere.filter { place in !listing.databases.contains { $0.databaseId == place.databaseId } } readRefusal = nil } catch { readRefusal = CouldNotRead.line(for: error) // The list stays what it was: a screen keeps drawing the databases // it had rather than none. Log.write("databases: the held list could not be read — \(error)") } listed = true return shown } /// What is said around the held list: each database's sync line, the /// owner's name and the rosters of the databases a window shows. func refreshAround(shown: Set) async { // Where each database's sync stood when this was asked, so a cap and // a page's top say it from launch rather than from the next pass // that ends. A read that failed leaves what the passes have said. if let said = try? await readSyncs() { syncLines.merge(said) { _, asked in asked } } await refreshOwnerName() // A database a window shows is awake, so its roster is read with the // list: the board head and Settings say who is in it, never "only // you" for a roster nobody has read yet. await refreshPeople(of: shown) } /// A window opened `id`: remember it to seed the next window, and pin it /// so no pass closes it while it is drawn. func opened(_ id: String) async { defaults.set(id, forKey: Self.lastOpenedKey) let earlier = defaults.stringArray(forKey: Self.openedOrderKey) ?? [] defaults.set([id] + earlier.filter { $0 != id }, forKey: Self.openedOrderKey) do { try await source.show(id) // Opening makes this database active; read its synced appearance // into the held list without waking any idle database. await refresh() } catch { Log.write("databases: could not pin \(id) — \(error)") } } /// A window stopped drawing `id`: undo that window's pin. func closed(_ id: String) async { do { try await source.hide(id) } catch { Log.write("databases: could not unpin \(id) — \(error)") } } /// Make a database from a toolkit. Nil when it was refused, with the /// sentence in `refusal` — a name the phone refuses never reaches the /// source. func create(name: String, toolkit: DatabaseToolkit) async -> HeldDatabase? { if let refused = DatabaseName.refusal(name, held: held) { refusal = refused return nil } refusal = nil creating = true defer { creating = false } do { let made = try await source.create( name: name.trimmingCharacters(in: .whitespacesAndNewlines), toolkit: toolkit ) held.removeAll { $0.databaseId == made.databaseId } held.append(made) return made } catch let error as CottonCallError { refusal = error.message } catch { refusal = error.localizedDescription } return nil } // MARK: - Arrival /// Where each database's sync stands, in the engine's words /// (`CottonKit/DatabaseSyncLine.swift`), by database id: what the line /// under its cap and the top of its page say. private(set) var syncLines: [String: DatabaseSyncLine] = [:] /// Where one database's sync stands; one nothing has been said of is /// level as far as anyone knows. func sync(_ databaseId: String) -> DatabaseSyncLine { syncLines[databaseId] ?? .current } /// The line under a database's cap — ONE line, always: how far its copy /// has come while it arrives; the engine's sync line ("syncing · 62%", /// "copying · 400 MB to go", "offline", "update app"); else who is in it. func capLine(_ database: HeldDatabase) -> String { if database.isArriving || database.unreadable != nil { return database.peopleLine } return sync(database.databaseId).capLine ?? database.peopleLine } /// Is the line under a database's cap the refusal no retry changes /// ("update app"), drawn in red. func capRefuses(_ database: HeldDatabase) -> Bool { !database.isArriving && sync(database.databaseId).refuses } /// Does the cap turn: while its copy arrives and while rows or bytes /// move. Offline and waiting for an update it stands still. func turns(_ database: HeldDatabase) -> Bool { database.isArriving || sync(database.databaseId).turns } /// The core's word on a listed database's arrival /// (`{phase:"arrival"}`): the cap's line moves with it, and one that has /// arrived is read again as an ordinary database. A database this device /// was just removed from (`{phase:"removed"}`) is read again too: the list /// no longer holds it — its copy is in the Bin on this device — so it /// leaves the caps arc at once, and every window that showed it goes back /// to Personal (`DatabaseSceneWiring`), not at a relaunch. func receive(_ event: ClientEvent) { if case .databaseSync(let database, let sync) = event { // A core that says no standing changes nothing. if let sync { syncLines[database] = sync } return } if case .removed = event { Task { await refresh() } return } guard case .arrival(let stage, let database, let written, let total, let reason) = event, let index = held.firstIndex(where: { $0.id == database }) else { return } switch stage { case "failed": held[index].arrival = DatabaseArrival(state: .failed, reason: reason) case "here": held[index].arrival = nil Task { await refresh() } default: // The cap's line moves with every figure the core reports, not // only at the next listing: Cotton's cap stood at "25 of 307 MB" // for a minute while its bytes came (walker 291). if let written, let arrival = held[index].arrival, arrival.state == .arriving { held[index].arrival = arrival.moved(written: written, total: total ?? arrival.totalBytes) } } } // MARK: - Admit a person /// The databases this person may admit someone to. var admitting: [HeldDatabase] { ordered.filter { $0.canAdmit && !$0.isArriving } } /// Only the open switcher asks for every roster; listing at launch leaves /// idle databases closed, and `refresh` asks for the shown databases' /// alone (`of`). Rights are read from the device's own statement. func refreshPeople(of only: Set? = nil) async { guard let members else { return } if only?.isEmpty == true { return } // A database on its way has no file to read a roster from; its cap // says it is arriving, and nothing here calls that a failure. for database in held where !database.isPersonal && !database.isArriving && (only?.contains(database.id) ?? true) { do { let read = try await members.members(of: database.databaseId) guard let index = held.firstIndex(where: { $0.id == database.id }) else { continue } let me = read.members.first { $0.personKey == read.me } held[index].rights = me.map { $0.isOwner ? .owner : ($0.rights == .admin ? .admin : .member) } ?? .member held[index].people = Members.ordered(read.members).filter { $0.personKey != read.me }.map { ThoughtWords.firstName($0.name) ?? $0.name } } catch { if let index = held.firstIndex(where: { $0.id == database.id }) { held[index].rights = .member } // A roster is the cap's quiet line, read again on the next // open; a red sentence under the grid for it was nothing the // person could act on. Log.write("databases: the people in \(database.databaseId) could not be read — \(error)") } } } /// Read who is waiting, on every database this person may admit to. A /// database that cannot answer keeps the cards it had, and says nothing /// red: the read goes to the database's server, and a device that cannot /// reach it says so on Home, since when it last synced. func refreshClaims() async { var waiting: [DatabaseClaim] = [] for database in admitting { do { waiting += try await invites.claims(on: database.databaseId) } catch { Log.write("databases: the claims on \(database.databaseId) could not be read — \(error)") waiting += claims.filter { $0.databaseId == database.databaseId } } } claims = waiting } /// Admit or refuse one waiting joiner; its card goes either way. func decide(_ claim: DatabaseClaim, admit: Bool) async { let done: Void? = await asking { if admit { try await self.invites.admit(claim) } else { try await self.invites.refuse(claim) } } guard done != nil else { return } claims.removeAll { $0.claimId == claim.claimId } if admit { await refresh() await refreshPeople() } } /// Fetch a database the person joined on another device, here. The core /// unlocks the vault and asks again once when the person key cannot sign /// yet (`CoreDatabases.present`, the join's own unlock). Answers the /// database, read from the held list again, for the window to show; nil /// with the sentence in `membersRefusal`. A place the person was removed /// from leaves the list until the next read. /// Leave the shared database this window shows (`CoreDatabases.leave`, /// which unlocks the vault for the signed leave). Throws the core's /// refusal for the caller to say. /// /// **One database, and never the device's own.** The personal database /// is this device's pairing and is refused here without a call; leaving /// a project database calls `databases.leave` and nothing that unpairs, /// starts or erases. func leave(_ databaseId: String) async throws { if held.first(where: { $0.databaseId == databaseId })?.isPersonal == true { throw CottonCallError( code: "personal_not_left", message: ShellLines.line("databases", "your_personal_database_is")) } _ = try await source.leave(databaseId) } func present(_ place: ElsewhereDatabase) async -> HeldDatabase? { guard presenting == nil else { return nil } presenting = place.databaseId defer { presenting = nil } membersRefusal = nil let answer: PresentedDatabase do { answer = try await source.present(place.databaseId) } catch is CancellationError { return nil } catch let error as CottonCallError { membersRefusal = error.message if error.code == "not_a_member" { elsewhere.removeAll { $0.databaseId == place.databaseId } } return nil } catch { membersRefusal = error.localizedDescription return nil } await refresh() guard let fetched = database(answer.databaseId) else { membersRefusal = answer.message ?? ShellLines.line("databases", "is_joined_here_but", ["name": "\(place.name)"]) return nil } return fetched } private func asking(_ ask: () async throws -> Answer) async -> Answer? { membersRefusal = nil do { return try await ask() } catch is CancellationError { return nil } catch let error as CottonCallError { membersRefusal = error.message } catch { membersRefusal = error.localizedDescription } return nil } /// The name changed: the last refusal no longer describes it. func clearRefusal() { refusal = nil } } /// One window's database: which one it shows, and whether its Databases /// screen is up. The phone's root holds one; each Mac window holds its own on /// `MacWindowState`. Read it from the environment /// (`@Environment(DatabaseScene.self) var scene: DatabaseScene?`). @MainActor @Observable final class DatabaseScene { /// The database this window shows. Nil until the held list is read. var shownId: String? /// A persisted scene choice belongs only to the household this scene began with. private(set) var restoresStoredSelection = true /// The Databases screen is up in this window. var choosing = false /// How many times the person picked a database for this window — the same one /// again counts: the page goes back to the database's own page, leaving a /// project a link had chosen. private(set) var picks = 0 /// The person long-pressed a cap for its page (Spec 10.2) or its sync /// page: once the window shows that database, Home opens it and clears this. var pageAsked: Route? /// Where this window left each database's page while it shows it — for /// this run only, and forgotten when the window turns to it: a cold launch /// and a switch both open the database at its top (coordinator 6 Oct, /// RJ11 on the build box; walk6 05:20Z: a switch back opened at the place left, which /// read as the last database's offset). @ObservationIgnored let places = PagePlaces() /// What this window's calls name: the shown database, nil while it is the /// personal one. The window's core reads it on every call /// (`DatabaseScopedCore`). @ObservationIgnored let calls = ShownDatabase() /// The database this window holds a pin on. The core COUNTS pins, so a /// window pins once per database it turns to and unpins the one it left. @ObservationIgnored private var pinned: String? /// Told the database id each time the calls are aimed, before `shownId` /// moves: the window turns its table catalogue (`DatabaseTableCatalog`) /// in the same step, so the records store and the calls never disagree. @ObservationIgnored var aimed: ((String) -> Void)? /// Told the database a switch turns to and what its calls will name (nil /// the personal one) BEFORE anything of the window moves, and awaited: /// the window reads that database's kept Home from the phone's own copy /// (`HomeModel.prepare`) while the old Home stands, so the switch is two /// frames — the old Home, then the new one whole (295 A, walker294). /// Nil turns at once. @ObservationIgnored var prepare: (@MainActor (_ id: String, _ calls: String?) async -> Void)? /// Each turn asked, counted: only the newest commits (`show`). @ObservationIgnored private var turning = 0 init(shownId: String? = nil) { self.shownId = shownId } /// Retire the old household's selected database and call scope. func reset() { restoresStoredSelection = false shownId = nil calls.id = nil pinned = nil choosing = false } /// The shown database's row, when the model holds it. func shown(in model: DatabasesModel) -> HeldDatabase? { model.database(shownId) } /// Open the Databases screen in this window — what the centre cap does. /// A business app that shows one database has no Databases screen. func openDatabases() { guard Self.hasDatabasesScreen(FlavourManifest.current) else { return } choosing = true } /// Whether this app has a Databases screen: Cotton does; a business app /// whose manifest says `single` does not. nonisolated static func hasDatabasesScreen(_ manifest: FlavourManifest?) -> Bool { manifest?.isSingleDatabase != true } /// Give a window that has not chosen — or whose database is no longer /// held — the model's opening database. A choice still held is kept. func seed(from model: DatabasesModel) async { if let shownId, model.database(shownId) != nil { // Already aimed and pinned here: the held list moving under the // window — a database arriving, a sync line, a roster — changes // nothing of it. Each move aimed the window again, and its Home // and catalogue were asked again with every database that // arrived after a launch (295 B, walker294). if pinned == shownId, calls.id == Self.calls(of: shownId, in: model) { return } // A choice restored from the scene's storage was never pinned. point(at: shownId, in: model) await pin(shownId, in: model) return } guard let opening = model.opening else { return } await show(opening.databaseId, in: model) } /// Show `id` in this window, and close its Databases screen. Other windows /// are untouched. /// /// **Read, then turn.** A switch from a database shown awaits `prepare` /// for `id` first — the window's calls, its shown id and its pin stay on /// the old database meanwhile, so a read still out for the old Home /// answers into it — and only then aims the calls, moves the shown id /// and pins, in one step: the frame that shows `id` draws its kept Home. /// A refused read still turns. A newer turn asked while this one reads /// wins, and this one turns nothing (`false`). A window showing nothing /// yet (a launch) has no Home to stand on and turns at once. @discardableResult func show(_ id: String, in model: DatabasesModel) async -> Bool { turning += 1 let asked = turning if id != shownId, shownId != nil, let prepare { await prepare(id, Self.calls(of: id, in: model)) guard asked == turning else { return false } } point(at: id, in: model) if id != shownId { places.forget(database: id) } shownId = id choosing = false // After the turn: the pin's own read of the held list never delays it. await pin(id, in: model) return true } /// The window stays on the database it shows (a cap turned back to it): /// a turn still reading for another commits nothing. func stay() { turning += 1 } /// The person's own pick on the Databases screen: shown as any other, and /// counted — a link that places itself in a database is not a pick, and /// must not leave the project it is on its way to. func pick(_ id: String, in model: DatabasesModel) async { guard await show(id, in: model) else { return } picks += 1 } /// What the window's calls name for `id`: nil for the personal database. private static func calls(of id: String, in model: DatabasesModel) -> String? { model.database(id)?.isPersonal == false ? id : nil } /// Aim this window's calls at `id` — BEFORE `shownId` moves, so whatever /// re-reads on the change already reads the new database. private func point(at id: String, in model: DatabasesModel) { calls.id = Self.calls(of: id, in: model) aimed?(id) } private func pin(_ id: String, in model: DatabasesModel) async { guard pinned != id else { return } let left = pinned pinned = id await model.opened(id) if let left { await model.closed(left) } } /// This window closed for good: the pin it held is given back. func leave(in model: DatabasesModel) async { guard let left = pinned else { return } pinned = nil await model.closed(left) } }