Cotton code
245 lines · 11.5 KB · SwiftRaw
// The two tap tables, and the totality guard the design asks for.//// The tap cases: the exact keys in their order, every per-type route// and fallback, an unmapped type answering nothing, the two retired Calls types// ABSENT, and the two tables rejecting each other's payloads.//// **The totality test reaches the crate through a METHOD, not a path.**// `routes.list` answers `pushTypes` and `pushTypesUnmapped` since 4j's Rust// half, so this file compares the Swift table against what the linked build// actually says — which a by-path read could not do, and which is P14's// *"the same guard that a new server type lands with its entry and its test in// the same change"*. It is also why this lane adds no new by-path reader: a// guard through the boundary cannot go quiet when a tree is deleted.import CottonKitimport XCTestfinal class NotificationRoutesTests: XCTestCase {    /// The data object on its own — this table reads the bag, never the    /// delegate's envelope, which is what the two-tables cases below assert.    private func route(_ type: String, _ fields: [String: JSONValue] = [:]) -> Route? {        NotificationRoutes.route(for: Fixture.push(type, fields))    }    // ── The table itself ──────────────────────────────────────────────────    // Native/Swift membership is held by PushVocabularyTests; order is not a contract.    func testMappedTypesAreNonemptyAndUnique() {        XCTAssertFalse(NotificationRoutes.mappedTypes.isEmpty)        XCTAssertEqual(Set(NotificationRoutes.mappedTypes).count, NotificationRoutes.mappedTypes.count)    }    func testEveryRetiredTypeIsAbsent() {        // "A route for a push nobody sends is a promise nothing keeps". A build        // that quietly re-added one would otherwise look like a fix. Two are        // the Calls pushes, retired 2026-08-23 with the cell that sent them;        // seven went with the multi-person sharing data plane.        for retired in NotificationRoutes.retiredTypes {            XCTAssertFalse(                NotificationRoutes.mappedTypes.contains(retired),                "\(retired) came back without its sender"            )            XCTAssertNil(route(retired, ["callId": .string("c1")]))        }    }    func testAnUnmappedTypeRoutesNowhere() {        XCTAssertNil(route("cotton_something_new", ["id": .string("x1")]))        // `UNMAPPED_BY_THE_APP` is EMPTY now — the two live server types no        // client mapped were both share pushes, and they left with the        // multi-person sharing data plane. Every type the server can emit has a        // route here, and the crate's own guard is what says so.    }    func testAPayloadThatIsNotAnObjectOrCarriesNoTypeRoutesNowhere() {        XCTAssertNil(NotificationRoutes.route(for: .string("cotton_document_ready")))        XCTAssertNil(NotificationRoutes.route(for: .null))        XCTAssertNil(NotificationRoutes.route(for: .object(["threadId": .string("t1")])))        // A non-string `type` is not a type.        XCTAssertNil(NotificationRoutes.route(for: .object(["type": .number(7)])))    }    // ── Every row, with its fallback ──────────────────────────────────────    func testTheStatementNotificationRoutesToItsPaper() {        XCTAssertEqual(            route("cotton_money_statement_read", ["statementId": .string("s1")]),            .moneyStatement(id: "s1")        )        XCTAssertEqual(route("cotton_money_statement_read"), .money)    }    func testBothMeetingLanesLandOnTheMeetingAndFallBackToTheList() {        for type in ["cotton_meeting_ready", "cotton_meeting_failed"] {            XCTAssertEqual(                route(type, ["meetingId": .string("m1"), "errorCode": .string("boom")]),                .meetingsMeeting(id: "m1")            )            XCTAssertEqual(route(type), .meetings(importing: false))        }    }    func testADocumentAndAnAgentNoteShareARouteAndNotAFallback() {        XCTAssertEqual(            route("cotton_document_ready", ["documentId": .string("d1")]),            .documentsDocument(id: "d1")        )        XCTAssertEqual(route("cotton_document_ready"), .documents(status: nil))        XCTAssertEqual(            route("cotton_agent_note", ["documentId": .string("d1")]),            .documentsDocument(id: "d1")        )        // A note an assistant left with no document opens the documents list.        XCTAssertEqual(route("cotton_agent_note"), .documents(status: nil))    }    func testASessionQuestion() {        XCTAssertEqual(            route("cotton_session_question", ["sessionId": .string("s1")]),            .sessionsId(id: "s1")        )        // No session named: the ONE list, which is the Code screen — there is        // no sessions list to fall back to any more.        XCTAssertEqual(route("cotton_session_question"), .code)    }    func testBothNewsLanes() {        for type in ["cotton_news_edition_ready", "cotton_news_edition_failed"] {            XCTAssertEqual(                route(                    type,                    [                        "editionId": .string("e1"),                        "storyCount": .number(4),                        "errorCode": .string("boom"),                    ]                ),                .newsEdition(id: "e1")            )            XCTAssertEqual(route(type), .news)        }    }    func testAFeedbackCapture() {        // A report filed in the app is read on the reports list, so        // it always lands there — with or without a payload.        XCTAssertEqual(            route("cotton_feedback_capture", ["feedbackId": .string("f1")]),            .tableList(table: "project_feedback", filter: nil, title: nil, query: nil)        )        XCTAssertEqual(route("cotton_feedback_capture"), .tableList(table: "project_feedback", filter: nil, title: nil, query: nil))    }    func testAnAssistantResult() {        XCTAssertEqual(            route("cotton_assistant_result", ["noteId": .string("n1"), "runId": .string("r1")]),            .notesNote(id: "n1")        )        XCTAssertEqual(route("cotton_assistant_result"), .notes)    }    /// A device asking to join lands on THAT request, by its pairing id.    ///    /// The other fields the push carries — `name`, `platform`, `digits` — ride    /// unread: the screen asks `devices.pending` for the row, so it draws what    /// the server says NOW rather than what it said when the push was composed.    /// A request answered on another device in the meantime reads as settled    /// rather than as a live question.    func testAJoinRequestTapLandsOnThatRequest() {        XCTAssertEqual(            route(                "device_join_requested",                [                    "pairingId": .string("p-1"),                    "name": .string("Asha's iPhone"),                    "platform": .string("ios"),                    "digits": .string("482913"),                ]            ),            .settingsJoinRequest(id: "p-1")        )        // No id is a push this build cannot open a page for, and the Devices        // tool's waiting list is the same two verbs one tap further on.        XCTAssertEqual(route("device_join_requested"), .devices)        XCTAssertEqual(route("device_join_requested", ["pairingId": .string("")]), .devices)    }    /// RULE: A standby Mac's ring — the serving Mac gone quiet, or its own copy behind — opens Devices, where the Macs and who serves are, whatever its payload says.    func testAStandbysRingOpensDevices() {        XCTAssertEqual(route("cotton_standby_silent", ["standby": .string("silent")]), .devices)        XCTAssertEqual(route("cotton_standby_silent", ["standby": .string("cleared")]), .devices)        XCTAssertEqual(route("cotton_standby_behind", ["standby": .string("behind")]), .devices)        XCTAssertEqual(route("cotton_standby_behind"), .devices)    }    func testTheDeviceTypesIgnoreTheirPayloads() {        for type in ["device_approved", "device_revoked"] {            XCTAssertEqual(route(type, ["deviceId": .string("d1")]), .devices)            XCTAssertEqual(route(type), .devices)        }        XCTAssertEqual(route("recovery_key_shown", ["deviceId": .string("d1")]), .device)    }    // ── Table two ─────────────────────────────────────────────────────────    func testTheReminderParseIsSuspicious() {        XCTAssertEqual(            ReminderTaps.parse(.object(["kind": .string("todo"), "id": .string("t1")])),            ReminderPayload(kind: .todo, id: "t1")        )        // Everything that is not exactly `{kind: <one of five>, id: <non-empty>}`.        XCTAssertNil(ReminderTaps.parse(.object(["kind": .string("todo"), "id": .string("")])))        XCTAssertNil(ReminderTaps.parse(.object(["kind": .string("recipe"), "id": .string("t1")])))        XCTAssertNil(ReminderTaps.parse(.object(["kind": .string("todo")])))        XCTAssertNil(ReminderTaps.parse(.object(["id": .string("t1")])))        XCTAssertNil(ReminderTaps.parse(.object(["kind": .number(1), "id": .string("t1")])))        XCTAssertNil(ReminderTaps.parse(.string("todo")))        XCTAssertNil(ReminderTaps.parse(.null))    }    func testWhereEachReminderKindLands() {        XCTAssertEqual(ReminderTaps.route(for: ReminderPayload(kind: .todo, id: "t1")), .todosTodo(id: "t1"))        XCTAssertEqual(            ReminderTaps.route(for: ReminderPayload(kind: .event, id: "e1")),            .calendarEvent(id: "e1", date: nil, at: nil)        )        // A birthday is not a record of its own: the tap opens the PERSON, and        // the id the engine put in the payload is the person's.        XCTAssertEqual(            ReminderTaps.route(for: ReminderPayload(kind: .birthday, id: "p1")),            .peoplePerson(id: "p1")        )        XCTAssertEqual(ReminderTaps.route(for: ReminderPayload(kind: .alarm, id: "a1")), .alarms)        // Nothing asks about mood on a schedule (owner, 11 Oct 2026): a mood        // nudge an older build left on the queue is no kind this build reads,        // so its tap only opens the app.        XCTAssertNil(ReminderTaps.parse(.object(["kind": .string("mood"), "id": .string("2026-10-11")])))    }    func testTheRecordAndToolTablesNeverOverlap() {        // A kind answering both would make the landing depend on the order two        // lookups happen to be written in.        for kind in NotificationKind.allCases {            let record = ReminderTaps.recordKind(for: kind)            let tool = ReminderTaps.toolRoute(for: kind)            XCTAssertFalse(                record != nil && tool != nil,                "\(kind.rawValue) is in both tables"            )            XCTAssertTrue(                record != nil || tool != nil,                "\(kind.rawValue) is in neither, so its tap leads nowhere"            )        }    }    // ── The mutual rejection, which is what makes ONE delegate safe ───────    func testEachTableRejectsTheOthersPayload() {        let reminder = JSONValue.object(["kind": .string("todo"), "id": .string("t1")])        let push = Fixture.push("cotton_document_ready", ["documentId": .string("d1")])        XCTAssertNil(NotificationRoutes.route(for: reminder), "the push table claimed a reminder")        XCTAssertNil(ReminderTaps.route(for: push), "the reminder table claimed a push")    }}