importCottonKitimportCottonValuesimport XCTest@testable importCottonUI/// Cotton Post on iPhone (launch-ios, mail CONTRACT row 17): each `mail.*` answer reads as the core shapes it/// (crates/cotton-ffi/src/phone/chat_mail_post*.rs), Archive is one tap with its scope, a refusal comes back in the/// core's words for the screen to say in place, the side page narrows Mail by the account's address, and Look's preview/// reads Post's inbox rows without breaking Days'. Invented mail only.#if os(iOS)@MainActorfinalclassPostAppTests: XCTestCase {privatefunc decode<T: Decodable>(_ json: String, as type: T.Type) throws -> T {try JSONDecoder().decode(type, from: Data(json.utf8)) }/// RULE: The home reads its three bands, the status line and the history, people round and machines square.func testTheHomeReadsAsTheCoreAnswersIt() throws {let home = try decode(#""" {"title":"Inbox","search":{"hint":"Search 164 mails"}, "people":{"title":"People","line":"2 new","more":{"place":"inbox","label":"People"},"rows":[ {"thread":"t1","email":"e1","from":{"name":"Priya Invented","address":"priya@people.invented.test","face":"person","initials":"PI","tint":3}, "subject":"Flat papers","line":"Here's the lease draft.","when":"7:28 pm","unread":true,"count":1,"attachments":2,"account":null,"a11y":["Unread","From a person"]}]}, "waiting":{"title":"Waiting on you","rows":[ {"thread":"t1","email":"e1","from":{"name":"Priya Invented","address":"priya@people.invented.test","face":"person","initials":"PI","tint":3}, "subject":"Flat papers","line":"Asked 7:28 pm","when":"7:28 pm","unread":true,"count":1,"act":"Reply"}]}, "machines":{"title":"From machines","line":"22 today","groups":[{"id":"group:receipts","title":"Receipts and banks","line":"Shop 1, Shop 2","count":4,"inbox":12}]}, "status":{"line":"Fetched by your Mac","state":"live"},"history":null,"write":"Write a mail","empty":null} """#, as: PostHome.self) XCTAssertEqual(home.people.rows.first?.from.isPerson, true) XCTAssertEqual(home.people.rows.first?.attachments, 2) XCTAssertEqual(home.waiting?.rows.first?.act, "Reply") XCTAssertEqual(home.machines?.groups.first?.id, "group:receipts") XCTAssertEqual(home.status?.line, "Fetched by your Mac") XCTAssertNil(home.empty) }/// RULE: A group reads its why, its two counted buttons and its after cursor; a draft row reads with its mark and no thread.func testAGroupAndADraftReadAsTheCoreAnswersThem() throws {let group = try decode(#""" {"title":"Shops and offers","line":"3 today, 214 in your Inbox in all","rows":[], "why":{"line":"Here because Gmail marked it Promotions.","rules":"See the rules"}, "bulk":[{"act":"read","label":"Mark 17 read","count":17},{"act":"archive","label":"Archive 214","count":214}], "after":"2026-11-25T10:00:00Z\u001ft9","empty":"Nothing waiting. Your Inbox is empty.","bin":null} """#, as: PostList.self) XCTAssertEqual(group.bulk?.last?.label, "Archive 214") XCTAssertEqual(group.why?.rules, "See the rules")let drafts = try decode(#""" {"title":"Drafts","rows":[{"draft":"d1","thread":"","from":{"name":"Sara Invented","address":"sara@people.invented.test","picture":{"initials":"SI","tint":2}}, "who":"person","subject":"November invoice","line":null,"when":"Mon","unread":false,"count":1,"mark":"Draft","note":null}],"empty":null} """#, as: PostList.self) XCTAssertEqual(drafts.rows.first?.draft, "d1") XCTAssertNil(drafts.rows.first?.thread) XCTAssertEqual(drafts.rows.first?.from.shownInitials, "SI") }/// RULE: A thread reads its messages, links where they stand, attachments that say whether they are on the phone, and Reply all only when offered.func testAThreadReadsAsTheCoreAnswersIt() throws {let thread = try decode(#""" {"thread":"t1","subject":"Flat papers","with":{"name":"Priya Invented","address":"priya@people.invented.test","picture":{"initials":"PI"}},"who":"person", "messages":[{"email":"e1","mine":false,"from":{"name":"Priya Invented","address":"priya@people.invented.test","sender":"priya@people.invented.test"}, "to":"To you","cc":null,"when":"Today, 7:28 pm","subject":"Flat papers","text":"See https://plans.invented.test/4b now","links":[{"at":[4,34],"url":"https://plans.invented.test/4b"}], "unread":false,"attachments":[{"index":0,"name":"lease-draft.pdf","mime":"application/pdf","size":"2 KB","can":true,"kept":true,"line":"On this phone"}]}], "acts":{"reply":{"mode":"reply","label":"Reply"},"reply_all":null,"forward":{"mode":"forward","label":"Forward"}}, "page":{"label":"Show the designed page","pictures":{"line":"Pictures are off.","load":"Load pictures","always":"Always for Priya Invented"}},"quoted":"Show the quoted text"} """#, as: PostThread.self) XCTAssertEqual(thread.messages.first?.links?.first?.at, [4, 34]) XCTAssertEqual(thread.messages.first?.attachments.first?.line, "On this phone") XCTAssertNil(thread.acts.reply_all) XCTAssertEqual(thread.page?.pictures.load, "Load pictures") }/// RULE: An empty search answers bare lists and reads as nothing found yet; a search with words reads its titled bands.func testSearchReadsBothItsShapes() throws {let bare = try decode(#"{"hint":"Search mail, people, files","people":[],"mail":[],"files":[]}"#, as: PostSearch.self) XCTAssertEqual(bare.hint, "Search mail, people, files") XCTAssertNil(bare.mail)let found = try decode(#""" {"people":{"title":"People","rows":[]},"mail":{"title":"Mail","rows":[]}, "files":{"title":"Files","rows":[{"email":"e1","index":0,"name":"lease-draft.pdf","kind":"documents","size":"2 KB","from":"Priya Invented","when":"Mon","line":"From Priya Invented · Mon","can":true}]}, "empty":null} """#, as: PostSearch.self) XCTAssertEqual(found.files?.rows.first?.kind, "documents") }/// RULE: Archive is one tap: `mail.archive` carries its scope and key, and its after-state comes back with Undo and the mailbox's line.func testArchiveIsOneTapWithItsScope() asyncthrows {let core = ScriptedCore(["mail.archive": .ok(#"{"after":"a1","act":"archive","count":214,"line":"Archived214 from Tiffinly.","mailbox":{"state":"waiting","line":"Gmail will follow in a moment."},"undo":"Undo"}"#), ])let model = PostModel(core: core)let before = model.generationlet done = await model.archive(scope: "group", key: "shops") XCTAssertEqual(done.answer?.count, 214) XCTAssertEqual(done.answer?.undo, "Undo") XCTAssertEqual(done.answer?.mailbox?.state, "waiting") XCTAssertEqual(model.generation, before + 1)let calls = await core.calls XCTAssertEqual(calls.count, 1) XCTAssertEqual(calls[0].method, "mail.archive") XCTAssertTrue(calls[0].requestJSON.contains(#""scope":"group""#)) XCTAssertTrue(calls[0].requestJSON.contains(#""key":"shops""#)) }/// RULE: A refusal comes back in the core's words, and nothing reads again.func testARefusalIsSaidInTheCoresWords() async {let core = ScriptedCore(["mail.senders": .refuse(code: "unknown_method", message: "Senders isn't answered yet.")])let model = PostModel(core: core)let before = model.generationlet read = await model.read("mail.senders", ["sort": "never_read"], as: PostSenders.self) XCTAssertEqual(read.refusal, "Senders isn't answered yet.") XCTAssertEqual(model.generation, before) }/// RULE: The side page narrows Mail by the account's address (as the mail names it), and All inboxes widens it again.func testTheSidePageNarrowsMailByTheAccountsAddress() {let model = PostModel(core: ScriptedCore([:])) model.paths[.mail] = [.thread("t1")] model.chooseSide(inbox: "acct-2", title: "Hello@Studio.invented.test") XCTAssertEqual(model.account, "hello@studio.invented.test") XCTAssertEqual(model.accountRequest["account"], .string("hello@studio.invented.test")) XCTAssertEqual(model.paths[.mail], []) XCTAssertFalse(model.sideOpen) model.chooseSide(inbox: "all", title: "All inboxes") XCTAssertNil(model.account) model.chooseSide(place: "bin") XCTAssertEqual(model.paths[.mail], [.list("bin")]) }/// RULE: Look's preview reads Post's inbox rows and open mail, and Days' rows and Secrets' shown value still read as before.func testLookPreviewReadsPostWithoutBreakingTheOthers() throws {let post = try decode(#""" {"rows":[{"from":"Priya Nair","subject":"Flat papers","line":"The lease draft is attached…","when":"10:02","unread":true,"face":"person"}], "shown":{"from":"Sara Lindqvist","subject":"Kickoff on 2 Dec","text":"Works for us."}} """#, as: LookAnswer.Preview.self) XCTAssertEqual(post.mail?.first?.face, "person") XCTAssertEqual(post.letter?.subject, "Kickoff on 2 Dec") XCTAssertNil(post.rows) XCTAssertNil(post.shown)let days = try decode(#"{"day":"Today","rows":[{"time":"9:00","title":"Standup","task":false}]}"#, as: LookAnswer.Preview.self) XCTAssertEqual(days.rows?.first?.title, "Standup") XCTAssertNil(days.mail)let secrets = try decode(#"{"secrets":[],"shown":{"label":"Password","value":"•••","copy":"Copy"}}"#, as: LookAnswer.Preview.self) XCTAssertEqual(secrets.shown?.copy, "Copy") XCTAssertNil(secrets.letter)// And back again: what is kept on the phone for the next launch reads the same.let again = try decode(String(decoding: try JSONEncoder().encode(post), as: UTF8.self), as: LookAnswer.Preview.self) XCTAssertEqual(again, post) }/// RULE: You reads its groups, each row's answer, and a row whose choices are made in place; Notifications sends `mail.set` and You reads again.func testYouReadsItsRowsAndSetsAChoiceInPlace() asyncthrows {let you = #""" {"title":"You","card":{"line":"me@invented.test","count":"164 mails"},"groups":[ {"id":"post","title":"Post","rows":[ {"id":"accounts","title":"Accounts","value":"me@invented.test","open":{"page":"accounts"}}, {"id":"notifications","title":"Notifications","value":"People only","open":{"name":"notifications","choices":[ {"value":"people","label":"People only","on":true},{"value":"everyone","label":"Everyone","on":false}]}}, {"id":"undo_send","title":"Undo send","value":"10 seconds","open":{"name":"undo_send","choices":[{"value":0,"label":"Off","on":false},{"value":10,"label":"10 seconds","on":true}]}}, {"id":"look","title":"Look","value":null,"open":{"page":"look"}}]}, {"id":"privacy","title":"Privacy","rows":[{"id":"privacy","title":"Privacy","value":"Sealed on your phone","open":{"page":"privacy"}}]}]} """#let read = try decode(you, as: PostYou.self) XCTAssertEqual(read.card?.count, "164 mails") XCTAssertEqual(read.groups.first?.rows[1].open?.choices?.first?.value, .string("people")) XCTAssertEqual(read.groups.first?.rows[2].open?.choices?.last?.value, .number(10)) XCTAssertEqual(read.groups.last?.rows.first?.open?.page, "privacy")let core = ScriptedCore(["mail.set": .ok(you)])let model = PostModel(core: core)let again = await model.read("mail.set", ["name": .string("notifications"), "value": .string("everyone")], as: PostYou.self) XCTAssertNotNil(again.answer)let calls = await core.calls XCTAssertTrue(calls[0].requestJSON.contains(#""name":"notifications""#)) }/// RULE: A row's acts take the whole conversation: Archive is `mail.archive {scope: thread}`, the rest `mail.act {thread}`.func testARowsActsTakeTheWholeConversation() asyncthrows {let after = #"{"after":"a2","act":"archive","count":3,"line":"Archived3.","mailbox":null,"undo":"Undo"}"#let core = ScriptedCore(["mail.archive": .ok(after), "mail.act": .ok(after)])let model = PostModel(core: core) _ = await model.archive(scope: "thread", key: "t1") _ = await model.act("delete", thread: "t1")let calls = await core.calls XCTAssertTrue(calls[0].requestJSON.contains(#""scope":"thread""#) && calls[0].requestJSON.contains(#""key":"t1""#)) XCTAssertEqual(calls[1].method, "mail.act") XCTAssertTrue(calls[1].requestJSON.contains(#""thread":"t1""#)) }/// RULE: A mail's quoted tail reads folded under its label, and pictures say whether they load for the sender.func testAThreadReadsItsQuotedTailAndPictures() throws {let thread = try decode(#""" {"thread":"t1","subject":"Re: Flat papers","with":{"name":"Priya Invented"},"who":"person", "messages":[{"email":"e2","mine":false,"from":{"name":"Priya Invented","address":"priya@people.invented.test"},"when":"Today","text":"Signed.", "attachments":[],"quoted":{"label":"Show the quoted text","text":"On Mon, you wrote:\n> Here it is","links":[]}}], "acts":{"reply":{"mode":"reply","label":"Reply"},"reply_all":null,"forward":{"mode":"forward","label":"Forward"}}, "page":{"label":"Show the designed page","pictures":{"line":"Pictures are off.","load":"Load pictures","always":"Always for Priya","on":true,"sender":"priya@people.invented.test"}}} """#, as: PostThread.self) XCTAssertEqual(thread.messages.first?.quoted?.label, "Show the quoted text") XCTAssertEqual(thread.page?.pictures.on, true) XCTAssertEqual(thread.page?.pictures.sender, "priya@people.invented.test") }/// RULE: `mail.do` answers the after-state, or (Delete, when more came since) the one question again; the ask sheet reads `go` and `also`.func testAskAndDoReadBothAnswers() throws {let plan = try decode(#"{"title":"Unsubscribe from Tiffinly?","line":"They will be asked to stop.","go":"Unsubscribe","also":{"label":"Also archive 12","count":12,"on":true},"cancel":"Not now","plan":"{}"}"#, as: PostPlan.self) XCTAssertEqual(plan.also?.count, 12)let more = try decode(#"{"more":{"line":"2 more came.","choices":[{"id":"all","label":"Delete14"},{"id":"only","label":"Delete12"},{"id":"not_now","label":"Not now"}]},"plan":"{}"}"#, as: PostDone.self) XCTAssertEqual(more.more?.choices.count, 3) XCTAssertNil(more.done)let done = try decode(#"{"after":"a3","act":"delete","count":12,"line":"Deleted12.","undo":"Undo"}"#, as: PostDone.self) XCTAssertEqual(done.done?.count, 12) }/// RULE: Senders read as the core answers them: `blocked` a label, a sender's `said` a list, its addresses titled, each act with its own call.func testSendersReadTheirCallsAndBlockedLabel() throws {let list = try decode(#""" {"title":"Senders","line":"Loudest first","sorts":[{"id":"never_read","label":"Never read","on":true}], "rows":[{"key":"@kitebox.example","title":"Kitebox","line":"Opened 4% · Never replied","count":1200,"count_label":"1,200","person":false,"addresses":2,"blocked":false}], "after":"50","foot":"81 senders, 12 people","blocked":{"label":"3 blocked"},"empty":null} """#, as: PostSenders.self) XCTAssertEqual(list.rows.first?.count_label, "1,200") XCTAssertEqual(list.blocked?.label, "3 blocked") XCTAssertEqual(list.after, "50")let page = try decode(#""" {"key":"@kitebox.example","title":"Kitebox","person":false,"line":"Since Mar 2024", "numbers":[{"value":"1,200","label":"in all"},{"value":"40","label":"in your Inbox"},{"value":"4%","label":"opened (48)"}], "said":["You never replied.","Offers one-tap unsubscribe."], "addresses":{"title":"Addresses","hint":"Tap an address for its own page.","rows":[{"key":"news@kitebox.example","address":"news@kitebox.example","line":"Kitebox News","count":900}]}, "acts":[{"act":"archive","label":"Archive 40","line":"Out of your Inbox","count":40,"call":{"method":"mail.archive","scope":"domain","key":"@kitebox.example"}}, {"act":"block","label":"Block","line":"To the Bin","count":0,"call":{"method":"mail.ask","act":"block","scope":"domain","key":"@kitebox.example"}}], "merge":{"label":"Join with another sender"},"rename":{"label":"Rename"},"part":null,"blocked":false} """#, as: PostSender.self) XCTAssertEqual(page.said?.count, 2) XCTAssertEqual(page.addresses?.rows.first?.count, 900) XCTAssertEqual(page.acts?.first?.call?.method, "mail.archive") XCTAssertEqual(page.acts?.last?.call?.act, "block") XCTAssertNil(page.part)let blocked = try decode(#"{"title":"Blocked","rows":[{"key":"spam@x.example","title":"spam@x.example","unblock":"Unblock"}]}"#, as: PostBlocked.self) XCTAssertEqual(blocked.rows.first?.unblock, "Unblock") }/// RULE: A new mail reads with no draft id until its first save; `quoted` is text whose first line is the fold's label; a forward's files carry their mail.func testTheWriterReadsANewMailAndAForward() throws {let new = try decode(#""" {"mode":"new","to":[],"cc":[],"bcc":[],"attachments":[],"subject":"","body":"","title":"New mail", "from":{"address":"ada@invented.test","choices":[{"address":"ada@invented.test","label":"ada@invented.test · Home"}],"why":null}, "signature":null,"undo_seconds":5,"words":{"from":"From","to":"To","send":"Send","cancel":"Cancel","discard":"Discard draft"}} """#, as: PostDraft.self) XCTAssertNil(new.draft) XCTAssertEqual(new.word("send"), "Send") XCTAssertEqual(new.from.choices?.first?.label, "ada@invented.test · Home")let forward = try decode(#""" {"mode":"forward","to":[],"cc":[],"bcc":[],"subject":"Fwd: Flat papers","body":"", "attachments":[{"index":0,"name":"lease.pdf","mime":"application/pdf","size":"88 KB","carry":{"email":"e1","index":0}}], "quoted":"Forwarded mail\nFrom: Priya <priya@people.invented.test>","thread":null,"reply_to":null, "title":"Forward","from":{"address":"ada@invented.test","choices":[]}} """#, as: PostDraft.self) XCTAssertEqual(forward.attachments?.first?.carry?.email, "e1") XCTAssertEqual(forward.quoteLabel, "Forwarded mail") XCTAssertEqual(forward.quoteText, "From: Priya <priya@people.invented.test>") XCTAssertEqual(try decode(#"{"draft":"d1","said":"Draft saved"}"#, as: PostSaved.self).draft, "d1") XCTAssertEqual(try decode(#"{"draft":"d1","attachments":[{"index":0,"name":"a.pdf","mime":null,"size":"1 KB"}]}"#, as: PostAttachedFiles.self).attachments.count, 1)let held = try decode(#"{"draft":"d1","state":"holding","line":"Sendingin5 seconds","undo":"Undo","until":"2026-11-26T10:00:05Z"}"#, as: PostSending.self) XCTAssertEqual(held.undo, "Undo") }/// RULE: Accounts, a plan with its ways' honest words, an account's page with its log, Remove's question, and a domain's page and remove ask read as the core answers them.func testAccountsAndDomainsReadAsTheCoreAnswersThem() throws {let plan = try decode(#""" {"kind":"gmail","provider":"Gmail","title":"How mail arrives","line":"Pick who fetches.", "fields":[{"id":"address","label":"Address"},{"id":"password","label":"App password","hint":"16 letters from Gmail","secret":true}], "how":"How to make one","steps":["Open your Google Account."],"note":"Work accounts no longer allow app passwords.", "ways":[{"id":"phone","title":"This phone fetches","line":"Only while Post is open.","more":"iPhone gives a little time.","chosen":true}, {"id":"cotton","title":"Cotton fetches","line":"Always.","could":"Could read Gmail.","kept":"Locked.","logged":"Each round written down.","chosen":false}], "chosen":"phone"} """#, as: PostAccountPlan.self) XCTAssertEqual(plan.fields.last?.secret, true) XCTAssertEqual(plan.ways.last?.logged, "Each round written down.")let account = try decode(#""" {"id":"a1","address":"ada@invented.test","kind":"gmail","provider":"Gmail","title":"How mail arrives","way":"cotton", "ways":[{"id":"cotton","title":"Cotton fetches","line":"Always.","chosen":true}], "status":{"line":"Didn't fetch · wrong password","state":"failed"}, "password":{"kept":"Locked.","logged":"Written down.","forget":"Remove password"}, "log":{"title":"What was written down","rows":[{"at":"2026-11-26T09:00:00Z","when":"9:00 am","line":"Didn't fetch · auth","failed":true,"why":"Gmail refused the password"}]}, "name":{"label":"Your name on mail","value":null},"signature":{"label":"Signature","value":"Ada"},"tag":{"label":"Tag","value":"Home"}, "remove":{"label":"Remove this account","line":"The 40 mails here stay.","count":40}} """#, as: PostAccount.self) XCTAssertEqual(account.log?.rows.first?.failed, true) XCTAssertEqual(account.remove?.count, 40)let ask = try decode(#"{"ask":{"title":"Remove this account","line":"The40 mails here stay.","go":"Remove this account","cancel":"Not now","count":40}}"#, as: PostRemoved.self) XCTAssertEqual(ask.ask?.count, 40)let domain = try decode(#""" {"domain":"invented.test","line":"1 record still to check", "records":[{"id":"proof","name":"It's yours","line":"_cotton.invented.test abc","state":"next","fix":{"type":"TXT","name":"_cotton.invented.test","value":"abc"}}, {"id":"mx","name":"Mail in","line":"MX found","state":"done"}], "keep_checking":"Leave this, it'll keep checking","addresses":{"title":"1 address","rows":[{"address":"ada@invented.test","line":null,"lands":null,"default":true}]}, "new_address":"New address","plus":null,"catch_all":{"label":"Anything else at invented.test","on":false,"line":"Bounces back as not found"}, "people_later":{"label":"People · later","line":"Later."},"server_reads":{"label":"What the server reads","line":"All of it."}} """#, as: PostDomain.self) XCTAssertEqual(domain.records.first?.fix?.type, "TXT") XCTAssertFalse(domain.catch_all.on)let removing = try decode(#"{"ask":{"title":"Remove x@invented.test?","line":"Bounces after.","go":"Remove address","cancel":"Not now"}}"#, as: PostAddressRemoved.self) XCTAssertNotNil(removing.ask) XCTAssertNil(removing.page)// A domain offers Remove, which asks once; agreed, the list answers and carries no question. XCTAssertNil(domain.remove)let removable = try decode(#""" {"domain":"invented.test","records":[],"addresses":{"title":"0 addresses","rows":[]},"new_address":"New address", "catch_all":{"label":"Anything else","on":false},"remove":{"label":"Remove domain","call":{"method":"mail.domain.remove","domain":"invented.test"}}} """#, as: PostDomain.self) XCTAssertEqual(removable.remove?.label, "Remove domain")let asked = try decode(#"{"ask":{"title":"Remove invented.test?","line":"Its2 addresses bounce after.","go":"Remove domain","cancel":"Not now","danger":true}}"#, as: PostDomainRemoved.self) XCTAssertEqual(asked.ask?.go, "Remove domain")let gone = try decode(#"{"title":"Domains","rows":[],"add":"Add a domain","line":"invented.test removed"}"#, as: PostDomainRemoved.self) XCTAssertNil(gone.ask) }/// RULE: Post's tabs and counted words read from the `post` set.func testPostWordsReadFromTheirSet() { XCTAssertEqual(PostWords.line("tab.mail"), ShellLines.line("post", "tab.mail")) XCTAssertFalse(PostWords.line("tab.senders").hasPrefix("tab.")) XCTAssertEqual(PostWords.count("home.search", 1), ShellLines.line("post", "home.search.one", ["n": "1"])) XCTAssertFalse(PostWords.count("home.search", 164).hasPrefix("home.")) }}#endif