Cotton code
250 lines · 13.7 KB · SwiftRaw
// Cotton Chat on iPhone (chat-new-ios): the core's answers read as the core// writes them (bundled under Fixtures/chat), the fan becomes the board's// cards, and the thread's model keeps a window of pages with every item// once, lands a send at once and merges only what arrived. The core's own// rules (runs, dividers, what a source can do) are the core's tests.#if os(iOS)import XCTest@testable import CottonUI@MainActorfinal class ChatBookTests: XCTestCase {    private func fixture<T: Decodable>(_ name: String, as type: T.Type) throws -> T {        let url = try XCTUnwrap(Bundle(for: Self.self).url(forResource: name, withExtension: "json", subdirectory: "Fixtures/chat"))        return try JSONDecoder().decode(type, from: Data(contentsOf: url))    }    // RULE (FEEDBACK-3, deleted means deleted): the newest page read again is laid anew wherever it no longer names    // something held (erased, deleted in WhatsApp, a pending text that now stands), the held stand in another order, or    // something new stands amid them (a deleted message's marker in its place); a page that only adds at its foot or    // changes a bubble in place merges as before.    func testTheNewestPageIsLaidAgainWhenSomethingLeftOrCameAmid() {        XCTAssertFalse(ChatThreadModel.laidAgain(held: ["a", "b"], tail: ["a", "b", "c"]), "new at the foot appends")        XCTAssertFalse(ChatThreadModel.laidAgain(held: ["a", "b"], tail: ["a", "b"]), "the same, merged in place")        XCTAssertTrue(ChatThreadModel.laidAgain(held: ["a", "b", "c"], tail: ["a", "c"]), "b erased leaves")        XCTAssertTrue(ChatThreadModel.laidAgain(held: ["a", "b", "c"], tail: ["a", "x", "c"]), "b deleted: its marker stands where it was")        XCTAssertTrue(ChatThreadModel.laidAgain(held: ["a", "outbox:1"], tail: ["a", "m1"]), "a pending text that now stands")        XCTAssertTrue(ChatThreadModel.laidAgain(held: ["a", "b"], tail: ["b", "a"]), "another order")    }    func testTheCoresThreadAnswerReadsAndWritesBack() throws {        let answer = try fixture("thread-answer", as: ChatThreadAnswer.self)        XCTAssertEqual(answer.items.count, 4)        guard case .bubble(let bubble) = answer.items[3] else { return XCTFail("the fourth item is a bubble") }        XCTAssertEqual(bubble.sender?.picture.photo, "p:asha")        XCTAssertEqual(bubble.reactions.first?.mine, true)        XCTAssertEqual(answer.composer?.sendEnabled, false)        XCTAssertEqual(answer.composer?.dictate, true)        XCTAssertNotNil(answer.request)        XCTAssertEqual(answer.older, "60")        XCTAssertNil(answer.newer)        let again = try JSONDecoder().decode(ChatThreadAnswer.self, from: JSONEncoder().encode(answer))        XCTAssertEqual(again, answer)    }    func testTheCoresFanBecomesTheBoardsCards() throws {        let list = try fixture("list-answer", as: ChatListAnswer.self)        let cards = ChatBooks.cards(list.fan)        XCTAssertEqual(cards.count, list.fan.count)        XCTAssertEqual(cards.first?.chat, list.fan.first?.id)        XCTAssertEqual(cards.last?.aside, true)        XCTAssertTrue(cards.dropLast().allSatisfy { $0.chat != nil && !$0.aside })        XCTAssertEqual(cards.map(\.label), list.fan.map(\.label))    }    func testDividersAreNamedByWhatFollowsThem() throws {        let answer = try fixture("thread-answer", as: ChatThreadAnswer.self)        let ids = ChatThreadModel.drawn(answer.items).map(\.id)        XCTAssertEqual(ids, ["day@e1", "unread@e1", "event:e1", "m1"])    }    func testTheWindowKeepsEveryItemOnceAcrossPages() async throws {        let book = try ChatFakeBook(template: fixture("thread-answer", as: ChatThreadAnswer.self))        let model = ChatThreadModel(book: book, thread: "t1")        await model.open()        for _ in 0..<12 { await model.loadOlder() }        let ids = model.items.map(\.id)        XCTAssertEqual(ids.count, Set(ids).count, "an item drawn twice")        XCTAssertEqual(model.pages.count, ChatThreadModel.window)        XCTAssertNotNil(model.newer, "a window that dropped its newest pages can page back down")        await model.loadNewer()        XCTAssertEqual(Set(model.items.map(\.id)).count, model.items.count)    }    func testASendLandsAtOnceAndAnArrivalOnlyAppends() async throws {        let book = try ChatFakeBook(template: fixture("thread-answer", as: ChatThreadAnswer.self))        let model = ChatThreadModel(book: book, thread: "t1")        await model.open()        let before = model.items.count        await model.send("x")        XCTAssertEqual(model.items.last?.id, book.lastSent)        XCTAssertEqual(model.items.count, before + 1)        book.arrive()        await model.apply(.arrived(thread: "t1"))        XCTAssertEqual(model.items.count, before + 2)        XCTAssertEqual(model.change, .appendedNewer)    }    func testReadingAShownThreadAsksTheCoreAndFlushesWhenItSays() async throws {        let book = try ChatFakeBook(template: fixture("thread-answer", as: ChatThreadAnswer.self))        let model = ChatThreadModel(book: book, thread: "t1")        await model.open()        let said = expectation(forNotification: .cottonChatRead, object: nil) { $0.userInfo?["thread"] as? String == "t1" }        await model.markRead()        await fulfillment(of: [said], timeout: 1)        XCTAssertEqual(book.acts.map(\.act), ["read"])        XCTAssertEqual(book.acts.first?.thread, "t1")        XCTAssertTrue(model.items.allSatisfy { $0.id.hasPrefix("m") }, "a read draws no bubble")        // The flush runs detached, off the main thread, as a send's does.        for _ in 0..<50 where book.flushes == 0 { try await Task.sleep(for: .milliseconds(10)) }        XCTAssertEqual(book.flushes, 1)    }    func testTheCoresCallShapesRead() throws {        struct Calls: Decodable {            let item: ChatThreadItem            let header: ChatHeader            let calls: ChatCallsAnswer            let screen: ChatCallScreen            let ringing: ChatCallScreen        }        let calls = try fixture("calls", as: Calls.self)        guard case .event(_, _, let call?, _, _) = calls.item else { return XCTFail("a call's line carries its call") }        XCTAssertTrue(call.missed && call.video && call.incoming)        XCTAssertEqual(calls.item.id, "event:call-r1")        let again = try JSONDecoder().decode(ChatThreadItem.self, from: JSONEncoder().encode(calls.item))        XCTAssertEqual(again, calls.item, "the call line writes back whole")        XCTAssertEqual(calls.header.calls?.map(\.video), [false, true])        XCTAssertEqual(calls.calls.rows.first?.missed, true)        XCTAssertNotNil(calls.calls.next)        XCTAssertEqual(calls.screen.controls.map(\.id), ["mute", "speaker", "video", "flip", "end"])        XCTAssertNil(calls.screen.status, "live: the clock is drawn from liveAt")        XCTAssertNotNil(calls.screen.bar)        XCTAssertNotNil(calls.ringing.ring)        XCTAssertTrue(calls.ringing.controls.isEmpty)    }    // RULE (owner, Comms build 19, 22 Nov 2026: a picture he had just sent said "Picture not available"): a picture    // on its way (the core's not_yet, or no answer) is never drawn as gone and is asked again after a short wait until    // its file comes; only the core's word (not_found, unreadable) is gone, and a gone one is not asked again in a storm.    func testAPictureOnItsWayIsNeverGoneAndComesWhenItLands() async throws {        let saved = ChatPictureTries.soon        ChatPictureTries.soon = [.milliseconds(20)]        defer { ChatPictureTries.soon = saved }        let book = try ChatFakeBook(template: fixture("thread-answer", as: ChatThreadAnswer.self))        let landed = URL(fileURLWithPath: "/tmp/landed.jpg")        book.found = [.notYet, .notYet, .file(landed)]        let tries = ChatPictureTries()        let first = await tries.find(message: "m1", index: 0, book: book)        XCTAssertEqual(first, .notYet)        XCTAssertFalse(tries.gone.contains(ChatPictureTries.key("m1", 0)), "on its way: never drawn as gone")        let url = await tries.file(message: "m1", index: 0, book: book)        XCTAssertEqual(url, landed, "asked again until it came")        XCTAssertEqual(book.pictureAsks, 3)        book.found = [.gone]        let gone = await tries.file(message: "m2", index: 0, book: book)        XCTAssertNil(gone)        XCTAssertTrue(tries.gone.contains(ChatPictureTries.key("m2", 0)), "the core's word: gone")        let asks = book.pictureAsks        for _ in 0..<5 { _ = await tries.file(message: "m2", index: 0, book: book) }        XCTAssertEqual(book.pictureAsks, asks, "a gone picture is not asked again while its wait runs")        XCTAssertEqual(ChatPictureFound.of(code: "not_yet"), .notYet)        XCTAssertEqual(ChatPictureFound.of(code: "not_connected"), .notYet)        XCTAssertEqual(ChatPictureFound.of(code: "not_found"), .gone)    }    func testTheCallClockCountsFromLive() {        let live = 1_000_000.0        XCTAssertEqual(ChatCallClock.text(liveAt: live * 1000, now: Date(timeIntervalSince1970: live + 192)), "3:12")        XCTAssertEqual(ChatCallClock.text(liveAt: live * 1000, now: Date(timeIntervalSince1970: live + 3723)), "1:02:03")        XCTAssertEqual(ChatCallClock.text(liveAt: live * 1000, now: Date(timeIntervalSince1970: live - 5)), "0:00")    }    // RULE (COMMS WITHOUT MAIL, 26 Nov 2026): the switch is Chats, Calls, You; Mail, Senders and Sites are other apps'.    func testTheSwitchIsChatsCallsAndYou() {        XCTAssertEqual(ChatPlace.allCases.map(\.rawValue), ["chats", "calls", "you"])        XCTAssertNil(ChatYouPage(rawValue: "sites"), "You has no Sites page")        XCTAssertEqual(ChatYouPage(rawValue: "blocked"), .blocked, "You's blocked row opens Blocked")    }    // RULE: a web link's answer (`chat.link`) names Sites' address on the iPhone, live and Dev.    func testALinkAnswerNamesSitesOnTheIPhone() throws {        let raw = #"{"url":"https://example.com/a","sites":{"ios":{"live":"cottonsites://open?url=x&from=comms","dev":"cottonsitesdev://open?url=x&from=comms"},"android":{"package":"com.cottondb.sites","dev_package":"com.cottondb.sites.dev","action":"android.intent.action.VIEW","extra":{"from":"comms"}}}}"#        let answer = try JSONDecoder().decode(ChatLinkAnswer.self, from: Data(raw.utf8))        XCTAssertEqual(answer.sites?.ios?.live, "cottonsites://open?url=x&from=comms")        XCTAssertEqual(answer.sites?.ios?.dev, "cottonsitesdev://open?url=x&from=comms")    }}/// A small book over numbered messages, answering in the core's shapes/// from a bundled answer's header, composer and words.final class ChatFakeBook: ChatBook, @unchecked Sendable {    private let template: ChatThreadAnswer    private var count = 100_000    private(set) var lastSent: String?    private let page = 60    init(template: ChatThreadAnswer) { self.template = template }    var photosByKey: Bool { true }    private func bubble(_ i: Int) -> ChatBubble {        ChatBubble(message: "m\(i)", mine: i % 3 == 0, kind: .text, text: nil, sender: nil, head: true, tail: true, time: "09:00",                   tick: nil, edited: nil, forwarded: nil, pinned: false, reply: nil, reactions: [], media: [], link: nil, actions: [])    }    func thread(_ ask: ChatThreadAsk) async throws -> ChatThreadAnswer {        var hi = count, lo = max(0, count - page)        if let before = ask.before.flatMap(Int.init) { hi = before; lo = max(0, before - page) }        if let after = ask.after.flatMap(Int.init) { lo = after; hi = min(count, after + page) }        var answer = template        answer.items = (lo..<hi).map { .bubble(bubble($0)) }        answer.older = lo > 0 ? String(lo) : nil        answer.newer = hi < count ? String(hi) : nil        answer.request = nil        return answer    }    /// Every act asked, in order.    private(set) var acts: [ChatActAsk] = []    private(set) var flushes = 0    func act(_ ask: ChatActAsk) async throws -> ChatActAnswer {        acts.append(ask)        if ask.act == "read" {            return ChatActAnswer(ok: true, act: "read", thread: ask.thread, message: nil, bubble: nil, row: nil, sentTo: nil, flush: true, said: nil)        }        let b = bubble(count)        count += 1        lastSent = b.message        return ChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: b.message, bubble: b, row: nil, sentTo: nil, flush: false, said: nil)    }    func arrive() { count += 1 }    func list(_ ask: ChatListAsk) async throws -> ChatListAnswer { throw CancellationError() }    func compose(_ ask: ChatComposeAsk) async throws -> ChatComposeAnswer { try XCTUnwrap(template.composer) }    func decide(_ thread: String, _ method: String) async throws {}    func themes() async throws -> ChatThemesAnswer { throw CancellationError() }    func choose(theme: String, dark: Bool) async throws -> ChatThemesAnswer { throw CancellationError() }    func setText(_ id: String) async throws -> ChatThemesAnswer { throw CancellationError() }    func setGround(_ ground: String) async throws -> ChatThemesAnswer { throw CancellationError() }    func calls(after: String?) async throws -> ChatCallsAnswer { throw CancellationError() }    func flush() async { flushes += 1 }    func picture(media: String?, message: String?, index: Int?) async -> URL? { nil }    /// What each ask for a picture finds, in turn (the last one again once they run out), and how many were asked.    var found: [ChatPictureFound] = []    private(set) var pictureAsks = 0    func findPicture(message: String, index: Int) async -> ChatPictureFound {        pictureAsks += 1        return found.isEmpty ? .notYet : (found.count > 1 ? found.removeFirst() : found[0])    }    func file(message: String, index: Int) async throws -> ChatFileAnswer {        throw CancellationError()    }    func changes() -> AsyncStream<ChatChange> { AsyncStream { $0.finish() } }}#endif