Cotton code
486 lines · 27.0 KB · SwiftRaw
import CottonKitimport Foundationimport XCTest@testable import CottonUI// The Mac stub build (swift-guards) has no iOS-only types this reads.#if os(iOS)/// Days on the core (CONTRACT.md): the core's answers read as the contract/// shapes them, and each act sent as the contract asks it, with the phone's/// zone and today on every call (section 0).final class DaysLogicTests: XCTestCase {    private func json(_ s: String) -> Any { try! JSONSerialization.jsonObject(with: Data(s.utf8)) }    private let friday = "2026-11-20"    private func day(_ answer: DaysSpanAnswer, _ at: Int = 0) -> DaysDay {        guard case .day(let d) = answer.days[at] else { XCTFail("not a day"); return DaysDay(day: "", number: "", weekday: "", month: "", today: false, rows: []) }        return d    }    private func book(_ core: any CottonCalling) -> CoreDaysBook {        CoreDaysBook(core: core, clock: .fixed("2026-11-20", zone: TimeZone(identifier: "Europe/London")!))    }    func testASpanIsReadAsTheContractShapesIt() {        let span = DaysRead.span(json("""        {"today":"2026-11-20","days":[          {"day":"2026-11-20","number":"20","weekday":"Friday","month":"November","today":true,"rows":[            {"key":"event:a@x","kind":"event","time":"11:30","end":"12:00","mark":{"kind":"dot"},"words":"Call with the bank","suffix":"to 12:00","done":false,"whose":"google","opens":{"sheet":"event","id":"a","occurrenceAt":"2026-11-20T11:30"}},            {"key":"todo:b","kind":"todo","time":null,"end":null,"mark":{"kind":"tick","done":false},"drawnMark":"star","words":"Send the invoice","suffix":"from Tue","done":false,"whose":"yours","opens":{"sheet":"todo","id":"b"}},            {"key":"birthday:p@x","kind":"birthday","time":null,"end":null,"mark":{"kind":"drawn","id":"cake"},"words":"Akash's birthday","suffix":null,"done":false,"whose":"birthday","opens":{"person":"p"}}]},          {"fold":{"from":"2026-11-22","to":"2026-11-25","count":4,"words":"22 – 25 · four quiet days"}}]}        """) as! [String: Any])        let today = day(span)        XCTAssertTrue(today.today)        let call = today.rows[0], invoice = today.rows[1], birthday = today.rows[2]        XCTAssertEqual(call.mark, .dot)        XCTAssertEqual(call.suffix, "to 12:00")        XCTAssertEqual(call.whose, .google)        XCTAssertFalse(call.movable, "a Google event's day is Google's")        XCTAssertEqual(invoice.mark, .tick(done: false))        XCTAssertEqual(invoice.drawnMark, "star")        XCTAssertTrue(invoice.movable)        XCTAssertEqual(invoice.table, "todo")        XCTAssertEqual(birthday.mark, .drawn("cake"))        XCTAssertEqual(birthday.opens, .person("p"))        XCTAssertNil(birthday.recordId)        guard case .fold(let fold) = span.days[1] else { return XCTFail("not a fold") }        XCTAssertEqual(fold.count, 4)        XCTAssertEqual(fold.words, "22 – 25 · four quiet days")        XCTAssertTrue(span.days[1].holds("2026-11-24"))    }    func testSometimeReadsAListOrGroups() {        let list = DaysRead.groups(json("""        [{"id":"h","name":"Home","count":1,"rows":[]},{"id":null,"name":"No group","count":41,"rows":[]}]        """))        XCTAssertEqual(list.map(\.id), ["h", "no-group"])        XCTAssertEqual(list[1].count, 41)        XCTAssertEqual(DaysRead.groups(json("""        {"groups":[{"id":"h","name":"Home","count":1,"rows":[]},{"id":null,"name":"No group","count":41,"rows":[]}]}        """)), list)    }    func testTheChosenGroupGoesWithEveryReadAndAdd() async throws {        let core = FakeDaysCore([            "days.span": #"{"today":"2026-11-20","days":[]}"#,            "days.sometime": #"[]"#,            "days.month": #"{"month":"2026-11","title":"November 2026","weekStart":7,"lead":0,"weeks":6,"days":[]}"#,            "days.add": #"{"table":"todo","id":"t","day":"2026-11-20","time":null}"#,        ])        let b = book(core)        _ = try await b.span(from: friday, to: friday, group: "g1")        _ = try await b.sometime(group: "g1")        let month = try await b.month("2026-11", weekStart: 7, group: "g1")        _ = try await b.add("Fix the shelf", where: "days", dayInView: friday, day: nil, time: nil, mark: nil, group: "g1")        let sent = await core.sent        XCTAssertEqual(sent.map { $0.body["group"] as? String }, ["g1", "g1", "g1", "g1"])        XCTAssertEqual(sent[2].body["weekStart"] as? Int, 7)        XCTAssertEqual(month.lead, 0)        XCTAssertEqual(month.weeks, 6)        // With no group chosen, none is sent.        _ = try await b.sometime(group: nil)        let last = await core.sent.last        XCTAssertNil(last?.body["group"])    }    func testTheFiltersGroupsAreReadWithTheirCounts() {        let groups = DaysRead.groupCounts(json("""        {"all":"All","count":41,"groups":[{"id":"g1","name":"Home","count":23},{"id":"g2","name":"Work","count":3}]}        """) as! [String: Any])        XCTAssertEqual(groups.all, "All")        XCTAssertEqual(groups.count, 41)        XCTAssertEqual(groups.groups.map(\.name), ["Home", "Work"])        XCTAssertEqual(groups.groups[0].count, 23)    }    @MainActor    func testMarksAreOfferedOnlyDrawnMatchesFirst() {        let drawn: @MainActor (String) -> Bool = { $0 != "ghost" }        XCTAssertEqual(DaysMarksRow.offered(["cake", "plane", "ghost", "tooth"], matches: ["tooth", "ghost"], chosen: nil, drawn: drawn),                       ["tooth", "cake", "plane"])        XCTAssertEqual(DaysMarksRow.offered(["cake"], matches: [], chosen: "plane", drawn: drawn), ["cake", "plane"])    }    func testAMarksStrokesAreRead() {        let marks = DaysRead.catalogue(json("""        [{"id":"cake","words":{"en":["cake"]},"strokes":["M4 20 C8 19 16 21 20 20","M6 20 L6 13"]},{"id":"plane","words":{}}]        """))        XCTAssertEqual(marks[0].strokes.count, 2)        XCTAssertEqual(marks[1].strokes, [])    }    func testAStrokeIsDrawnFromItsPath() {        let path = PenStroke.path("M4 20 C8 19 16 21 20 20 l-2 -3 Q12 4 6 8 z")        XCTAssertFalse(path.isEmpty)        let box = path.boundingRect        XCTAssertEqual(box.minX, 4, accuracy: 0.6)        XCTAssertEqual(box.maxX, 20, accuracy: 0.6)        XCTAssertTrue(PenStroke.path("").isEmpty)        XCTAssertTrue(PenStroke.path("garbage").isEmpty)    }    func testAChangeSendsOnlyWhatChangedAndNullForACleared() {        var change = DaysChange()        XCTAssertTrue(change.isEmpty)        change.mark = .some(nil)        change.title = .some("Dinner")        let sent = change.json        XCTAssertEqual(sent.keys.sorted(), ["mark", "title"])        XCTAssertTrue(sent["mark"] is NSNull)        XCTAssertEqual(sent["title"] as? String, "Dinner")    }    /// "No alert" did nothing (Android launch walk of Days, 22 Nov 2026): an event with no alert stored showed No alert    /// chosen though it reminds ten minutes before, and No alert was sent as null, the same default. The sheet now reads    /// the choices the core answers with the one that stands, and No alert is sent as "none".    func testAnEventsSheetMarksTheAlertThatStandsAndSendsNoAlertAsNone() async throws {        let core = FakeDaysCore([            "days.item": #"{"table":"event","id":"e","whose":"yours","says":"Yours","words":"Invented dentist","day":"2026-11-24","time":"10:00","end":null,"mark":null,"note":null,"alert":10,"alerts":[{"alert":"none","on":false},{"alert":0,"on":false},{"alert":10,"on":true},{"alert":30,"on":false},{"alert":60,"on":false}],"done":false,"repeats":false,"canChange":{"title":true,"time":true,"mark":true,"note":true,"alert":true}}"#,        ])        let item = try await book(core).item(table: "event", id: "e", occurrenceAt: nil)        XCTAssertEqual(item.alerts.map(\.alert), [.off, .minutes(0), .minutes(10), .minutes(30), .minutes(60)])        XCTAssertEqual(item.alerts.filter(\.on).map(\.alert), [.minutes(10)])        var change = DaysChange()        change.alert = .off        XCTAssertEqual(change.json["alert"] as? String, "none")        change.alert = .minutes(30)        XCTAssertEqual(change.json["alert"] as? Int, 30)    }    func testEveryReadCarriesThePhonesZoneAndToday() async throws {        let core = FakeDaysCore(["days.span": #"{"today":"2026-11-20","days":[]}"#])        _ = try await book(core).span(from: "2026-11-16", to: "2026-12-04")        let sent = await core.sent        XCTAssertEqual(sent.first?.method, "days.span")        XCTAssertEqual(sent.first?.body["timezone"] as? String, "Europe/London")        XCTAssertEqual(sent.first?.body["today"] as? String, friday)        XCTAssertEqual(sent.first?.body["from"] as? String, "2026-11-16")    }    // RULE: a span is read whole up to 370 days (CONTRACT §2, Android bd81b91d54), so the months Days opens on are one read and a long quiet run one fold.    func testASpanIsReadInPartsOfAtMost370Days() async throws {        let core = FakeDaysCore(["days.span": #"{"today":"2026-11-20","days":[{"day":"2026-11-20","number":"20","weekday":"Friday","month":"November","today":true,"rows":[]}]}"#])        _ = try await book(core).span(from: "2026-10-23", to: "2027-01-15")        _ = try await book(core).span(from: "2026-01-01", to: "2027-02-10")        let sent = await core.sent.map { "\($0.body["from"] as? String ?? "")…\($0.body["to"] as? String ?? "")" }        XCTAssertEqual(sent, ["2026-10-23…2027-01-15", "2026-01-01…2027-01-05", "2027-01-06…2027-02-10"])    }    func testAQuietStretchOverTheEdgeOfTwoReadsIsOneFold() async throws {        let core = FakeSpanCore()        let span = try await book(core).span(from: "2026-01-01", to: "2027-02-10")        let folds = span.days.compactMap { if case .fold(let f) = $0 { f } else { nil } }        XCTAssertEqual(folds.map { $0.from }, ["2027-01-01"])        XCTAssertEqual(folds.first?.to, "2027-01-10")    }    func testAddingSendsThePillsDayAndTimeAndReadsWhereItLanded() async throws {        let core = FakeDaysCore(["days.add": #"{"table":"event","id":"e1","day":"2026-11-24","time":"8:30"}"#])        let added = try await book(core).add("Call the plumber", where: "days", dayInView: friday, day: .some("2026-11-24"), time: "8:30", mark: "phone")        XCTAssertEqual(added, DaysAdded(table: "event", id: "e1", day: "2026-11-24", time: "8:30"))        let body = await core.sent[0].body        XCTAssertEqual(body["day"] as? String, "2026-11-24")        XCTAssertEqual(body["time"] as? String, "8:30")        XCTAssertEqual(body["mark"] as? String, "phone")        XCTAssertEqual(body["dayInView"] as? String, friday)    }    func testNoDaySetOnThePillIsSentAsNull() async throws {        let core = FakeDaysCore(["days.add": #"{"table":"todo","id":"t1","day":null,"time":null}"#])        let added = try await book(core).add("Fix the shelf", where: "sometime", dayInView: nil, day: .some(nil), time: nil, mark: nil)        XCTAssertNil(added?.day)        let body = await core.sent[0].body        XCTAssertTrue(body["day"] is NSNull)        XCTAssertNil(body["time"])    }    func testAMoveOfOneOccurrenceSaysWhichAndSometimeIsNull() async throws {        let core = FakeDaysCore(["days.move": #"{"id":"e","moved":true}"#])        try await book(core).move(table: "event", id: "e", day: "2026-11-24", occurrenceAt: "2026-11-20T09:00:00.000Z")        try await book(core).move(table: "todo", id: "t", day: nil, occurrenceAt: nil)        let sent = await core.sent        XCTAssertEqual(sent[0].body["occurrenceAt"] as? String, "2026-11-20T09:00:00.000Z")        XCTAssertTrue(sent[1].body["day"] is NSNull)        XCTAssertEqual(sent[1].body["timezone"] as? String, "Europe/London")    }    func testTickAndUntickAreDoneAndUndone() async throws {        let core = FakeDaysCore(["days.done": #"{"id":"t","done":true}"#, "days.undone": #"{"id":"t","done":false}"#])        try await book(core).done("t", true)        try await book(core).done("t", false)        let methods = await core.sent.map(\.method)        XCTAssertEqual(methods, ["days.done", "days.undone"])    }    func testAToDosSheetReadsItsGroupAndTheGroupsToChooseFrom() async throws {        let core = FakeDaysCore([            "days.item": #"{"table":"todo","id":"t","whose":"yours","says":"Yours","words":"Fix the shelf","day":null,"time":null,"end":null,"mark":"house","note":null,"group":{"id":"g1","name":"Home"},"alert":null,"done":false,"repeats":true,"canChange":{"title":true,"time":true,"mark":true,"note":true,"alert":false}}"#,            "days.groups": #"{"all":"All","count":4,"groups":[{"id":"g1","name":"Home","count":3},{"id":"g2","name":"Work","count":1}]}"#,        ])        let item = try await book(core).item(table: "todo", id: "t", occurrenceAt: nil)        XCTAssertEqual(item.group, "g1")        XCTAssertEqual(item.groups.map(\.name), ["Home", "Work"])        XCTAssertTrue(item.repeats)        XCTAssertTrue(item.canChange.group)        XCTAssertFalse(item.canChange.alert)        let methods = await core.sent.map(\.method)        XCTAssertEqual(methods, ["days.item", "days.groups"])    }    func testAGoogleEventsSheetHoldsItsTimeAndTitle() async throws {        let core = FakeDaysCore([            "days.item": #"{"table":"event","id":"e","whose":"google","says":"From Google Calendar","words":"Standup","day":"2026-11-20","time":"9:00","end":"9:15","mark":null,"note":null,"alert":10,"done":false,"repeats":false,"canChange":{"title":false,"time":false,"mark":true,"note":true,"alert":true}}"#,        ])        let item = try await book(core).item(table: "event", id: "e", occurrenceAt: "2026-11-20T09:00:00.000Z")        XCTAssertEqual(item.whose, .google)        XCTAssertFalse(item.canChange.title)        XCTAssertFalse(item.canChange.time)        XCTAssertFalse(item.canChange.group)        let sent = await core.sent        XCTAssertEqual(sent.map(\.method), ["days.item"])        XCTAssertEqual(sent[0].body["occurrenceAt"] as? String, "2026-11-20T09:00:00.000Z")    }    func testANewGroupGoesWithTheRestInDaysChange() async throws {        let core = FakeDaysCore(["days.change": #"{"id":"t","changed":true}"#])        var change = DaysChange()        change.title = .some("Fix the shelf today")        change.group = .some("g2")        try await book(core).change(table: "todo", id: "t", occurrenceAt: nil, change)        let sent = await core.sent        XCTAssertEqual(sent.map(\.method), ["days.change"])        XCTAssertEqual(sent[0].body["group"] as? String, "g2")        XCTAssertEqual(sent[0].body["title"] as? String, "Fix the shelf today")    }    func testNoGroupIsSentAsNull() async throws {        let core = FakeDaysCore(["days.change": #"{"id":"t","changed":true}"#])        var change = DaysChange()        change.group = .some(nil)        try await book(core).change(table: "todo", id: "t", occurrenceAt: nil, change)        let sent = await core.sent        XCTAssertEqual(sent.map(\.method), ["days.change"])        XCTAssertTrue(sent[0].body["group"] is NSNull)    }    func testACoreRefusalComesBackAsItsSentence() async throws {        let core = FakeDaysCore([:], refuse: ["days.move": ("google_read_only", "This event is from Google Calendar. Change its time and title in Google.")])        do {            try await book(core).move(table: "event", id: "e", day: "2026-11-24", occurrenceAt: nil)            XCTFail("a Google event moved")        } catch {            XCTAssertEqual(ActionRefused.words(for: error), "This event is from Google Calendar. Change its time and title in Google.")        }    }    func testADayOrTimeSetToNoneOnThePillDropsTheWordsThatSaidIt() {        let words = "Dinner with Rose Thursday 7pm"        // As days.read_line marks them: characters 17..<25 the day, 26..<29 the time.        let read = DaysReadLine(title: "Dinner with Rose", day: "2026-11-26", time: "19:00", end: nil, kind: .event, pill: "Thu 26 Nov · 19:00",                                marks: [], said: [DaysSaid(from: 17, to: 25, what: "day"), DaysSaid(from: 26, to: 29, what: "time")])        XCTAssertEqual(DaysPillPick.words(words, read: read, pick: nil), words)        XCTAssertEqual(DaysPillPick.words(words, read: read, pick: DaysPillPick(day: "2026-11-26", time: nil)), "Dinner with Rose Thursday")        XCTAssertEqual(DaysPillPick.words(words, read: read, pick: DaysPillPick(day: nil, time: nil)), "Dinner with Rose")        XCTAssertEqual(DaysPillPick.words(words, read: read, pick: DaysPillPick(day: nil, time: "19:00")), "Dinner with Rose 7pm")        XCTAssertEqual(DaysPillPick.clock("09:05"), "9:05")        XCTAssertNil(DaysPillPick.clock("25:00"))    }    func testThePillsStretchesCountCharactersAsTheCoreDoes() {        // The core counts characters (Unicode scalars), not UTF-16 units: an emoji before the day is one.        let words = "🎂 cake Thursday"        let read = DaysReadLine(title: "🎂 cake", day: "2026-11-26", time: nil, end: nil, kind: .todo, pill: nil,                                marks: [], said: [DaysSaid(from: 7, to: 15, what: "day")])        XCTAssertEqual(DaysPillPick.words(words, read: read, pick: DaysPillPick(day: nil, time: nil)), "🎂 cake")    }    // MARK: Round three: nothing moves at the moment a person acts    private let todayWithAToDo = #"{"today":"2026-11-20","days":[{"day":"2026-11-20","number":"20","weekday":"Friday","month":"November","today":true,"rows":[{"key":"todo:t","kind":"todo","time":null,"end":null,"mark":{"kind":"tick","done":false},"words":"Invented chore","suffix":null,"done":false,"whose":"yours","opens":{"sheet":"todo","id":"t"}}]}]}"#    @MainActor private func model(_ core: any CottonCalling) -> DaysModel {        let m = DaysModel(book: book(core), clock: .fixed(friday, zone: TimeZone(identifier: "Europe/London")!))        m.group = nil        return m    }    @MainActor private func todays(_ m: DaysModel) -> [DaysRow] {        m.days.compactMap { if case .day(let d) = $0, d.today { d.rows } else { nil } }.first ?? []    }    // RULE (DECISIONS: nothing moves at the moment a person acts): a tick shows on the row at once, nothing is read after it, and every later read carries it as keep with the day its row stood on, until the list is opened again.    @MainActor func testATickShowsAtOnceReadsNothingAndIsKept() async throws {        let core = FakeDaysCore(["days.span": todayWithAToDo, "days.sometime": "[]", "days.done": #"{"id":"t","done":true}"#])        let m = model(core)        await m.read()        let row = try XCTUnwrap(todays(m).first)        let before = await core.sent.count        m.tick(row)        XCTAssertTrue(m.drawn(row).done, "the tick shows before any answer")        XCTAssertEqual(m.drawn(row).mark, .tick(done: true))        await m.written()        let after = await core.sent.dropFirst(before).map(\.method)        XCTAssertEqual(after, ["days.done"], "the tick wrote and read nothing")        await m.read()        let read = await core.sent        let span = try XCTUnwrap(read.last { $0.method == "days.span" })        let keep = try XCTUnwrap(span.body["keep"] as? [[String: Any]])        XCTAssertEqual(keep.first?["id"] as? String, "t")        XCTAssertEqual(keep.first?["day"] as? String, friday)        let sometime = try XCTUnwrap(read.last { $0.method == "days.sometime" })        XCTAssertNotNil(sometime.body["keep"], "Sometime is read with the same keep")        await m.tidy()        let reread = await core.sent        let tidied = try XCTUnwrap(reread.last { $0.method == "days.span" })        XCTAssertNil(tidied.body["keep"], "opened again, nothing is kept")        XCTAssertFalse(m.drawn(row).done, "opened again, the row is as the core answers it")    }    // RULE: a second tap on the circle acts on what the first left (untick), and the two writes go in the order made.    @MainActor func testTwoTapsTickThenUntickInOrder() async throws {        let core = FakeDaysCore(["days.span": todayWithAToDo, "days.sometime": "[]", "days.done": "{}", "days.undone": "{}"])        let m = model(core)        await m.read()        let row = try XCTUnwrap(todays(m).first)        let before = await core.sent.count        m.tick(m.drawn(row))        m.tick(m.drawn(row))        XCTAssertFalse(m.drawn(row).done, "the second tap unticked")        await m.written()        let after = await core.sent.dropFirst(before).map(\.method)        XCTAssertEqual(after, ["days.done", "days.undone"])    }    // RULE: only the newest read lands: an answer asked before a later read never draws over it.    @MainActor func testOnlyTheNewestReadLands() async throws {        let core = SlowFirstSpanCore()        let m = model(core)        let first = Task { await m.later() }        try await Task.sleep(for: .milliseconds(80))        await m.later()        await first.value        XCTAssertEqual(todays(m).map(\.words), ["new"], "the older answer, landing last, was dropped")    }    // RULE (contract §2, The end): a read that says the list ends draws its closing line and no read goes further ahead.    @MainActor func testTheEndStopsTheReadsAhead() async throws {        let core = FakeDaysCore([            "days.span": #"{"today":"2026-11-20","days":[{"day":"2026-11-20","number":"20","weekday":"Friday","month":"November","today":true,"rows":[]}],"end":{"after":"2026-11-20","words":"Nothing planned after today."},"begins":"2026-11-20"}"#,            "days.sometime": "[]",        ])        let m = model(core)        await m.read()        XCTAssertEqual(m.end?.words, "Nothing planned after today.")        XCTAssertEqual(m.begins, friday)        let before = await core.sent.count        await m.later()        await m.earlier()        let after = await core.sent.count        XCTAssertEqual(after, before, "nothing lies ahead or before: nothing more is read")    }    // RULE (DECISIONS: never two folds in a row): a quiet stretch longer than one read is one fold.    func testAQuietStretchLongerThanOneReadIsOneFold() async throws {        let span = try await book(LongQuietCore()).span(from: "2026-01-01", to: "2027-12-31")        let folds = span.days.compactMap { if case .fold(let f) = $0 { f } else { nil } }        XCTAssertEqual(folds.count, 1, "one fold: \(folds)")        XCTAssertEqual(folds.first?.from, "2026-06-01")        XCTAssertEqual(folds.first?.to, "2027-09-01")        XCTAssertEqual(folds.first?.count, 458)    }    // RULE (contract §2, Edge folds reach): a fold reaching past a read's end is not read again; the next read starts past it.    func testTheNextReadStartsPastAFoldThatReaches() async throws {        let core = FakeDaysCore(["days.span": #"{"today":"2026-11-20","days":[{"fold":{"from":"2026-01-01","to":"2027-03-01","count":425,"words":"quiet"}}]}"#])        _ = try await book(core).span(from: "2026-01-01", to: "2027-02-10")        let sent = await core.sent.map { $0.body["from"] as? String ?? "" }        XCTAssertEqual(sent, ["2026-01-01"], "the fold already reached past the asked end")    }    // RULE (contract §3): the sheet's quick day row is read from days.item's choices, Sometime as null.    func testTheSheetsQuickChoicesAreRead() {        let item = DaysRead.item(table: "todo", id: "t", json("""        {"whose":"yours","words":"Fix the shelf","day":"2026-11-20","choices":[{"key":"today","day":"2026-11-20"},{"key":"tomorrow","day":"2026-11-21"},{"key":"next_week","day":"2026-11-23"},{"key":"sometime","day":null}],"canChange":{"title":true,"time":true}}        """) as! [String: Any])        XCTAssertEqual(item.choices.map(\.key), ["today", "tomorrow", "next_week", "sometime"])        XCTAssertNil(item.choices.last?.day)        XCTAssertEqual(item.choices[2].day, "2026-11-23")    }}/// A core answering `days.*` and `groups.*` in the contract's shapes, saying what it was asked.private actor FakeDaysCore: CottonCalling {    struct Sent: @unchecked Sendable {        let method: String        let body: [String: Any]    }    private let answers: [String: String]    private let refuse: [String: (String, String)]    private(set) var sent: [Sent] = []    init(_ answers: [String: String], refuse: [String: (String, String)] = [:]) {        self.answers = answers        self.refuse = refuse    }    func callRaw(_ method: String, requestJSON: String) async throws -> String {        sent.append(Sent(method: method, body: (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8)) as? [String: Any]) ?? [:]))        if let (code, message) = refuse[method] {            return #"{"ok":false,"error":{"code":"\#(code)","message":"\#(message)"}}"#        }        return #"{"ok":true,"data":\#(answers[method] ?? "{}")}"#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}/// A span whose quiet stretch 1–10 Jan runs over the edge of the first read (ending 5 Jan).private actor FakeSpanCore: CottonCalling {    func callRaw(_ method: String, requestJSON: String) async throws -> String {        let body = (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8)) as? [String: Any]) ?? [:]        let from = body["from"] as? String ?? "", to = body["to"] as? String ?? ""        let a = max(from, "2027-01-01"), b = min(to, "2027-01-10")        let fold = a <= b ? #"{"fold":{"from":"\#(a)","to":"\#(b)","count":2,"words":"quiet"}}"# : nil        let days = [fold].compactMap { $0 }.joined(separator: ",")        return #"{"ok":true,"data":{"today":"2026-11-20","days":[\#(days)]}}"#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}/// A span whose first read answers slowly with an older list ("old") and whose second answers at once ("new").private actor SlowFirstSpanCore: CottonCalling {    private var calls = 0    func callRaw(_ method: String, requestJSON: String) async throws -> String {        guard method == "days.span" else { return #"{"ok":true,"data":{}}"# }        calls += 1        let words = calls == 1 ? "old" : "new"        if calls == 1 { try await Task.sleep(for: .milliseconds(400)) }        return #"{"ok":true,"data":{"today":"2026-11-20","days":[{"day":"2026-11-20","number":"20","weekday":"Friday","month":"November","today":true,"rows":[{"key":"todo:\#(words)","kind":"todo","mark":{"kind":"tick","done":false},"words":"\#(words)","done":false,"whose":"yours","opens":{"sheet":"todo","id":"\#(words)"}}]}]}}"#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}/// A quiet stretch from 1 Jun 2026 to 1 Sep 2027, longer than one read: each read answers its own part of it as a fold.private actor LongQuietCore: CottonCalling {    func callRaw(_ method: String, requestJSON: String) async throws -> String {        let body = (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8)) as? [String: Any]) ?? [:]        let from = body["from"] as? String ?? "", to = body["to"] as? String ?? ""        let a = max(from, "2026-06-01"), b = min(to, "2027-09-01")        let fold = a <= b ? #"{"fold":{"from":"\#(a)","to":"\#(b)","count":2,"words":"quiet"}}"# : nil        return #"{"ok":true,"data":{"today":"2026-11-20","days":[\#([fold].compactMap { $0 }.joined(separator: ","))]}}"#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}#endif