// `DevicesModel` — the devices read and the pending queue Home and the settings sheet share — driven through its model and its pure words.//// What is NOT carried across, with the reason://// • the router assertions ("Pair now opens /auth with the server filled in",// "'Scan a device's code' opens the Scanner") are about the old router.// Here both are closures the host supplies, so what is held is that the// SCREEN calls them — which is a `RootView` wiring fact, named in this// lane's report, not a model fact.// • the query-key assertions and their invalidation spies belong to a query// cache. There is no query cache here: a landed verb re-reads both lists// itself, and that is asserted below by the methods actually called.// • the two hook cases for `useThisDeviceId` — the phone compared the// device key's own public half; the crate answers `thisDevice` in the list,// so the assertion moved to "the row the server named wears the badge".//// Every device id, name and number here is invented.importCottonKitimport XCTest@testable importCottonUI@MainActorfinalclassDevicesTests: XCTestCase {// ── Fixtures ─────────────────────────────────────────────────────────privatelet thisPhone = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"privatelet macId = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"privatelet oldId = "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"privatelet padId = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"privatelet droidId = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"/// A fixed instant. Never the wall clock: `NOW` is/// `2026-09-06T10:00:00.000Z`, the same one the TypeScript pins.privatelet now = Date(timeIntervalSince1970: 1_788_688_800)/// One row, shaped exactly as `routes/devices.rs::public_row` writes it —/// twelve keys, every one PRESENT, a missing column as `null`.privatefunc row( id: String, name: String, platform: String? = "mac", appVersion: String? = "1.0.0", approvedAt: String = "2026-09-01T10:00:00.000Z", approvedBy: String = "self", lastSeenAt: String? = "2026-09-06T08:00:00.000Z", revokedAt: String? = nil, revokedBy: String? = nil, revokedReason: String? = nil, recoveryKeyShownAt: String? = nil, serving: Bool? = nil ) -> String {func text(_ value: String?) -> String { value.map { "\"\($0)\"" } ?? "null" }func flag(_ value: Bool?) -> String { value.map { $0 ? "true" : "false" } ?? "null" }return""" { "deviceId": "\(id)", "name": "\(name)", "platform": \(text(platform)), "appVersion": \(text(appVersion)), "approvedAt": "\(approvedAt)", "approvedBy": "\(approvedBy)", "lastSeenAt": \(text(lastSeenAt)), "revokedAt": \(text(revokedAt)), "revokedBy": \(text(revokedBy)), "revokedReason": \(text(revokedReason)), "recoveryKeyShownAt": \(text(recoveryKeyShownAt)), "serving": \(flag(serving)) } """ }privatevar mac: String { row(id: macId, name: "Study Mac") }privatevar phone: String { row( id: thisPhone, name: "Test Phone", platform: "ios", appVersion: "1.2.3", approvedAt: "2026-09-02T10:00:00.000Z", approvedBy: macId, lastSeenAt: "2026-09-06T09:59:30.000Z" ) }privatevar old: String { row( id: oldId, name: "Old phone", platform: "ios", approvedBy: macId, revokedAt: "2026-09-05T10:00:00.000Z", revokedBy: thisPhone, revokedReason: "lost" ) }privatefunc list(_ rows: [String], thisDevice: String? = nil) -> String {let named = thisDevice.map { "\"\($0)\"" } ?? "null"return"{\"devices\":[\(rows.joined(separator: ","))],\"thisDevice\":\(named)}" }/// A refusal envelope carrying `details.status`, which is what/// `phone/owner.rs::refused` builds and what `OwnerRefusal.isTerminal`/// reads. `ScriptedCore.refuse` writes no details, so the envelope is given/// whole.privatefunc refusal(code: String, message: String, status: Int) -> ScriptedCore.Reply { .garbage(""" {"ok":false,"error":{"code":"\(code)","message":"\(message)", "details":{"status":\(status)}}} """ ) }privatefunc subject( devices: String? = nil, pending: String? = nil, extra: [String: ScriptedCore.Reply] = [:] ) -> (DevicesModel, ScriptedCore, ToastCenter) {var replies: [String: ScriptedCore.Reply] = [:]iflet devices { replies[CottonMethod.readDevices] = .ok(devices) } replies[CottonMethod.devicesPending] = .ok(pending ?? "{\"pending\":[]}")for (method, reply) in extra { replies[method] = reply }let core = ScriptedCore(replies)let toasts = ToastCenter(scheduler: ManualToastScheduler())let model = DevicesModel(core: core, toasts: toasts)return (model, core, toasts) }/// The `args` a call carried, read back off the wire.privatefunc sent(_ json: String?) -> [String: Any]? {guardlet data = json?.data(using: .utf8) else { returnnil }returntry? JSONSerialization.jsonObject(with: data) as? [String: Any] }// ── The digits are never on the wire ─────────────────────────────────/// **The digits that travel are the ROW's, and nothing else's.**////// The rule inverted with the mechanism and the guard inverted with it. The/// number used to be a secret typed here off the joining phone's screen, so/// a row carrying one would have handed the second factor to whoever could/// read the list; it is a FINGERPRINT now — the same six reach this device/// and the one asking, and seeing them match is the whole of the check — so/// the row carries it and the screen draws it.////// What travels back is an ECHO of what was drawn: not a proof of who is/// asking (the signature is that) but a proof of WHICH request the person/// was looking at. The fixture carries the joining device's KEY as well —/// the field `pending_row` still drops on the floor, because the digits are/// a pure function of it and the pairing id — and nothing reads it.func testTheDigitsThatTravelAreTheRowsOwn() asyncthrows {let wire = """ {"pending":[{ "pairingId":"p-1", "deviceId":"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD", "name":"Kitchen phone","platform":"ios","appVersion":"1.2.3", "createdAt":"2026-09-06T08:00:00.000Z", "expiresAt":"2026-09-06T08:05:00.000Z", "digits":"123456" }]} """let (model, core, _) = subject( devices: list([mac]), pending: wire, extra: [CottonMethod.devicesApprovePending: .ok("{\"approved\":true}")] )await model.load()let pairing = try XCTUnwrap(model.pending.first)// The seven the screen draws, and they are the seven the crate projects. XCTAssertEqual(pairing.text("pairingId"), "p-1") XCTAssertEqual(pairing.text("name"), "Kitchen phone") XCTAssertEqual(pairing.text("platform"), "ios") XCTAssertEqual(pairing.text("appVersion"), "1.2.3") XCTAssertEqual(pairing.text("createdAt"), "2026-09-06T08:00:00.000Z") XCTAssertEqual(pairing.text("expiresAt"), "2026-09-06T08:05:00.000Z") XCTAssertEqual(pairing.text("digits"), "123456")await model.approvePending(pairing)let calls = await core.callslet approve = try XCTUnwrap( calls.first { $0.method == CottonMethod.devicesApprovePending } )let body = try XCTUnwrap(sent(approve.requestJSON)) XCTAssertEqual( body["digits"] as? String,"123456","the echo is the row's own number, which is the one the person compared" )// Two keys and no third: the joining device's key does not travel back// — the pairing id is what names the row. XCTAssertEqual(Set(body.keys), ["pairingId", "digits"]) }/// The other half of the rule, said as a sweep: no file on this screen/// carries a number of its own. A `digits` on this screen is read off the/// ANSWER or it is not drawn — anything computed, folded from typing, or/// derived here would be a second opinion about a number only the server/// can answer.////// A DIRECTORY walk and never a file list: a three-file list is green on/// the day a fourth file starts typing digits. The directory is this lane's/// own (`Sources/CottonUI/Screens/Devices`), and finding nothing/// there fails loudly rather than passing on an empty sweep.func testNothingOnThisScreenTakesADigitFromAnybodyButTheServer() throws {let prefix = "CottonUI/Screens/Devices/"let screen = trySourceSweep.swiftSources().filter { $0.name.hasPrefix(prefix) } XCTAssertGreaterThan( screen.count,0,""" the sweep found \(screen.count) files under \(prefix) — did the screen move? \ That directory is this lane's; grep it repo-wide (Tests and every open \ worktree included) before changing this guard. """ )for (name, text) in screen {let code = SourceSweep.withoutComments(text)// A keypad, a one-time-code fill, or a fold over typed input:// every shape of a person putting a NUMBER in. (A plain text field// is not one.) Nobody// types digits any more.for spelling in ["keyboardType", "oneTimeCode", "pairingDigitsTyped", "digitCursor"] { XCTAssertFalse( code.contains(spelling),"\(name) has somewhere to type a number — the six digits are compared, never entered" ) } } }func testTheSixBoxesHoldTheServersOwnAnswerOrNoneAtAll() { XCTAssertEqual(pairingDigitSlots("482913"), ["4", "8", "2", "9", "1", "3"])// A row the server could not answer six digits for asks no question,// so it fills no boxes and offers no Approve. XCTAssertEqual(pairingDigitSlots(""), []) XCTAssertEqual(pairingDigitSlots("48291"), []) XCTAssertEqual(pairingDigitSlots("4829134"), []) XCTAssertEqual(pairingDigitSlots("१२३४५६"), []) }/// A server too old to answer the digits is told so, and nothing is/// approved: the second factor IS seeing the same six on both screens, so/// an approve with nothing to compare would be an approve with no second/// factor at all.func testARowWithNoNumberIsNotApprovedAtAll() asyncthrows {let (model, core, toasts) = subject( devices: list([mac]), pending: """ {"pending":[{"pairingId":"p-9","name":"Kitchen phone","platform":"ios", "appVersion":null,"createdAt":"2026-09-06T09:58:00.000Z", "expiresAt":"2026-09-06T10:03:00.000Z","digits":null}]} """, extra: [CottonMethod.devicesApprovePending: .ok("{\"approved\":true}")] )await model.load()let pairing = try XCTUnwrap(model.pending.first)await model.approvePending(pairing) XCTAssertEqual(toasts.current?.tone, .error)let calls = await core.methodsCalled() XCTAssertFalse(calls.contains(CottonMethod.devicesApprovePending)) }func testTheApproveBodyCarriesThePairingAndItsDigits() asyncthrows {let (model, core, _) = subject( devices: list([mac]), pending: """ {"pending":[{"pairingId":"p-1","name":"Kitchen phone","platform":"ios", "appVersion":"1.2.3","createdAt":"2026-09-06T09:58:00.000Z", "expiresAt":"2026-09-06T10:03:00.000Z","digits":"123456"}]} """, extra: [CottonMethod.devicesApprovePending: .ok("{\"approved\":true}")] )await model.load()let pairing = try XCTUnwrap(model.pending.first)await model.approvePending(pairing)let calls = await core.callslet approve = try XCTUnwrap( calls.first { $0.method == CottonMethod.devicesApprovePending } )let body = try XCTUnwrap(sent(approve.requestJSON)) XCTAssertEqual(body["pairingId"] as? String, "p-1") XCTAssertEqual(body["digits"] as? String, "123456") }func testDeclineNamesThePairingAndNothingElse() asyncthrows {let (model, core, _) = subject( devices: list([mac]), pending: """ {"pending":[{"pairingId":"p-2","name":"Kitchen phone","platform":null, "appVersion":null,"createdAt":"2026-09-06T09:58:00.000Z", "expiresAt":"2026-09-06T10:03:00.000Z"}]} """, extra: [CottonMethod.devicesDeclinePending: .ok("{\"ok\":true}")] )await model.load()let pairing = try XCTUnwrap(model.pending.first)await model.declinePending(pairing)let calls = await core.callslet decline = try XCTUnwrap( calls.first { $0.method == CottonMethod.devicesDeclinePending } ) XCTAssertEqual(sent(decline.requestJSON)?["pairingId"] as? String, "p-2") }func testANumberThatDidNotMatchIsOneSentenceAndTheRowStays() asyncthrows {let (model, _, toasts) = subject( devices: list([mac]), pending: """ {"pending":[{"pairingId":"p-1","name":"Kitchen phone","platform":"ios", "appVersion":null,"createdAt":"2026-09-06T09:58:00.000Z", "expiresAt":"2026-09-06T10:03:00.000Z","digits":"000000"}]} """, extra: [CottonMethod.devicesApprovePending: refusal( code: "pairing_refused", message: "refused", status: 403 ) ] )await model.load()let pairing = try XCTUnwrap(model.pending.first)await model.approvePending(pairing) XCTAssertEqual(toasts.current?.message, DeviceRefusalWords.sentence(forCode: "pairing_refused")) XCTAssertEqual(toasts.current?.tone, .error) XCTAssertEqual(model.pending.count, 1, "the row stays for another try") XCTAssertNil(model.busyPairing) }func testNothingWaitingIsNoCardAtAll() async {let (model, _, _) = subject(devices: list([mac]))await model.load() XCTAssertTrue(model.pending.isEmpty) }// ── This phone ───────────────────────────────────────────────────────func testTheServerSaysWhichRowIsThisPhone() async {let (model, _, _) = subject( devices: list([mac, phone, old], thisDevice: thisPhone) )await model.load() XCTAssertEqual(model.thisDeviceId, thisPhone) XCTAssertTrue(model.isThisPhone(model.devices[1])) XCTAssertFalse(model.isThisPhone(model.devices[0])) }func testAListWithNoThisDeviceMarksNoRow() async {let (model, _, _) = subject(devices: list([mac, phone]))await model.load() XCTAssertNil(model.thisDeviceId) XCTAssertFalse(model.devices.contains(where: model.isThisPhone)) }// ── The approved list, and its refusals ──────────────────────────────func testTheRowsAreReadOffTheFileOnceAndNeverOffTheRegistry() async {// ONE local read, no retry: the rows are `cotton_devices`, synced// and on this phone, so the list is on screen before any Mac answers// and reads the same on a train. `devices.list` over HTTP is asked// by nothing here any more.let (model, core, _) = subject(devices: list([mac, phone], thisDevice: thisPhone))await model.load() XCTAssertEqual(model.ordered.count, 2) XCTAssertFalse(model.isFirstRead)let asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.readDevices, CottonMethod.devicesPending], "the file first, the Mac after") XCTAssertFalse(asked.contains("devices.list")) }func testAFileThatCouldNotBeReadIsASentenceNotASkeleton() async {let (model, core, _) = subject( extra: [CottonMethod.readDevices: refusal( code: "not_connected", message: "no file is open", status: 0 ) ] )await model.load() XCTAssertNotNil(model.refusalSentence) XCTAssertTrue(model.showsRefusal) XCTAssertFalse(model.isFirstRead, "a read that failed has still answered, and must have an end")let asked = await core.methodsCalled().filter { $0 == CottonMethod.readDevices } XCTAssertEqual(asked.count, 1, "a local read that failed is not asked again a second later") }func testTheRefusalLadderInItsOwnOrder() {// The gate's refusals are the core's to word now (`shell.home`); the// ones the shell still words itself are the Keychain's.let gateRefusal = CottonCallError( code: "device_key_unreadable", message: "no", details: .object(["status": .number(401)]) )let namedCode = CottonCallError( code: "device_last_full", message: "no", details: .object(["status": .number(403)]) )let unknown = CottonCallError( code: "some_new_word", message: "no", details: .object(["status": .number(500)]) )// The server's STANDING refusal of this phone is no arm here any// more: the rows are the file's and stay readable under it, and the// refusal is the banner over the whole app (`BootModel.readOnly`).// 1. the read's own refusal, read as a gate refusal.let gate = DeviceRefusalWords.cardSentence(error: gateRefusal) XCTAssertEqual(gate, ServerRefusal.of(code: "device_key_unreadable")?.title)// 2. else the code's own sentence.let named = DeviceRefusalWords.cardSentence(error: namedCode) XCTAssertEqual(named, DeviceRefusalWords.sentence(forCode: "device_last_full"))// 3. else the last resort — about the file, not the server.let last = DeviceRefusalWords.cardSentence(error: unknown) XCTAssertNotNil(gate) XCTAssertNotNil(last) XCTAssertEqual(Set([gate, named, last]).count, 3, "each rung says its own sentence")// …and nothing at all when there is no error. XCTAssertNil(DeviceRefusalWords.cardSentence(error: nil)) }/// RULE: every refusal code the server names has its own non-empty sentence, no two alike, and an unknown code has none.func testEveryRefusalCodeHasItsOwnSentenceAndAnUnknownOneHasNone() {let codes = ["pairing_refused", "pairing_not_found", "pairing_ambiguous","device_last_full", "rekey_needs_another_device", "rekey_not_approved", "serving_twin", "bad_request"]let sentences = codes.compactMap { DeviceRefusalWords.sentence(forCode: $0) } XCTAssertEqual(sentences.count, codes.count, "every named code has a sentence") XCTAssertFalse(sentences.contains(where: \.isEmpty)) XCTAssertEqual(Set(sentences).count, sentences.count, "no two codes share a sentence") XCTAssertNil(DeviceRefusalWords.sentence(forCode: "something_else")) XCTAssertNil(DeviceRefusalWords.sentence(forCode: nil)) }func testAReadThatFailedLaterIsSaidInTheCardAndNeverToasted() async {// The screen draws the sentence as the FIRST arm of its chain, so a// file that stopped reading replaces the list the person was reading// — rows nobody can vouch for are not rows. And nothing is toasted:// this READ has no toast at all. The screen's one error toast is// called only by its three MUTATION flows (decide a pending device,// rename, revoke), which DO toast here too.let (model, core, toasts) = subject(devices: list([mac, phone]))await model.load() XCTAssertEqual(model.ordered.count, 2)await core.answer(CottonMethod.readDevices, refusal(code: "not_connected", message: "no file is open", status: 0) )await model.loadDevices() XCTAssertTrue(model.showsRefusal, "the sentence replaces the rows") XCTAssertNotNil(model.refusalSentence) XCTAssertNil(toasts.current, "the card says it; nothing else does") }func testLiveRowsComeFirstAndRemovedOnesAfter() async {let (model, _, _) = subject(devices: list([old, mac, phone]))await model.load() XCTAssertEqual(model.ordered.map(\.deviceId), [macId, thisPhone, oldId]) }/// A key re-approved after a removal holds a row per approval (store/// version 41). The device is the KEY: it is drawn once, as it stands.func testAKeyApprovedAgainIsOneDeviceDrawnAsItsLiveApproval() async {let removedEarlier = row( id: macId, name: "Study Mac (first approval)", approvedAt: "2026-08-20T10:00:00.000Z", revokedAt: "2026-08-25T10:00:00.000Z", revokedBy: thisPhone, revokedReason: "revoked" )// Newest approval first, as the answer sends them — and the removed// one AFTER the live one, so neither order in the answer decides it.let (model, _, _) = subject(devices: list([removedEarlier, mac, phone, old]))await model.load() XCTAssertEqual(model.ordered.map(\.deviceId), [macId, thisPhone, oldId]) XCTAssertEqual(model.ordered.first?.name, "Study Mac") XCTAssertNil(model.ordered.first?.revokedAt) XCTAssertEqual(model.deviceLines.map(\.id), [macId, thisPhone, oldId], "one line per key")// A key whose every approval is removed is ONE removed line: its newest.let removedLater = row( id: oldId, name: "Old phone, approved again", platform: "ios", approvedAt: "2026-09-04T10:00:00.000Z", approvedBy: macId, revokedAt: "2026-09-05T12:00:00.000Z", revokedBy: thisPhone, revokedReason: "lost" )let (again, _, _) = subject(devices: list([removedLater, mac, old]))await again.load() XCTAssertEqual(again.ordered.map(\.deviceId), [macId, oldId]) XCTAssertEqual(again.ordered.last?.name, "Old phone, approved again") }// ── What a row reads ─────────────────────────────────────────────────func testARowTheMacRetiredWhenItRestoredItselfReadsRestoredNotRemoved() asyncthrows {let restored = row( id: oldId, name: "Old root", approvedBy: "self", revokedAt: "2026-09-05T10:00:00.000Z", revokedBy: "self", revokedReason: "restored" )let (model, _, _) = subject(devices: list([mac, restored]))await model.load()let old = try XCTUnwrap(model.devices.first { $0.deviceId == oldId }) XCTAssertTrue(old.isRevoked) XCTAssertEqual(old.revokedReason, "restored") }func testAPendingReadThatFailedLeavesTheLastAnswerAndSaysNothing() async {let (model, core, toasts) = subject( devices: list([mac]), pending: """ {"pending":[{"pairingId":"p-1","name":"Kitchen phone","platform":"ios", "appVersion":null,"createdAt":"2026-09-06T09:58:00.000Z", "expiresAt":"2026-09-06T10:03:00.000Z"}]} """ )await model.load() XCTAssertEqual(model.pending.count, 1)await core.answer(CottonMethod.devicesPending, refusal(code: "no_connection", message: "nothing answered", status: 0) )await model.loadPending() XCTAssertEqual(model.pending.count, 1, "the last answer stays on screen") XCTAssertNil(toasts.current, "the pending list has no failure surface, and must not grow one") }// ── The twelve keys, built off the shape the Rust writes ────────────/// `ApprovedDevice` is the one type this screen kept, because the list/// sorts, groups, names its own actors and arms a Remove against one id./// So the twelve keys are held HERE, at its `init(_ json:)`, where they are/// spelled — one case for the shape, rather than a decoder nobody has any/// more.func testADeviceRowIsBuiltFromEveryKeyPublicRowWritesAndSurvivesTheNulls() async {let (model, _, _) = subject(devices: list([mac, old], thisDevice: macId))await model.load() XCTAssertEqual(model.thisDeviceId, macId)let macRow = model.devices[0] XCTAssertEqual(macRow.deviceId, macId) XCTAssertEqual(macRow.name, "Study Mac") XCTAssertEqual(macRow.platform, "mac") XCTAssertEqual(macRow.appVersion, "1.0.0") XCTAssertEqual(macRow.approvedAt, "2026-09-01T10:00:00.000Z") XCTAssertEqual(macRow.approvedBy, "self") XCTAssertEqual(macRow.lastSeenAt, "2026-09-06T08:00:00.000Z") XCTAssertNil(macRow.serving, "the fixture's Mac says nothing about the line") XCTAssertNil(macRow.revokedAt) XCTAssertNil(macRow.revokedBy) XCTAssertNil(macRow.revokedReason) XCTAssertNil(macRow.recoveryKeyShownAt) XCTAssertFalse(macRow.isRevoked)let oldRow = model.devices[1] XCTAssertTrue(oldRow.isRevoked) XCTAssertEqual(oldRow.revokedBy, thisPhone) XCTAssertEqual(oldRow.revokedReason, "lost") }func testAnAnswerMissingKeysAltogetherReadsAsNothingRatherThanFailing() async {// The crate may land a field before this app reads it, and an app that// refused on an unknown shape would be a phone bricked by a core it// links in the same binary. So: absent keys read as nothing, and an// extra key is ignored.let sparse = """ {"devices":[{"deviceId":"\(macId)","name":"Study Mac","somethingNew":7}]} """let (model, _, _) = subject(devices: sparse)await model.load() XCTAssertEqual(model.devices.count, 1) XCTAssertNil(model.thisDeviceId) XCTAssertNil(model.devices[0].platform) XCTAssertNil(model.devices[0].approvedAt) XCTAssertEqual(model.devices[0].name, "Study Mac")let (empty, _, _) = subject(devices: "{}", pending: "{}")await empty.load() XCTAssertTrue(empty.devices.isEmpty) XCTAssertTrue(empty.pending.isEmpty) }}