oficina / base Public

Store and People models: polling, the owner's writes, and the busy rule

Task 8 of the native slice 2 part 1 plan.

StoreModel (@MainActor @Observable):
- P4's polling: every 2 s while a row is installing and the screen shows;
  none when nothing installs or once the screen has gone; after errors
  2, 4, 8 s, then every 15 s; stops on 401.
- Install and Try again show installing at once, and put the row back if
  Base couldn't start it. Uninstall waits for confirmation
  (pendingUninstall), with the web's words.
- busy has the web's words; a failed row shows its reason or "The install
  didn't finish."; a member gets no buttons (Installed is a tag).
- Only a row turning installed or failed is announced, once, never the
  first read or a poll that changes nothing.

PeopleModel: loads; invite trims and lowercases; bad_email and
mail_failed in the web's words, announced (the web's role="status");
success clears the field and reloads; Invite is busy from the tap until
Base answers and at least 650 ms have passed. Uninstall keeps the same
rule.

Strings: the web's words, plus three drafts for Luna (DRAFT 2026-11-28,
copy-review/slice2-part1.json): the two install announcements and "Base
didn't answer. Try again in a moment."

Gate: swift test -j 4 --filter 'BaseKitTests.StoreModelTests|BaseKitTests.PeopleModelTests':
18 passed. check-strings.py: ok.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Summary

Task 8: StoreModel and PeopleModel
claude agent, operated by paul@keymail.dev dd65bf1d6cfef79a7e5e6e3f4b51cf27b2b5f580 parent 7a0cb1e
4 files changed, +683 −0
  • native/apple/Sources/BaseKit/Resources/Localizable.xcstrings +96 −0
  • native/apple/Sources/BaseKit/Team/PeopleModel.swift +84 −0
  • native/apple/Sources/BaseKit/Team/StoreModel.swift +226 −0
  • native/apple/Tests/BaseKitTests/StoreModelTests.swift +277 −0
diff --git a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
index 3af3278..f13bc3c 100644
--- a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
@@ -829,6 +829,30 @@
}
}
},
+ "native.people.bad_email": {
+ "comment": "Base on the web's approved copy (people.html). People's line when the invite's address isn't one.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "That doesn't look like an email address."
+ }
+ }
+ }
+ },
+ "native.people.mail_failed": {
+ "comment": "Base on the web's approved copy (people.html). People's line when the invitation email wasn't delivered.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The invitation wasn't sent. Try inviting them again."
+ }
+ }
+ }
+ },
"native.phone.account_a11y": {
"comment": "The round button top right, with the person's initials, that opens the account menu.",
"extractionState": "manual",
@@ -1441,6 +1465,78 @@
}
}
},
+ "native.store.announce.failed": {
+ "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). Said by VoiceOver when an install fails. {app} is its name, {reason} Base's reason or 'The install didn't finish.'",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "{app} didn't install: {reason}"
+ }
+ }
+ }
+ },
+ "native.store.announce.installed": {
+ "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). Said by VoiceOver when an app the Store was showing as installing finishes. {app} is its name.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "{app} is installed."
+ }
+ }
+ }
+ },
+ "native.store.busy": {
+ "comment": "Base on the web's approved copy (store.html, install.ErrBusy). The Store's line when Uninstall is refused because the app is still installing.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This app is still installing. Try again in a moment."
+ }
+ }
+ }
+ },
+ "native.store.failed": {
+ "comment": "Base on the web's approved copy (store.html). A failed app's line in the Store when Base gives no reason.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The install didn't finish."
+ }
+ }
+ }
+ },
+ "native.store.uninstall.confirm": {
+ "comment": "Base on the web's approved copy (uninstall.html). The Store's Uninstall confirmation. {app} is the app's name, {base} the Base's name.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Uninstall {app}? It's removed from Home for everyone at {base}. Its data is kept, and comes back if you install it again."
+ }
+ }
+ }
+ },
+ "native.team.unavailable": {
+ "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). Store and People: a read or write that Base didn't answer (offline, or Base couldn't read its own store).",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Base didn't answer. Try again in a moment."
+ }
+ }
+ }
+ },
"native.wordmark": {
"comment": "Not in copy review: Base's wordmark, as the web's templates write it (lowercase), beside the mark on the sign-in screen.",
"extractionState": "manual",
diff --git a/native/apple/Sources/BaseKit/Team/PeopleModel.swift b/native/apple/Sources/BaseKit/Team/PeopleModel.swift
new file mode 100644
index 0000000..c1259ab
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Team/PeopleModel.swift
@@ -0,0 +1,84 @@
+import Foundation
+import SwiftUI
+
+/// People, natively (spec 7.4): everyone here, and the owner's invite.
+/// Nothing removes a member, as on the web.
+@MainActor @Observable public final class PeopleModel {
+ public private(set) var people: PeopleData?
+ /// This Base has no People route: the app opens the web page (P3).
+ public private(set) var notOnThisBase = false
+ /// The last read failed and there is nothing to show.
+ public private(set) var failed = false
+ /// The invite field.
+ public var email = ""
+ /// Invite's busy state: from the tap until Base has answered and at
+ /// least 650 ms have passed (the busy rule).
+ public private(set) var inviting = false
+ /// The invite's refusal, in the web's words (its `role="status"`).
+ public private(set) var error: String?
+ public private(set) var work: Task<Void, Never>?
+
+ let client: BaseClient
+ let announce: @MainActor (String) -> Void
+ let hold: @MainActor (Duration) async -> Void
+
+ public init(client: BaseClient, announce: @escaping @MainActor (String) -> Void = AskModel.announce,
+ hold: @escaping @MainActor (Duration) async -> Void = StoreModel.sleep) {
+ self.client = client; self.announce = announce; self.hold = hold
+ }
+
+ /// How many people are here, once People has loaded (the apps sheet's
+ /// count); nil before.
+ public var count: Int? { people?.people.count }
+
+ public func appear() { work = Task { await load() } }
+
+ func load() async {
+ do {
+ people = try await client.people()
+ failed = false
+ } catch .notOnThisBase {
+ notOnThisBase = true
+ } catch {
+ failed = people == nil
+ }
+ }
+
+ public func invite() {
+ let address = email.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ guard !address.isEmpty, !inviting, people?.owner == true else { return }
+ inviting = true
+ error = nil
+ let started = ContinuousClock.now
+ work = Task {
+ defer { inviting = false }
+ do throws(BaseAPIError) {
+ _ = try await client.invite(email: address)
+ await holdBusy(since: started)
+ email = ""
+ await load()
+ } catch {
+ await holdBusy(since: started)
+ refused(error)
+ }
+ }
+ }
+
+ private func holdBusy(since started: ContinuousClock.Instant) async {
+ let left = StoreModel.busyAtLeast - (ContinuousClock.now - started)
+ if left > .zero { await hold(left) }
+ }
+
+ private func refused(_ error: BaseAPIError) {
+ let line: String
+ switch error {
+ case .unauthenticated: return
+ case .notOnThisBase: notOnThisBase = true; return
+ case .team(.badEmail): line = BaseText.text("native.people.bad_email")
+ case .team(.mailFailed): line = BaseText.text("native.people.mail_failed")
+ default: line = BaseText.text("native.team.unavailable")
+ }
+ self.error = line
+ announce(line)
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Team/StoreModel.swift b/native/apple/Sources/BaseKit/Team/StoreModel.swift
new file mode 100644
index 0000000..cd40e41
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Team/StoreModel.swift
@@ -0,0 +1,226 @@
+import Foundation
+import SwiftUI
+
+/// The Store, natively (spec 7.4): the catalogue with each app's state, and
+/// the owner's Install, Try again and Uninstall. The web's page refreshes
+/// every 2 s while an app installs; this polls the same way (plan P4):
+/// - every 2 s while a row is installing and the screen shows;
+/// - not at all when nothing is installing, or once the screen has gone;
+/// - after an error, 2, 4, 8 s, then every 15 s;
+/// - never again after a 401 (the session signs in again).
+///
+/// Polling never moves VoiceOver: only a row that turns installed or failed
+/// is announced, once.
+@MainActor @Observable public final class StoreModel {
+ /// What a row offers.
+ public enum Action: Equatable { case install, tryAgain, uninstall, installing, installedTag, none }
+
+ public private(set) var store: StoreData?
+ /// This Base has no Store route: the app opens the web page (P3).
+ public private(set) var notOnThisBase = false
+ /// The last read failed and there is nothing to show.
+ public private(set) var failed = false
+ /// A line under the heading (the web's `role="status"`): busy, or a
+ /// write that didn't happen.
+ public private(set) var notice: String?
+ /// The row waiting for Uninstall's confirmation.
+ public private(set) var pendingUninstall: StoreRow?
+ /// The app being uninstalled (its button busy).
+ public private(set) var uninstalling: String?
+ /// The read or write running now, for tests and the screen's refresh.
+ public private(set) var work: Task<Void, Never>?
+
+ let client: BaseClient
+ let baseName: String
+ let schedule: @MainActor (Duration, @escaping @MainActor () -> Void) -> Void
+ let announce: @MainActor (String) -> Void
+ let hold: @MainActor (Duration) async -> Void
+ private var showing = false
+ private var failures = 0
+ private var stopped = false
+ /// Bumped when the screen goes, so a scheduled poll from before does nothing.
+ private var generation = 0
+ private var pollScheduled = false
+
+ public init(client: BaseClient, baseName: String,
+ schedule: @escaping @MainActor (Duration, @escaping @MainActor () -> Void) -> Void = AskModel.later,
+ announce: @escaping @MainActor (String) -> Void = AskModel.announce,
+ hold: @escaping @MainActor (Duration) async -> Void = StoreModel.sleep) {
+ self.client = client; self.baseName = baseName; self.schedule = schedule; self.announce = announce; self.hold = hold
+ }
+
+ public static func sleep(_ d: Duration) async { try? await Task.sleep(for: d) }
+
+ /// The busy rule: a button's spinner shows for at least this long.
+ static let busyAtLeast = Duration.milliseconds(650)
+
+ // MARK: The screen
+
+ public func appear() {
+ showing = true
+ stopped = false
+ generation += 1
+ pollScheduled = false
+ read()
+ }
+
+ public func disappear() {
+ showing = false
+ generation += 1
+ pollScheduled = false
+ }
+
+ private func read() {
+ work = Task { await load() }
+ }
+
+ func load() async {
+ do {
+ let next = try await client.store()
+ failures = 0
+ failed = false
+ apply(next)
+ } catch .unauthenticated {
+ stopped = true
+ return
+ } catch .notOnThisBase {
+ notOnThisBase = true
+ return
+ } catch {
+ failures += 1
+ failed = store == nil
+ }
+ poll()
+ }
+
+ /// Schedules the next read while it is wanted: 2 s while installing,
+ /// longer after errors.
+ private func poll() {
+ guard showing, !stopped, !pollScheduled else { return }
+ let wanted = failures > 0 || (store?.installing ?? false)
+ guard wanted else { return }
+ let delay: Duration = switch failures {
+ case 0, 1: .seconds(2)
+ case 2: .seconds(4)
+ case 3: .seconds(8)
+ default: .seconds(15)
+ }
+ pollScheduled = true
+ let epoch = generation
+ schedule(delay) { [weak self] in
+ guard let self, self.generation == epoch, self.showing else { return }
+ self.pollScheduled = false
+ self.read()
+ }
+ }
+
+ /// Takes Base's store, announcing each row that became installed or
+ /// failed since the last one (never on the first, or on no change).
+ private func apply(_ next: StoreData) {
+ if let before = store {
+ let old = Dictionary(before.rows.map { ($0.id, $0.state) }, uniquingKeysWith: { a, _ in a })
+ for row in next.rows where old[row.id] != row.state {
+ switch row.state {
+ case .installed: announce(BaseText.format("native.store.announce.installed", ["app": row.name]))
+ case .failed: announce(BaseText.format("native.store.announce.failed", ["app": row.name, "reason": reason(row)]))
+ default: break
+ }
+ }
+ }
+ store = next
+ }
+
+ // MARK: Rows
+
+ public func action(_ row: StoreRow) -> Action {
+ let owner = store?.owner ?? false
+ switch row.state {
+ case .installing: return .installing
+ case .installed: return owner ? .uninstall : .installedTag
+ case .failed: return owner ? .tryAgain : .none
+ case .notInstalled: return owner ? .install : .none
+ }
+ }
+
+ /// A failed row's line: Base's reason, or the web's words.
+ public func reason(_ row: StoreRow) -> String {
+ row.error.isEmpty ? BaseText.text("native.store.failed") : row.error
+ }
+
+ // MARK: Writes (the owner's)
+
+ /// Install, or Try again: the row shows installing at once.
+ public func install(_ id: String) {
+ guard store?.owner == true, let index = store?.rows.firstIndex(where: { $0.id == id }) else { return }
+ let before = store!.rows[index].state
+ store!.rows[index].state = .installing
+ notice = nil
+ work = Task {
+ do throws(BaseAPIError) {
+ apply(try await client.install(app: id))
+ poll()
+ } catch {
+ if let i = store?.rows.firstIndex(where: { $0.id == id }), store?.rows[i].state == .installing { store?.rows[i].state = before }
+ refused(error)
+ }
+ }
+ }
+
+ public func requestUninstall(_ id: String) {
+ guard store?.owner == true, let row = store?.rows.first(where: { $0.id == id }), row.state == .installed else { return }
+ pendingUninstall = row
+ }
+
+ public func cancelUninstall() { pendingUninstall = nil }
+
+ /// The confirmation's words (the web's uninstall page).
+ public var confirmation: String? {
+ pendingUninstall.map { BaseText.format("native.store.uninstall.confirm", ["app": $0.name, "base": baseName]) }
+ }
+
+ public func confirmUninstall() {
+ guard let row = pendingUninstall else { return }
+ pendingUninstall = nil
+ uninstalling = row.id
+ notice = nil
+ let started = ContinuousClock.now
+ work = Task {
+ defer { uninstalling = nil }
+ do throws(BaseAPIError) {
+ let next = try await client.uninstall(app: row.id)
+ await holdBusy(since: started)
+ apply(next)
+ } catch {
+ await holdBusy(since: started)
+ refused(error)
+ }
+ }
+ }
+
+ private func holdBusy(since started: ContinuousClock.Instant) async {
+ let left = Self.busyAtLeast - (ContinuousClock.now - started)
+ if left > .zero { await hold(left) }
+ }
+
+ private func refused(_ error: BaseAPIError) {
+ switch error {
+ case .unauthenticated:
+ stopped = true
+ case .notOnThisBase:
+ notOnThisBase = true
+ case .team(.busy):
+ say(BaseText.text("native.store.busy"))
+ case .team(.ownerOnly), .team(.unknownApp):
+ // The Store changed under the person (no longer the owner, or
+ // the app gone): show it as it is now.
+ read()
+ default:
+ say(BaseText.text("native.team.unavailable"))
+ }
+ }
+
+ private func say(_ line: String) {
+ notice = line
+ announce(line)
+ }
+}
diff --git a/native/apple/Tests/BaseKitTests/StoreModelTests.swift b/native/apple/Tests/BaseKitTests/StoreModelTests.swift
new file mode 100644
index 0000000..80d8482
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/StoreModelTests.swift
@@ -0,0 +1,277 @@
+@testable import BaseKit
+import Foundation
+import RastrilloApple
+import RastrilloTestSupport
+import XCTest
+
+/// Task 8: the Store's model (plan P4: polling while installing).
+@MainActor final class StoreModelTests: XCTestCase {
+ var later: [(Duration, @MainActor () -> Void)] = []
+ var said: [String] = []
+
+ func model(_ steps: [ScriptedTransport.Step], rejections: Rejections = Rejections()) -> (StoreModel, ScriptedTransport) {
+ let t = ScriptedTransport(steps)
+ let m = StoreModel(client: BaseClient(transport: t) { rejections.hit() }, baseName: "Acme",
+ schedule: { [unowned self] delay, body in self.later.append((delay, body)) },
+ announce: { [unowned self] in self.said.append($0) },
+ hold: { _ in })
+ return (m, t)
+ }
+
+ static func store(owner: Bool = true, _ rows: [(String, String, String)]) -> String {
+ let body = rows.map { id, state, error in
+ #"{"id":"\#(id)","name":"\#(id.capitalized)","summary":"","tint":"teal","icon_svg":"","state":"\#(state)","error":"\#(error)"}"#
+ }.joined(separator: ",")
+ return #"{"owner":\#(owner),"rows":[\#(body)]}"#
+ }
+ func store(owner: Bool = true, _ rows: [(String, String, String)]) -> ScriptedTransport.Step { json(200, Self.store(owner: owner, rows)) }
+ func written(_ rows: [(String, String, String)], status: Int = 200) -> ScriptedTransport.Step {
+ json(status, #"{"store":\#(Self.store(rows))}"#)
+ }
+
+ /// Runs the next scheduled poll, and waits for its read.
+ func tick(_ m: StoreModel) async {
+ let (_, body) = later.removeFirst()
+ body()
+ await m.work?.value
+ }
+
+ func testItPollsEveryTwoSecondsWhileInstallingAndTheScreenShows() async {
+ let (m, t) = model([store([("scratchpad", "installing", "")]), store([("scratchpad", "installing", "")]),
+ store([("scratchpad", "installed", "")])])
+ m.appear()
+ await m.work?.value
+ XCTAssertEqual(later.map(\.0), [.seconds(2)])
+ await tick(m)
+ XCTAssertEqual(later.map(\.0), [.seconds(2)])
+ XCTAssertEqual(said, [], "a poll that changes nothing says nothing")
+ await tick(m)
+ XCTAssertEqual(m.store?.rows.first?.state, .installed)
+ XCTAssertTrue(later.isEmpty, "nothing installing: it stops")
+ XCTAssertEqual(said, ["Scratchpad is installed."])
+ XCTAssertEqual(t.calls.count, 3)
+ }
+
+ func testNothingInstallingMeansNoPolling() async {
+ let (m, _) = model([store([("scratchpad", "installed", "")])])
+ m.appear()
+ await m.work?.value
+ XCTAssertTrue(later.isEmpty)
+ XCTAssertEqual(said, [], "the first read announces nothing")
+ }
+
+ func testItStopsWhenTheScreenGoesAway() async {
+ let (m, t) = model([store([("scratchpad", "installing", "")])])
+ m.appear()
+ await m.work?.value
+ m.disappear()
+ later.removeFirst().1()
+ XCTAssertEqual(t.calls.count, 1, "no read once the screen has gone")
+ }
+
+ func testErrorsBackOffTwoFourEightThenFifteen() async {
+ let (m, _) = model([store([("scratchpad", "installing", "")]), .offline(), .offline(), .offline(), .offline(), .offline(),
+ store([("scratchpad", "installing", "")])])
+ m.appear()
+ await m.work?.value
+ var delays: [Duration] = []
+ for _ in 0..<6 {
+ await tick(m)
+ delays.append(later.first!.0)
+ }
+ XCTAssertEqual(delays, [.seconds(2), .seconds(4), .seconds(8), .seconds(15), .seconds(15), .seconds(2)])
+ XCTAssertEqual(m.store?.rows.first?.state, .installing, "the last good store stays on screen")
+ }
+
+ func testARefusedSessionStopsPolling() async {
+ let rejections = Rejections()
+ let (m, _) = model([store([("scratchpad", "installing", "")]), json(401, #"{"code":"unauthenticated"}"#)], rejections: rejections)
+ m.appear()
+ await m.work?.value
+ await tick(m)
+ XCTAssertTrue(later.isEmpty)
+ XCTAssertEqual(rejections.count, 1, "the session handles it")
+ }
+
+ func testInstallShowsInstallingAtOnce() async {
+ let (m, t) = model([store([("scratchpad", "", "")]), written([("scratchpad", "installing", "")], status: 202)])
+ m.appear()
+ await m.work?.value
+ m.install("scratchpad")
+ XCTAssertEqual(m.store?.rows.first?.state, .installing, "before Base answers")
+ await m.work?.value
+ XCTAssertEqual(t.calls.last?.path, "/api/v1/store/scratchpad/install")
+ XCTAssertEqual(later.map(\.0), [.seconds(2)], "and it polls")
+ }
+
+ func testAnInstallThatCantStartPutsTheRowBack() async {
+ let (m, _) = model([store([("contra", "failed", "")]), json(503, #"{"code":"unavailable"}"#)])
+ m.appear()
+ await m.work?.value
+ m.install("contra")
+ await m.work?.value
+ XCTAssertEqual(m.store?.rows.first?.state, .failed)
+ XCTAssertEqual(m.notice, "Base didn't answer. Try again in a moment.")
+ XCTAssertEqual(said, ["Base didn't answer. Try again in a moment."])
+ }
+
+ func testUninstallConfirmsFirst() async {
+ let (m, t) = model([store([("scratchpad", "installed", "")]), written([("scratchpad", "", "")])])
+ m.appear()
+ await m.work?.value
+ m.requestUninstall("scratchpad")
+ XCTAssertEqual(m.pendingUninstall?.id, "scratchpad")
+ XCTAssertEqual(m.confirmation, "Uninstall Scratchpad? It's removed from Home for everyone at Acme. Its data is kept, and comes back if you install it again.")
+ XCTAssertEqual(t.calls.count, 1, "nothing until confirmed")
+ m.cancelUninstall()
+ XCTAssertNil(m.pendingUninstall)
+ m.requestUninstall("scratchpad")
+ m.confirmUninstall()
+ XCTAssertNil(m.pendingUninstall)
+ XCTAssertEqual(m.uninstalling, "scratchpad", "busy while it goes")
+ await m.work?.value
+ XCTAssertNil(m.uninstalling)
+ XCTAssertEqual(t.calls.last?.path, "/api/v1/store/scratchpad/uninstall")
+ XCTAssertEqual(m.store?.rows.first?.state, .notInstalled)
+ }
+
+ func testBusyHasTheWebsWords() async {
+ let (m, _) = model([store([("scratchpad", "installed", "")]), json(409, #"{"code":"busy"}"#)])
+ m.appear()
+ await m.work?.value
+ m.requestUninstall("scratchpad")
+ m.confirmUninstall()
+ await m.work?.value
+ XCTAssertEqual(m.notice, "This app is still installing. Try again in a moment.")
+ XCTAssertEqual(said, ["This app is still installing. Try again in a moment."])
+ }
+
+ func testAFailedRowSaysWhy() async {
+ let (m, _) = model([store([("contra", "failed", "The app did not start answering"), ("scratchpad", "failed", "")])])
+ m.appear()
+ await m.work?.value
+ XCTAssertEqual(m.store?.rows.map(m.reason), ["The app did not start answering", "The install didn't finish."])
+ XCTAssertEqual(m.store?.rows.map(m.action), [.tryAgain, .tryAgain])
+ }
+
+ func testOnlyTheOwnerHasButtons() async {
+ let rows = [("welcome", "installed", ""), ("scratchpad", "installing", ""), ("contra", "", ""), ("other", "failed", "")]
+ let (owner, _) = model([store(rows)])
+ owner.appear()
+ await owner.work?.value
+ XCTAssertEqual(owner.store?.rows.map(owner.action), [.uninstall, .installing, .install, .tryAgain])
+ later = []
+ let (member, _) = model([store(owner: false, rows)])
+ member.appear()
+ await member.work?.value
+ XCTAssertEqual(member.store?.rows.map(member.action), [.installedTag, .installing, .none, .none])
+ member.install("contra")
+ member.requestUninstall("welcome")
+ XCTAssertNil(member.pendingUninstall)
+ }
+
+ func testAFailureIsAnnouncedOnce() async {
+ let (m, _) = model([store([("contra", "installing", "")]), store([("contra", "failed", "Out of space")])])
+ m.appear()
+ await m.work?.value
+ await tick(m)
+ XCTAssertEqual(said, ["Contra didn't install: Out of space"])
+ }
+
+ func testAnOlderBaseOpensTheWeb() async {
+ let (m, _) = model([.respond(status: 404)])
+ m.appear()
+ await m.work?.value
+ XCTAssertTrue(m.notOnThisBase)
+ }
+}
+
+/// Task 8: People's model.
+@MainActor final class PeopleModelTests: XCTestCase {
+ var said: [String] = []
+ var released: CheckedContinuation<Void, Never>?
+ var holds: [Duration] = []
+
+ func model(_ steps: [ScriptedTransport.Step], hold: @escaping @MainActor (Duration) async -> Void = { _ in }) -> (PeopleModel, ScriptedTransport) {
+ let t = ScriptedTransport(steps)
+ return (PeopleModel(client: BaseClient(transport: t) {}, announce: { [unowned self] in self.said.append($0) }, hold: hold), t)
+ }
+
+ let people = json(200, #"{"owner":true,"people":[{"id":"m1","initial":"O","name":"","email":"owner@acme.test","role":"owner"}]}"#)
+ let morePeople = json(200, #"{"owner":true,"people":[{"id":"m1","initial":"O","name":"","email":"owner@acme.test","role":"owner"},{"id":"m2","initial":"M","name":"","email":"maria@acme.test","role":"invited"}]}"#)
+ let invited = json(200, #"{"person":{"id":"m2","initial":"M","name":"","email":"maria@acme.test","role":"invited"}}"#)
+
+ func testItLoads() async {
+ let (m, _) = model([people])
+ m.appear()
+ await m.work?.value
+ XCTAssertEqual(m.people?.people.map(\.email), ["owner@acme.test"])
+ XCTAssertTrue(m.people?.owner ?? false)
+ }
+
+ func testInviteTrimsAndLowercasesThenClearsAndReloads() async throws {
+ let (m, t) = model([people, invited, morePeople])
+ m.appear()
+ await m.work?.value
+ m.email = " Maria@Acme.TEST "
+ m.invite()
+ await m.work?.value
+ let body = try XCTUnwrap(t.calls[1].body)
+ XCTAssertEqual(try JSONSerialization.jsonObject(with: body) as? [String: String], ["email": "maria@acme.test"])
+ XCTAssertEqual(m.email, "")
+ XCTAssertNil(m.error)
+ XCTAssertEqual(t.calls.map(\.path), ["/api/v1/people", "/api/v1/people", "/api/v1/people"])
+ XCTAssertEqual(m.people?.people.count, 2)
+ }
+
+ func testEachRefusalHasTheWebsWordsAndIsAnnounced() async {
+ let (m, _) = model([people, json(422, #"{"code":"bad_email"}"#), json(502, #"{"code":"mail_failed"}"#), .offline()])
+ m.appear()
+ await m.work?.value
+ var errors: [String?] = []
+ for _ in 0..<3 {
+ m.email = "x@acme.test"
+ m.invite()
+ await m.work?.value
+ errors.append(m.error)
+ }
+ let words = ["That doesn't look like an email address.", "The invitation wasn't sent. Try inviting them again.",
+ "Base didn't answer. Try again in a moment."]
+ XCTAssertEqual(errors, words)
+ XCTAssertEqual(said, words)
+ XCTAssertEqual(m.email, "x@acme.test", "a refused address stays to be corrected")
+ }
+
+ func testAnEmptyAddressSendsNothing() async {
+ let (m, t) = model([people])
+ m.appear()
+ await m.work?.value
+ m.email = " "
+ m.invite()
+ XCTAssertFalse(m.inviting)
+ XCTAssertEqual(t.calls.count, 1)
+ }
+
+ /// The busy rule: Invite's label is a spinner from the tap until at
+ /// least 650 ms have passed, however fast Base answers.
+ func testInviteIsBusyForAtLeast650ms() async throws {
+ var release: (() -> Void)?
+ let (m, _) = model([people, invited, morePeople], hold: { [unowned self] d in
+ self.holds.append(d)
+ await withCheckedContinuation { c in release = { c.resume() } }
+ })
+ m.appear()
+ await m.work?.value
+ m.email = "maria@acme.test"
+ m.invite()
+ XCTAssertTrue(m.inviting, "busy at once")
+ try await waitUntil { release != nil }
+ XCTAssertTrue(m.inviting, "still busy after Base answered, until the hold ends")
+ XCTAssertEqual(holds.count, 1)
+ XCTAssertLessThanOrEqual(holds[0], .milliseconds(650))
+ XCTAssertGreaterThan(holds[0], .zero)
+ release?()
+ await m.work?.value
+ XCTAssertFalse(m.inviting)
+ }
+}