Cotton code
1956 lines · 114.1 KB · SwiftRaw
// Chat Dev's invented chats, for looking at the Warm screens on a simulator:// `-chat-warm-seed YES` draws the core's own answers over invented people,// written once by the core's test `write_chat_warm_fixture`// (Resources/Fixtures/chat-warm.json), and skips sign-in. `-chat-warm-long N`// adds a conversation of N messages (5,000 for the scroll check), paged as// the core pages, its words the fixture's own lines in turn. Never in a store// build, and never anyone's real chats. The people and group asks that want// the server (chat.contact, chat.profile, chat.group.info …)// answer from invented answers in the contract's shapes// (Resources/Fixtures/chat-warm-people.json, ChatWarmSeedCore); a change asked// of them answers ok and changes nothing. `-chat-warm-voice YES`: the microphone held// records an invented recording (Fixtures/chat-warm-voice.m4a, a made-up// sentence in a system voice), as the simulator has no microphone, and its// words are the sentence it says (`-chat-warm-voice-hear YES` hears it with// the phone's own engine instead). The safety number (CONTRACT.md "Safety// number") is the core's own answers between invented phones, written by the// same test: Asha's chat says her safety number changed, her page and screen// answer as the core does, and `-chat-safety-scan theirs|old|other` scans her// phone's code, her phone's before the change, or Meera's chat's// (`ChatWarmSafety`); the verified mark is held for the launch. Disappearing// messages are the core's answers too: a length chosen in Asha's chat answers// as the core did, and her chat then holds the core's timer, header and line.#if os(iOS) && COTTON_DEVimport AVFoundationimport CottonKitimport Foundation#if canImport(UIKit)import UIKit#endif/// A switch the seed's core and book share, set once from any thread.final class ChatWarmFlag: @unchecked Sendable {    private let lock = NSLock()    private var value = false    var on: Bool { lock.withLock { value } }    func set() { lock.withLock { value = true } }}enum ChatWarmSeed {    static var asked: Bool { UserDefaults.standard.bool(forKey: "chat-warm-seed") }    static var long: Int { UserDefaults.standard.integer(forKey: "chat-warm-long") }    /// `-chat-warm-open <thread>` opens that chat over the list.    static var open: String? { UserDefaults.standard.string(forKey: "chat-warm-open") }    static let longThread = "chat-warm-long"    /// Meera's chat carries an invented photo, voice message and file.    static let mediaThread = "11111111-1111-4111-8111-0000000000e1"    /// Ravi's chat stands for someone not on Cotton yet.    static let notYetThread = "11111111-1111-4111-8111-0000000000d1"    /// The imported pictures whose files the store does not have (the Hill trip's m-w7, which the core's    /// fixture already says is gone): no file, as a 404, should one be asked.    static let gonePictures: Set<String> = ["m-w7"]    /// `-chat-warm-place calls|you` opens that place.    static var place: String? { UserDefaults.standard.string(forKey: "chat-warm-place") }    /// `-chat-warm-you profile|sync|claude|privacy|notifications|storage|help|about` opens that page of You.    static var youPage: String? { UserDefaults.standard.string(forKey: "chat-warm-you") }    /// `-chat-warm-claude timed`: Your Claude reads for a while (until 10:30), not any time.    static var claudeTimed: Bool { UserDefaults.standard.string(forKey: "chat-warm-claude") == "timed" }    /// `-chat-warm-agent connect`: no assistant connected yet, so Add an agent answers the line to connect one.    static var agentConnect: Bool { UserDefaults.standard.string(forKey: "chat-warm-agent") == "connect" }    /// `-chat-warm-unreachable YES`: Sync says three changes wait and Cotton is out of reach.    static var unreachable: Bool { UserDefaults.standard.bool(forKey: "chat-warm-unreachable") }    /// `-chat-warm-person YES` opens the opened chat's person page.    static var person: Bool { UserDefaults.standard.bool(forKey: "chat-warm-person") }    /// `-chat-warm-timer <seconds>` chooses that disappearing length in the opened chat as it opens;    /// `-chat-warm-timer-sheet YES` opens the Disappearing messages sheet on its page.    static var timer: Int? { UserDefaults.standard.object(forKey: "chat-warm-timer").flatMap { Int("\($0)") } }    static var timerSheet: Bool { UserDefaults.standard.bool(forKey: "chat-warm-timer-sheet") }    /// `-chat-warm-new YES` opens New chat.    static var new: Bool { UserDefaults.standard.bool(forKey: "chat-warm-new") }    /// `-chat-warm-refuse <method>` answers that method `not_connected`, as a phone whose copy is being made again.    static var refused: String? { UserDefaults.standard.string(forKey: "chat-warm-refuse") }    /// `-chat-warm-slow <method>` answers that method three seconds late, as a server far away.    static var slow: String? { UserDefaults.standard.string(forKey: "chat-warm-slow") }    /// Who the seed's invented phone is signed in as, before any profile was read: its number alone.    static let signedIn = ChatYouRemembered.Held(name: nil, number: "+15550100100")    /// `-chat-warm-send-picture <seconds>` sends five invented pictures, then one, in the opened chat, as the composer    /// does (`seed-sent-1`, `seed-sent-2`), and their upload takes that long (a slow line): it must stand at once from the phone's own file, never "Picture not    /// available", and say nothing under it until the core's quiet moment has passed.    static var sendPicture: Double? { UserDefaults.standard.string(forKey: "chat-warm-send-picture").flatMap(Double.init) }    /// `-chat-warm-picture-wait <seconds>`: every picture's file takes that long to come, as from a server far away    /// (a picture still going up still opens from the phone's own file at once). Its preview, carried in the message,    /// must stand on the first frame meanwhile: never a blank box.    static var pictureWait: Double? { UserDefaults.standard.string(forKey: "chat-warm-picture-wait").flatMap(Double.init) }    /// `-chat-warm-freeable <bytes>`: Storage offers that much to Free up space (the seed's phone holds no files of    /// its own); once it is freed the invented pictures are off the phone and come back slowly, as from the account.    static var freeable: Int64? { UserDefaults.standard.string(forKey: "chat-warm-freeable").flatMap { Int64($0) } }    static let freed = ChatWarmFlag()    /// `-chat-warm-vote <seconds>`: that long after the chats are first watched, Farid's vote on the Book club's poll    /// arrives, as the link's change lands it (the core's answer after it), and the open chat is told so.    static var vote: Double? { UserDefaults.standard.string(forKey: "chat-warm-vote").flatMap(Double.init) }    static let voted = ChatWarmFlag()    static let voteComing = ChatWarmFlag()    /// `-chat-warm-revoke <seconds>`: the Book club opens as it stood before its deletes, and that long after the chats    /// are first watched the deletes land, as the link's revokes do, and the open chat is told so.    static var revoke: Double? { UserDefaults.standard.string(forKey: "chat-warm-revoke").flatMap(Double.init) }    static let revoked = ChatWarmFlag()    static let revokeComing = ChatWarmFlag()    /// `-chat-warm-pictures N`: the long chat (`-chat-warm-long`) carries a picture in every third message.    static var longPictures: Bool { UserDefaults.standard.bool(forKey: "chat-warm-pictures") }    /// An invented picture written into the outbox's folder, as a picked photo is.    static func inventedAttachment(_ n: Int = 0) -> ChatAttachment? {        #if canImport(UIKit)        let url = ChatOutbox.folder.appendingPathComponent("chat-warm-sent-\(UUID().uuidString).png")        let image = UIGraphicsImageRenderer(size: CGSize(width: 480, height: 360)).image { context in            UIColor(red: 0.36 + 0.1 * CGFloat(n % 4), green: 0.55, blue: 0.62 - 0.08 * CGFloat(n % 4), alpha: 1).setFill()            context.fill(CGRect(x: 0, y: 0, width: 480, height: 360))            UIColor(red: 0.93, green: 0.78, blue: 0.45, alpha: 1).setFill()            context.cgContext.fillEllipse(in: CGRect(x: 300, y: 60, width: 110, height: 110))        }        guard (try? image.pngData()?.write(to: url)) != nil else { return nil }        return ChatOutbox.attachment(at: url)        #else        return nil        #endif    }    /// A link preview's invented picture (ChatWarmLinks.swift): a hill under a sky, larger than a card's, so the phone    /// makes it small.    static func inventedHill() -> Data? {        let size = CGSize(width: 1200, height: 800)        let format = UIGraphicsImageRendererFormat()        format.scale = 1        let image = UIGraphicsImageRenderer(size: size, format: format).image { context in            let colours = [UIColor(red: 0.55, green: 0.7, blue: 0.85, alpha: 1).cgColor, UIColor(red: 0.95, green: 0.8, blue: 0.6, alpha: 1).cgColor]            if let sky = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colours as CFArray, locations: [0, 1]) {                context.cgContext.drawLinearGradient(sky, start: .zero, end: CGPoint(x: 0, y: 520), options: [])            }            UIColor(red: 0.3, green: 0.5, blue: 0.35, alpha: 1).setFill()            let hill = UIBezierPath()            hill.move(to: CGPoint(x: 0, y: 800))            hill.addLine(to: CGPoint(x: 0, y: 560))            hill.addQuadCurve(to: CGPoint(x: 1200, y: 520), controlPoint: CGPoint(x: 600, y: 260))            hill.addLine(to: CGPoint(x: 1200, y: 800))            hill.fill()        }        return image.jpegData(compressionQuality: 0.92)    }    /// `-chat-warm-call ring|live|video|notes` draws the call screen in that state; `notes-bar` its folded bar with notes;    /// `group`, `group8`, `group-notes` a group call's (four on video, eight on voice, notes taken).    static var call: String? { UserDefaults.standard.string(forKey: "chat-warm-call") }    /// `-chat-warm-pick YES`: Photos and videos hands over an invented picture instead of opening the library.    static var pick: Bool { UserDefaults.standard.bool(forKey: "chat-warm-pick") }    /// `-chat-warm-wa-land <s>`: pictures sent to WhatsApp as one grid land that many seconds after Send, a message    /// each, as the Mac's link lands them (FEEDBACK-4 B3).    static var waLand: Double? { UserDefaults.standard.string(forKey: "chat-warm-wa-land").flatMap(Double.init) }    /// How many invented pictures Photos and videos has handed over: each a wash of its own tone.    nonisolated(unsafe) static var picked = 0    /// `-chat-warm-linked YES`: the list is the linked copy's (WhatsApp through the Mac), as the core answers it.    static var linked: Bool { UserDefaults.standard.bool(forKey: "chat-warm-linked") }    /// `-chat-warm-wa-refuse YES`: a WhatsApp chat's send with files is refused as the core refuses a file over 16 MB.    static var waRefuse: Bool { UserDefaults.standard.bool(forKey: "chat-warm-wa-refuse") }    /// `-chat-warm-wa-words-only YES`: Tara's chat as a server whose outbox takes no file yet answers it (words only).    static var waWordsOnly: Bool { UserDefaults.standard.bool(forKey: "chat-warm-wa-words-only") }    /// `-chat-warm-pick-file YES`: Files hands over an invented document ("Train times.pdf") instead of opening the    /// picker; `large`, one past WhatsApp's 100 MB ("Hill line map.pdf", its length set, never written out).    static var pickFile: String? { UserDefaults.standard.string(forKey: "chat-warm-pick-file") }    /// `-chat-warm-wa-no-documents YES`: Tara's chat as a server whose outbox has no `file_name` yet answers a document.    static var waNoDocuments: Bool { UserDefaults.standard.bool(forKey: "chat-warm-wa-no-documents") }    /// `-chat-warm-wa-vote YES`: Tara's chat holds her poll from WhatsApp, which he can vote on, as the core answers it;    /// `failed`: his vote the Mac could not send; `refuse`: a vote refused in the core's words.    static var waVote: String? { UserDefaults.standard.string(forKey: "chat-warm-wa-vote") }    /// `-chat-warm-wa-poll alone`: Tara's writing box as a server whose outbox takes a poll but no file answers it (the    /// plus with Poll alone); `refuse`: a poll's send is refused in the core's words.    static var waPoll: String? { UserDefaults.standard.string(forKey: "chat-warm-wa-poll") }    /// `-chat-warm-wa-changes YES`: Tara's chat holds his fresh text (Edit, Delete for everyone, Delete for me), his of    /// hours ago and hers, as the core answers them; `failed`: the edit and the delete for everyone the Mac could not send.    static var waChanges: String? { UserDefaults.standard.string(forKey: "chat-warm-wa-changes") }    /// `-chat-warm-wa-late YES`: WhatsApp's windows closed between the long press and the tap (`too_late`, `too_late_delete`).    static var waLate: Bool { UserDefaults.standard.bool(forKey: "chat-warm-wa-late") }    /// The microphone's state as the phone would answer it, for Record's card (`-chat-warm-mic notDetermined|denied`).    static var microphone: CapabilityAccess? {        switch UserDefaults.standard.string(forKey: "chat-warm-mic") {        case "notDetermined": .notDetermined        case "denied": .denied        case "authorized": .authorized        default: nil        }    }    /// A new account, none of the person's chats yet (`-chat-warm-fresh YES`).    static var fresh: Bool { UserDefaults.standard.bool(forKey: "chat-warm-fresh") }    /// `-chat-warm-voice YES`: the microphone held records the invented recording.    static var voice: Bool { UserDefaults.standard.bool(forKey: "chat-warm-voice") }    /// `-chat-warm-voice-hear YES`: its words are heard by the phone's own engine, not taken as written.    static var voiceHear: Bool { UserDefaults.standard.bool(forKey: "chat-warm-voice-hear") }    /// What the invented recording says (invented words, kept in the fixture beside the invented people).    static var voiceWords: String { ChatWarmSeedCore.answers["seed.voice.said"]?.string ?? "" }    /// The words under the voice message Meera's chat ends with (invented).    static var heardWords: String { ChatWarmSeedCore.answers["seed.voice.heard"]?.string ?? "" }    /// The invented recording, copied where a recorded voice message waits, and its length.    static func recordedVoice() -> (url: URL, seconds: Double)? {        guard let source = Bundle.module.url(forResource: "chat-warm-voice", withExtension: "m4a", subdirectory: "Fixtures") else { return nil }        let url = ChatOutbox.folder.appendingPathComponent("chat-warm-voice-\(UUID().uuidString).m4a")        guard (try? FileManager.default.copyItem(at: source, to: url)) != nil, let file = try? AVAudioFile(forReading: url) else { return nil }        return (url, Double(file.length) / file.processingFormat.sampleRate)    }    /// The invented picture Photos and videos hands over: a warm wash written where an attachment waits.    static func pickedPhoto() -> ChatAttachment? {        #if canImport(UIKit)        let url = ChatOutbox.folder.appendingPathComponent("chat-warm-picked-\(UUID().uuidString).png")        // Cool blue-greens, a shade apart each time, so each picked picture is told from the others.        let tones: [(CGFloat, CGFloat, CGFloat)] = [(0.45, 0.6, 0.55), (0.35, 0.55, 0.7), (0.3, 0.65, 0.45)]        let tone = tones[picked % tones.count]        picked += 1        let image = UIGraphicsImageRenderer(size: CGSize(width: 480, height: 360)).image { context in            let colours = [UIColor(red: tone.0, green: tone.1, blue: tone.2, alpha: 1).cgColor, UIColor(red: tone.0 * 0.45, green: tone.1 * 0.5, blue: tone.2 * 0.5, alpha: 1).cgColor]            guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colours as CFArray, locations: [0, 1]) else { return }            context.cgContext.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 480, y: 360), options: [])        }        guard (try? image.pngData()?.write(to: url)) != nil else { return nil }        return ChatOutbox.attachment(at: url)        #else        return nil        #endif    }    /// The invented document Files hands over (`-chat-warm-pick-file`): written outside the outbox's folder under its    /// own name, as the picker hands over a file of elsewhere, so it is copied in as a picked file is.    static func pickedDocument() -> URL? {        let large = pickFile == "large"        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("chat-warm-files-\(UUID().uuidString)", isDirectory: true)        // The invented names and page are the seed's answers (chat-warm-people.json), never words in the code.        let said = { (key: String) in ChatWarmSeedCore.answers[key]?.string ?? "" }        let url = folder.appendingPathComponent(said(large ? "seed.file.large" : "seed.file.name"))        do {            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)            // As long as the core's own (`write_chat_warm_fixture`'s 24 000 bytes), so the size it says is this file's.            let page = Data(said("seed.file.page").utf8)            try (page + Data(repeating: 0x20, count: 24_000 - page.count)).write(to: url)            if large {                let handle = try FileHandle(forWritingTo: url)                try handle.truncate(atOffset: (100 << 20) + 1)                try handle.close()            }        } catch { return nil }        return url    }    /// The call screen as the core would answer it, over invented Asha.    static func callScreen(_ state: String) -> ChatCallScreen {        // `group`, `group8`, `group-notes`: the core's own group screens for invented calls (CONTRACT.md "Group calls",        // Fixtures/chat-group-call.json, written by cotton-core `write_group_call_seed`).        if state.hasPrefix("group"), let screen = groupCallScreen(state) { return screen }        func w(_ key: String) -> String { ShellLines.line("chat", key) }        let video = state == "video"        var controls = [ChatCallControl(id: "mute", label: w("app.call.control.mute"), on: false),                        ChatCallControl(id: "speaker", label: w("app.call.control.speaker"), on: state == "live")]        if video {            controls.append(ChatCallControl(id: "video", label: w("app.call.control.video"), on: true))            controls.append(ChatCallControl(id: "flip", label: w("app.call.control.flip"), on: false))        }        controls.append(ChatCallControl(id: "end", label: w("app.call.control.end"), on: false))        let ringing = state == "ring"        return ChatCallScreen(            shown: true, phase: ringing ? "ringing" : "live", name: ChatWarmSeed.invented("asha"),            picture: ChatAvatar(photo: nil, initials: "AV", tint: 3),            status: ringing ? w("app.call.ring.voice") : nil,            liveAt: ringing ? nil : (Date.now.timeIntervalSince1970 - 194) * 1000,            video: video, camera: video, controls: ringing ? [] : controls,            ring: ringing ? ChatCallRing(title: w("app.call.ring.voice"), answer: w("app.call.ring.answer"), decline: w("app.call.ring.decline")) : nil,            bar: ringing ? nil : ShellLines.line("chat", "app.call.bar", ["name": ChatWarmSeed.invented("asha")]), endedFor: 0, thread: nil,            // `-chat-warm-call notes`: Asha is taking notes, as the core says it (CONTRACT.md "Take notes").            notes: state == "notes" ? ChatCallNotes(by: [.init(member: "m-asha", name: ChatWarmSeed.invented("asha"))],                                                    line: ShellLines.line("chat", "app.call.notes.one", ["name": ChatWarmSeed.invented("asha")]),                                                    mark: true) : nil)    }    static func groupCallScreen(_ state: String) -> ChatCallScreen? {        guard let url = Bundle.module.url(forResource: "chat-group-call", withExtension: "json", subdirectory: "Fixtures"),              let data = try? Data(contentsOf: url),              let all = try? JSONDecoder().decode([String: JSONValue].self, from: data),              let one = all[state], let raw = try? JSONEncoder().encode(one) else { return nil }        guard var screen = try? JSONDecoder().decode(ChatCallScreen.self, from: raw) else { return nil }        // The fixture's invented call went live at its own made-up instant: the preview's clock starts minutes ago.        if screen.liveAt != nil { screen.liveAt = (Date.now.timeIntervalSince1970 - 194) * 1000 }        return screen    }    struct Fixture: Decodable {        var list: ChatListAnswer        var unread: ChatListAnswer        var groups: ChatListAnswer        var archived: ChatListAnswer        /// A new account's list: Cotton's own Downloads chat alone, and the words saying how to begin (`-chat-warm-fresh`).        var fresh: ChatListAnswer?        /// An invented document's words, drawn into the PDF Comms Dev opens (Kabir's, Comms 28 fixes 2).        struct Document: Decodable { var title: String; var lines: [String] }        var documents: [String: Document]?        /// Rows of chats in no list, as the core's read answers them (Kabir's, opened by `-chat-warm-open`).        var rows: [String: ChatListRow]?        var threads: [String: ChatThreadAnswer]        /// The safety number's answers (`chat_safety_tests::warm_fixture`).        var safety: JSONValue?        var whatsapp: WhatsAppFixture        /// Writing to a number on the linked copy (`chat_whatsapp_warm_tests::route`).        var route: RouteFixture?        /// Replying, by chat and message: the core's writing box with its strip, and the quote the reply carries.        var replies: [String: [String: ReplyFixture]]?        /// Storage by chat: the core's answers before anything is freed and after each chat is freed by itself.        var storage: JSONValue?        /// Disappearing messages, by chat and length ("604800", "0" …, and "day": the day its first line stands under).        var timers: [String: [String: TimerFixture]]?        /// The voice player: which notes' files can't be fetched, the core's refusals in its words, the speed.        var voice: VoiceFixture?        /// Search over the invented chats by words, as `chat.list { search }` answered them (the Book club's deleted        /// messages' words among them, which find nothing).        var searches: [String: ChatListAnswer]?        /// Polls shown: the Book club's poll as the core answers it once Farid's vote has come.        var votes: VotesFixture?        /// Deleted while he looks: the Book club's page before its deletes.        var revoke: RevokeFixture?        /// Link previews in Asha's chat (ChatWarmLinks.swift).        var linkPreview: ChatWarmLinks.Fixture?    }    /// A chat's page before WhatsApp's deletes landed (`write_chat_warm_fixture`'s `revoke`).    struct RevokeFixture: Decodable {        var thread: String        var before: ChatThreadAnswer    }    /// A poll's bubble after a vote arrived (`write_chat_warm_fixture`'s `votes`).    struct VotesFixture: Decodable {        var thread: String        var bubble: ChatBubble    }    /// One length chosen in a chat, as the core answers it (`write_chat_warm_fixture`): the act, then the chat's    /// timer, its header and the line it gained. The "day" entry is only the day item, in `day`.    struct TimerFixture: Decodable {        var act: ChatActAnswer?        var timer: ChatTimerCard?        var header: ChatHeader?        var lines: [ChatThreadItem]?        var day: ChatThreadItem?        init(from decoder: Decoder) throws {            if let day = try? ChatThreadItem(from: decoder), case .day = day {                self.day = day                return            }            let c = try decoder.container(keyedBy: Keys.self)            act = try c.decodeIfPresent(ChatActAnswer.self, forKey: .act)            timer = try c.decodeIfPresent(ChatTimerCard.self, forKey: .timer)            header = try c.decodeIfPresent(ChatHeader.self, forKey: .header)            lines = try c.decodeIfPresent([ChatThreadItem].self, forKey: .lines)        }        private enum Keys: String, CodingKey { case act, timer, header, lines }    }    /// The voice player's answers (`write_chat_warm_fixture`).    struct VoiceFixture: Decodable {        /// Notes whose file the seed can't fetch now (`file_offline`).        var offline: [String]        /// The core's refusals of a file, in its words, by code.        var refusals: [String: String]        var settings: Settings        struct Settings: Decodable { var voiceSpeed: Double }    }    /// The core's 36 bars from a waveform (`bubble::bars`), for the seed's own invented notes and a note sent here:    /// the core works them out for every other.    static func bars(_ wave: [Double]) -> [Double]? {        guard !wave.isEmpty else { return nil }        let n = 36        let gathered: [Double] = wave.count >= n            ? (0..<n).map { i in wave[(i * wave.count / n)..<max(i * wave.count / n + 1, (i + 1) * wave.count / n)].max() ?? 0 }            : (0..<n).map { wave[$0 * wave.count / n] }        let top = gathered.max() ?? 0        return top < 0.05 ? Array(repeating: 0, count: n) : gathered.map { $0 / top }    }    /// An invented voice note's file, `seconds` long: a soft tone rising and falling as words do, made once.    static func inventedVoice(_ message: String, seconds: Double) -> URL? {        let ms = Int(seconds * 1000)        let url = FileManager.default.temporaryDirectory.appendingPathComponent("chat-warm-voice-\(message)-\(ms).m4a")        if FileManager.default.fileExists(atPath: url.path) { return url }        // Made beside it and moved in whole, so a half-made file is never opened.        let making = FileManager.default.temporaryDirectory.appendingPathComponent("chat-warm-voice-\(message)-\(ms)-\(UUID().uuidString).m4a")        let rate = 22_050.0        let settings: [String: Any] = [AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: rate, AVNumberOfChannelsKey: 1, AVEncoderBitRateKey: 32_000]        guard let format = AVAudioFormat(standardFormatWithSampleRate: rate, channels: 1),              let file = try? AVAudioFile(forWriting: making, settings: settings, commonFormat: .pcmFormatFloat32, interleaved: false) else { return nil }        let total = Int(seconds * rate), chunk = 8_192        var at = 0        while at < total {            let count = min(chunk, total - at)            guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(count)), let out = buffer.floatChannelData?[0] else { return nil }            buffer.frameLength = AVAudioFrameCount(count)            for i in 0..<count {                let t = Double(at + i) / rate                out[i] = Float(0.2 * abs(sin(t * 2.7)) * sin(2 * .pi * 220 * t))            }            do { try file.write(from: buffer) } catch { return nil }            at += count        }        file.close()        try? FileManager.default.moveItem(at: making, to: url)        return FileManager.default.fileExists(atPath: url.path) ? url : nil    }    /// One message replied to, as the core answers it (`write_chat_warm_fixture`).    struct ReplyFixture: Decodable {        var composer: ChatComposeAnswer        var quote: ChatQuote    }    /// The core's answers over a WhatsApp chat that sends through the Mac (`write_chat_warm_fixture`).    struct WhatsAppFixture: Decodable {        /// `chat.act send`: the pending bubble, "Waiting to send".        var send: ChatActAnswer        /// `chat.act retry` of the failed text: waiting again.        var retry: ChatActAnswer        /// `chat.act retry` of a text still waiting: refused.        var refused: Refusal        /// `chat.act send` of a picture with its caption, of a video and of a voice note: each its own pending bubble.        var picture: ChatActAnswer?        var video: ChatActAnswer?        var voice: ChatActAnswer?        /// `chat.act send` of a file over WhatsApp's 16 MB: refused before anything is kept.        var tooLarge: Refusal?        /// `chat.act retry` of the picture the Mac could not send: waiting again, the same entry.        var retryPicture: ChatActAnswer?        /// Tara's writing box on a server whose outbox takes no file yet: words only.        var wordsOnly: ChatComposeAnswer?        /// A file picked as a file, sent as a document: its pending bubble under its own name, and its refusals.        var document: DocumentFixture?        /// Voting on her poll: the chat with it, his tap's answer, the vote not sent and its retry, a refusal.        var vote: VoteFixture?        struct VoteFixture: Decodable {            /// The poll's message, and the option the fixture's tap chose.            var message: String            var option: Int            /// Tara's chat with her poll, votable.            var page: ChatThreadAnswer            /// `chat.act vote`: his choice drawn at once, "Vote waiting to send".            var vote: ChatActAnswer            /// The vote the Mac could not send ("Vote not sent: <why>", Retry), and its retry.            var failed: ChatThreadItem            var retried: ChatActAnswer            /// A vote where the chat does not send: refused in the core's words.            var refused: Refusal        }        /// Making a poll: the plus with Poll alone, a poll's send, and a refusal.        var poll: PollFixture?        /// Editing and deleting his own message, and Delete for me.        var changes: ChangesFixture?        struct PollFixture: Decodable {            /// Tara's writing box on a server whose outbox takes a poll but no file: the plus with Poll alone.            var alone: ChatComposeAnswer            /// `chat.act poll`: the poll's card, "Waiting to send".            var send: ChatActAnswer            /// One option given twice: "A poll needs at least two options."            var refused: Refusal        }        struct ChangesFixture: Decodable {            /// The message edited, the one deleted for everyone, and hers deleted for him only.            var edited: String            var deleted: String            var deletedMine: String            /// Tara's chat with the three standing, each offering what the core says.            var page: ChatThreadAnswer            /// `chat.compose { edit }`: the edit strip, the message's words in the field; and as the words change.            var editCompose: ChatComposeAnswer            var editTyping: ChatComposeAnswer            /// `chat.act edit`: the new words at once, "Edit waiting to send".            var edit: ChatActAnswer            var editCancelled: ChatComposeAnswer            /// The edit the Mac could not send ("Edit not sent: <why>", Retry), and its retry.            var editFailed: ChatThreadItem            var editRetried: ChatActAnswer            /// The edit past WhatsApp's 15 minutes.            var tooLate: Refusal            /// `chat.act delete`: the marker in its place, "You deleted this message", "Waiting to delete for everyone".            var delete: ChatActAnswer            var deleteFailed: ChatThreadItem            var deleteRetried: ChatActAnswer            /// The delete for everyone past 48 hours.            var tooLateDelete: Refusal            /// `chat.act deleteMine`: his copy only.            var deleteMine: ChatActAnswer        }        /// Three pictures with words, one grid (FEEDBACK-4 B3): the send's pending grid, and the grid once they landed.        var grid: GridFixture?        struct GridFixture: Decodable {            /// `chat.act send` of three pictures with words: one pending grid, each tile naming its row.            var send: ChatActAnswer            /// The grid as `chat.thread` draws it once the Mac sent each and they landed: each tile naming its message.            var landed: ChatBubble        }        struct DocumentFixture: Decodable {            /// `chat.act send` of a document: the pending file bubble, "Waiting to send".            var send: ChatActAnswer            /// Over WhatsApp's 100 MB: refused before anything is kept.            var tooLarge: Refusal            /// On a server whose outbox has no `file_name` yet: refused in words.            var notYet: Refusal        }        struct Refusal: Decodable {            var code: String            var message: String        }    }    /// Writing to a number on the copy linked through the invented Mac: what `chat.start` answered for each number,    /// the row `chat.act read` answers for each chat it opened, and the linked copy's list.    struct RouteFixture: Decodable {        var starts: [String: JSONValue]        var rows: [String: ChatListRow?]        var list: ChatListAnswer        /// The start answered for a number however it was written ("+1 555 010 7101").        func start(_ number: String) -> JSONValue? {            let digits = number.filter(\.isNumber)            return starts.first { $0.key.filter(\.isNumber) == digits }?.value        }    }    /// The invented people's names and the media's words (Resources/Fixtures/chat-warm-seed.json), kept out of    /// the code as the chats themselves are.    private static let words: [String: String] = {        guard let url = Bundle.module.url(forResource: "chat-warm-seed", withExtension: "json", subdirectory: "Fixtures"),              let data = try? Data(contentsOf: url),              let read = try? JSONDecoder().decode([String: String].self, from: data) else { return [:] }        return read    }()    static func invented(_ key: String) -> String { words[key] ?? key }    static func load() -> Fixture? {        guard let url = Bundle.module.url(forResource: "chat-warm", withExtension: "json", subdirectory: "Fixtures"),              let data = try? Data(contentsOf: url) else { return nil }        // Decoded on a thread of its own with a deep stack: a debug build's frames for the fixture's many nested answers        // overflow the 512 KB of a task's thread (the first reader is often a launch task), and the app dies on launch.        final class Decoded: @unchecked Sendable { var fixture: Fixture? }        let decoded = Decoded()        let done = DispatchSemaphore(value: 0)        let thread = Thread {            decoded.fixture = try? JSONDecoder().decode(Fixture.self, from: data)            done.signal()        }        thread.stackSize = 64 << 20        thread.start()        done.wait()        return decoded.fixture    }}private final class ChatWarmObserver: @unchecked Sendable {    let token: any NSObjectProtocol    init(_ token: any NSObjectProtocol) { self.token = token }}/// Mark as unread and opening in Comms Dev's seed, for the launch: a thread/// marked is unread (and offers Mark as read), one opened is read.final class ChatWarmMarks: @unchecked Sendable {    private let lock = NSLock()    private var held: [String: Bool] = [:]    /// Chats deleted this launch: gone from every list, as the core's `cleared_before` keeps them.    private var deleted: Set<String> = []    func delete(_ thread: String) {        lock.lock(); defer { lock.unlock() }        deleted.insert(thread)    }    /// Chats archived this launch: off every list but Archived, as the core keeps them.    private var archived: Set<String> = []    func archive(_ thread: String, _ on: Bool) {        lock.lock(); defer { lock.unlock() }        if on { archived.insert(thread) } else { archived.remove(thread) }    }    func kept(_ rows: [ChatListRow], archivedList: Bool = false) -> [ChatListRow] {        lock.lock(); defer { lock.unlock() }        return rows.filter { !deleted.contains($0.thread) && (archivedList || !archived.contains($0.thread)) }    }    func set(_ thread: String, unread: Bool) {        lock.lock(); defer { lock.unlock() }        held[thread] = unread    }    func applied(_ row: ChatListRow) -> ChatListRow {        lock.lock(); defer { lock.unlock() }        guard let unread = held[row.thread] else { return row }        var row = row        if unread { row.markedUnread = true } else { row.unread = 0; row.markedUnread = false }        let now = row.unread > 0 || row.markedUnread        let act = now ? "read" : "unread"        let turned = { (swipe: ChatSwipe, words: String) -> ChatSwipe in            swipe.act == "read" || swipe.act == "unread" ? ChatSwipe(act: act, label: ShellLines.line("chat", "app.\(words).\(act)"), confirm: nil) : swipe        }        row.leading = row.leading.map { turned($0, "swipe") }        row.hold = row.hold.map { turned($0, "hold") }        return row    }}/// The invented chats as a book: what the core answered, held; acts answer ok and change nothing but a thread's unread mark.final class ChatWarmSeedBook: ChatBook, @unchecked Sendable {    private let fixture: ChatWarmSeed.Fixture    private let long: Int    private let page = 60    init?(long: Int) {        guard let fixture = ChatWarmSeed.load() else { return nil }        self.fixture = fixture        self.long = long        // His vote the Mac could not send, standing as the core then answers the poll.        if ChatWarmSeed.waVote == "failed" { votedPoll = fixture.whatsapp.vote?.failed.bubble }        // The edit and the delete for everyone the Mac could not send, standing as the core then answers them.        if ChatWarmSeed.waChanges == "failed", let c = fixture.whatsapp.changes {            changed[c.edited] = c.editFailed.bubble            changed[c.deleted] = c.deleteFailed.bubble        }    }    /// Tara's chat with his own messages to edit and delete, when asked (`-chat-warm-wa-changes`).    private func changesPage(_ thread: String) -> ChatThreadAnswer? {        guard ChatWarmSeed.waChanges != nil, let c = fixture.whatsapp.changes, c.page.thread == thread else { return nil }        return c.page    }    var photosByKey: Bool { true }    func list(_ ask: ChatListAsk) async throws -> ChatListAnswer {        var answer: ChatListAnswer        switch ask.filter {        case "unread": answer = fixture.unread        case "groups": answer = fixture.groups        case "archived": answer = fixture.archived        default:            if ChatWarmSeed.fresh, let fresh = fixture.fresh { return fresh }            answer = ChatWarmSeed.linked ? fixture.route?.list ?? fixture.list : fixture.list        }        // Mark as unread and opening, held for the launch as the core holds a thread's mark.        answer.rows = answer.rows.map(marks.applied)        if ask.filter == "unread" {            answer.rows = fixture.list.rows.map(marks.applied).filter { $0.unread > 0 || $0.markedUnread }        }        if long > 0, ask.filter == nil || ask.filter == "all", var row = fixture.list.rows.first {            row.thread = ChatWarmSeed.longThread            row.unread = 0            row.markedUnread = false            row.pinned = false            answer.rows.insert(row, at: 0)        }        if let search = ask.search?.trimmingCharacters(in: .whitespaces), !search.isEmpty {            // Words the core was asked over these chats: its own answer, the messages' words as well as the names.            if let found = fixture.searches?.first(where: { $0.key.caseInsensitiveCompare(search) == .orderedSame })?.value {                answer.rows = found.rows.map(marks.applied)            } else {                answer.rows = answer.rows.filter { $0.name.localizedCaseInsensitiveContains(search) }            }            answer.search = search        }        answer.rows = marks.kept(answer.rows, archivedList: ask.filter == "archived")        return answer    }    func thread(_ ask: ChatThreadAsk) async throws -> ChatThreadAnswer {        guard ask.thread == ChatWarmSeed.longThread,              let template = fixture.threads.values.filter({ !$0.header.group }).max(by: { $0.items.count < $1.items.count }) else {            guard var answer = votePage(ask.thread) ?? changesPage(ask.thread) ?? fixture.threads[ask.thread] else { throw CancellationError() }            if ask.thread == ChatWarmSeed.mediaThread { answer.items += Self.media(after: answer.items) }            if let words = wordsOnly(ask.thread) { answer.composer = words }            // Opened around a message (a quote tapped): the core's page stands on it.            if let around = ask.around { answer.focus = around }            // Deleted while he looks: until the deletes land, the chat as it stood before them.            if ChatWarmSeed.revoke != nil, !ChatWarmSeed.revoked.on, let revoke = fixture.revoke, revoke.thread == ask.thread {                answer = revoke.before            }            // A vote arrived: the poll as the core then answers it.            if ChatWarmSeed.voted.on, let votes = fixture.votes, votes.thread == ask.thread {                answer.items = answer.items.map { $0.bubble?.message == votes.bubble.message ? .bubble(votes.bubble) : $0 }            }            // Invented people are on no server: only Ravi's chat shows "Not on Cotton yet".            if ask.thread != ChatWarmSeed.notYetThread, answer.reach?.state == "notYet" { answer.reach?.state = "on" }            // A timer chosen here: the chat's timer and header as the core then answered them, and its lines at the foot.            if let timed = sentLock.withLock({ timed[ask.thread] }) {                answer.timer = timed.timer                answer.header = timed.header                answer.items += timed.lines            }            let (going, again, kept) = sentLock.withLock { (waiting[ask.thread] ?? [], retried, (sentIn[ask.thread] ?? []).map { sentBubbles[$0.message] ?? $0 }) }            // What was sent here stands at the foot of the chat, as the core's newest page holds it.            answer.items = answer.items.map { item in item.bubble.flatMap { again[$0.message] }.map { ChatThreadItem.bubble($0) } ?? item }                + kept.map { ChatThreadItem.bubble($0) } + going.map { ChatThreadItem.bubble($0) }            // His vote on her poll, as the core then answers the poll.            if let poll = sentLock.withLock({ votedPoll }) {                answer.items = answer.items.map { $0.bubble?.message == poll.message ? .bubble(poll) : $0 }            }            // His messages edited or deleted here, as the core then answers them (a deleted one's marker in its place);            // one deleted for him only is gone.            let (swapped, removed) = sentLock.withLock { (changed, gone) }            answer.items = answer.items.compactMap { item in                guard let bubble = item.bubble else { return item }                if removed.contains(bubble.message) { return nil }                return swapped[bubble.message].map { ChatThreadItem.bubble($0) } ?? item            }            answer.items = await withPreviews(answer.items)            answer.items = answer.items.map { item in item.bubble.map { ChatThreadItem.bubble(playedApplied($0)) } ?? item }            return answer        }        // The long chat: pages of the core's size, its bubbles the template's in turn.        let bubbles = template.items.compactMap { item -> ChatBubble? in            if case .bubble(let bubble) = item, bubble.tick != .failed { return bubble }            return nil        }        guard !bubbles.isEmpty else { return template }        var hi = long, lo = max(0, long - 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(long, after + page) }        var answer = template        answer.thread = ask.thread        answer.items = (lo..<hi).map { n in            var bubble = bubbles[n % bubbles.count]            bubble.message = "long-\(n)"            bubble.reply = nil            // The newest is a picture of theirs with its caption (the owner saw a picture tile behind the writing box).            if n == long - 1 || (ChatWarmSeed.longPictures && n % 3 == 0) {                bubble.mine = n == long - 1 ? false : n % 2 == 0                bubble.kind = .photo                bubble.text = ChatWarmSeed.invented("photo")                bubble.link = nil                bubble.media = [ChatMediaPart(index: 0, kind: .photo, name: nil, width: 480, height: 360, length: nil, size: nil,                                              waveform: nil, preview: nil, contact: nil, number: nil)]            }            return .bubble(bubble)        }        answer.older = lo > 0 ? String(lo) : nil        answer.newer = hi < long ? String(hi) : nil        answer.focus = nil        answer.unread = 0        answer.jump = nil        // Invented people are on no server: the long chat is someone on Cotton, as every chat but Ravi's.        if answer.reach?.state == "notYet" { answer.reach?.state = "on" }        answer.items = await withPreviews(answer.items)        return answer    }    /// Tara's writing box as a server whose outbox takes no file yet answers it, when asked (`-chat-warm-wa-words-only`).    /// Tara's chat with her poll he can vote on, when asked (`-chat-warm-wa-vote`).    private func votePage(_ thread: String) -> ChatThreadAnswer? {        guard ChatWarmSeed.waVote != nil, let vote = fixture.whatsapp.vote, vote.page.thread == thread else { return nil }        return vote.page    }    /// His tap on an option of her poll, and its retry, as the core answers them; refused in its words when asked.    private func voted(_ ask: ChatActAsk) throws -> ChatActAnswer? {        guard let vote = fixture.whatsapp.vote, vote.page.thread == ask.thread, ask.message == vote.message else { return nil }        switch ask.act {        case "vote":            if ChatWarmSeed.waVote == "refuse" { throw CottonCallError(code: vote.refused.code, message: vote.refused.message) }            // Only the tap the fixture asked the core of has its answer; another option changes nothing here.            guard ask.option == vote.option else { return ChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: ask.message, bubble: nil, row: nil, sentTo: nil, flush: false, said: nil) }            sentLock.withLock { votedPoll = vote.vote.bubble }            return vote.vote        case "retry":            sentLock.withLock { votedPoll = vote.retried.bubble }            return vote.retried        default:            return nil        }    }    private func wordsOnly(_ thread: String) -> ChatComposeAnswer? {        if ChatWarmSeed.waPoll == "alone", let alone = fixture.whatsapp.poll?.alone, alone.thread == thread { return alone }        guard ChatWarmSeed.waWordsOnly, let words = fixture.whatsapp.wordsOnly, words.thread == thread else { return nil }        return words    }    /// The edit strip, as the core answers it while he edits his message (`chat.compose { edit }`), or nil.    private func editing(_ ask: ChatComposeAsk) -> ChatComposeAnswer? {        guard let c = fixture.whatsapp.changes, c.page.thread == ask.thread else { return nil }        if ask.cancel == true { return nil }        guard let message = ask.edit, message == c.edited else { return nil }        guard let text = ask.text else { return c.editCompose }        var typing = c.editTyping        typing.text = text        typing.sendEnabled = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty        typing.button = typing.sendEnabled ? .send : .idle        return typing    }    func compose(_ ask: ChatComposeAsk) async throws -> ChatComposeAnswer {        if let edit = editing(ask) { return edit }        guard var composer = wordsOnly(ask.thread) ?? fixture.threads[ask.thread]?.composer ?? fixture.threads.values.compactMap(\.composer).first else { throw CancellationError() }        // The reply strip, as the core keeps it on the chat until it is cancelled or sent (draft_reply_to_id).        let strip = sentLock.withLock { () -> ChatStrip? in            if ask.cancel == true { replying[ask.thread] = nil }            if let message = ask.replyTo, let strip = fixture.replies?[ask.thread]?[message]?.composer.strip { replying[ask.thread] = strip }            return replying[ask.thread]        }        composer.strip = strip        // As the core's send rule answers (compose::answer): something written, or pictures waiting, is Send, in the core's own word.        guard let text = ask.text else { return composer }        // A link written offers its card, as the core answered these words (none with the setting off).        if let offered = ChatWarmLinks.composer(ask.thread, text) { composer.preview = offered.preview }        composer.text = text        if !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || (ask.attached ?? 0) > 0 {            composer.button = .send            composer.buttonLabel = ShellLines.line("chat", "app.compose.send")            composer.sendEnabled = true        }        return composer    }    private let sentLock = NSLock()    private var sent = 0    /// What was sent in each chat (not over a slow line), standing at its foot when the chat is read again.    private var sentIn: [String: [ChatBubble]] = [:]    /// The reply strip standing on each chat, until cancelled or sent.    private var replying: [String: ChatStrip] = [:]    /// What Send answered, by message, for the acts that follow it (a voice message's words).    private var sentBubbles: [String: ChatBubble] = [:]    /// Disappearing messages chosen in each chat: the core's timer and header after the last choice, and every line.    private var timed: [String: (timer: ChatTimerCard?, header: ChatHeader, lines: [ChatThreadItem])] = [:]    /// A length chosen: what the core answered for it in this chat, its line kept at the foot under a name of its own    /// (a length chosen twice stands twice, as the core's lines do). A length the fixture holds no answer for changes nothing.    private func timer(_ ask: ChatActAsk) -> ChatActAnswer? {        guard ask.act == "timer", let seconds = ask.seconds, let held = fixture.timers?[ask.thread],              let chosen = held[String(seconds)], let header = chosen.header else { return nil }        sentLock.withLock {            var now = timed[ask.thread] ?? (nil, header, [])            if now.lines.isEmpty, let day = held["day"]?.day { now.lines.append(day) }            let n = now.lines.count            now.lines += (chosen.lines ?? []).map { line in                guard case .event(let message, let text, let call, let opens, let groupCall) = line else { return line }                return .event(message: "\(message)-\(n)", text: text, call: call, opens: opens, groupCall: groupCall)            }            now.timer = chosen.timer            now.header = header            timed[ask.thread] = now        }        return chosen.act    }    /// Acts answer ok and change nothing; Send answers the person's own new bubble, as the core draws it at once    /// from what was written (and the pictures it carries), so what lands can be seen.    func act(_ ask: ChatActAsk) async throws -> ChatActAnswer {        if ask.act == "unread" || ask.act == "read" { marks.set(ask.thread, unread: ask.act == "unread") }        if ask.act == "archive" || ask.act == "unarchive" { marks.archive(ask.thread, ask.act == "archive") }        // Deleted: off the list and kept off, with the core's words (`app.said.chat_deleted`).        if ask.act == "deleteChat" {            marks.delete(ask.thread)            return ChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: nil, bubble: nil, row: nil, sentTo: nil, flush: false,                                 said: ShellLines.line("chat", "app.said.chat_deleted"))        }        // A chat started by number holds nothing yet, so it is in no list: its row is the one the core's read answers.        if ask.act == "read", let row = fixture.route?.rows[ask.thread] ?? fixture.rows?[ask.thread] {            return ChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: nil, bubble: nil, row: row, sentTo: nil, flush: false, said: nil)        }        // A voice message's words, kept on it as the core keeps them (meta.cotton.transcript), once only.        if ask.act == "transcript", let message = ask.message, let words = ask.text {            let bubble = sentLock.withLock { () -> ChatBubble? in                guard var bubble = sentBubbles[message], bubble.kind == .voice, bubble.media.first?.transcript == nil else { return nil }                bubble.media[0].transcript = words                sentBubbles[message] = bubble                return bubble            }            return ChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: message, bubble: bubble, row: nil, sentTo: nil, flush: false, said: nil)        }        if let answer = timer(ask) { return answer }        // A note of theirs played a second: played on the person's own copy, never told to the sender.        if ask.act == "played", let message = ask.message {            sentLock.withLock { _ = played.insert(message) }            let bubble = fixtureBubble(message).map(playedApplied)            return ChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: message, bubble: bubble, row: nil, sentTo: nil, flush: false, said: nil)        }        if let answer = try voted(ask) { return answer }        if let answer = try whatsAppChange(ask) { return answer }        if let answer = try whatsApp(ask) { return answer }        guard ask.act == "send", let bubble = sentBubble(ask) else {            return ChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: ask.message, bubble: nil, row: nil, sentTo: nil, flush: false, said: nil)        }        // With a slow line asked for (-chat-warm-send-picture), the send goes as the core's does: quiet for two        // seconds, its pictures the phone's own files, then sent once the upload is over (flush).        guard ChatWarmSeed.sendPicture != nil else {            sentLock.withLock { sentIn[ask.thread, default: []].append(bubble) }            return ChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: bubble.message, bubble: bubble, row: nil, sentTo: nil, flush: false, said: nil)        }        var going = bubble        going.quietUntil = (Date().timeIntervalSince1970 + 2) * 1_000        sentLock.withLock { outbox[going.message] = (ask.thread, going, (ask.attachments ?? []).map(\.path)) }        return ChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: going.message, bubble: going, row: nil, sentTo: nil, flush: true, said: nil)    }    /// A WhatsApp chat's send and retry, as the core answers them: the text waits for the Mac (no flush); Retry is    /// offered on the failed one, and a text still waiting is refused in the core's words. A picture, a video or a voice    /// note is its own pending bubble from the phone's own copy, as the core answers each kind; a file over 16 MB is    /// refused when asked (`-chat-warm-wa-refuse`).    private func whatsApp(_ ask: ChatActAsk) throws -> ChatActAnswer? {        guard let page = fixture.threads[ask.thread], page.header.source == "whatsapp" || page.header.place?.id == "whatsapp" else { return nil }        let wa = fixture.whatsapp        switch ask.act {        case "send":            let files = ask.attachments ?? []            if !files.isEmpty, ChatWarmSeed.waRefuse, let refused = wa.tooLarge { throw CottonCallError(code: refused.code, message: refused.message) }            if let document = files.first(where: { $0.kind == "file" }), let doc = wa.document {                if ChatWarmSeed.waNoDocuments { throw CottonCallError(code: doc.notYet.code, message: doc.notYet.message) }                let bytes = (try? FileManager.default.attributesOfItem(atPath: document.path)[.size] as? NSNumber)?.int64Value ?? 0                if bytes > 100 << 20 { throw CottonCallError(code: doc.tooLarge.code, message: doc.tooLarge.message) }                return documentSent(ask, document, doc.send)            }            let n = sentLock.withLock { sent += 1; return sent }            if let grid = gridSent(ask, files, n) { return grid }            let first = files.first            var answer = (first?.kind == "voice" ? wa.voice : first?.kind == "video" ? wa.video : first == nil ? nil : wa.picture) ?? wa.send            answer.thread = ask.thread            answer.message = "\(ChatThreadModel.pending)seed-sent-\(n)"            answer.bubble?.message = answer.message ?? ""            // A voice note carries no words; a picture's or a video's are its caption.            answer.bubble?.text = first?.kind == "voice" ? nil : ask.text            if let first, var part = answer.bubble?.media.first {                // Drawn at once from the phone's own copy: the file just picked, its own shape and preview.                part.width = first.width ?? part.width                part.height = first.height ?? part.height                part.preview = first.preview ?? part.preview                if let ms = first.durationMs {                    part.durationMs = Int(ms)                    part.length = Duration.milliseconds(Int64(ms)).formatted(.time(pattern: .minuteSecond))                }                if let wave = first.waveform { part.waveform = wave; part.bars = ChatWarmSeed.bars(wave) }                answer.bubble?.media = [part]            }            // Still on its way when the chat is asked again, as the core keeps it.            if let bubble = answer.bubble { sentLock.withLock { waiting[ask.thread, default: []].append(bubble) } }            return answer        case "retry":            guard let message = ask.message, message.hasPrefix(ChatThreadModel.pending) else { return nil }            let held = page.items.lazy.compactMap(\.bubble).first { $0.message == message }            guard held?.actions.first == "retry" else { throw CottonCallError(code: wa.refused.code, message: wa.refused.message) }            let picture = held.map { [.photo, .video, .album].contains($0.kind) } ?? false            var answer = (picture ? wa.retryPicture : nil) ?? wa.retry            answer.thread = ask.thread            answer.message = message            answer.bubble?.message = message            answer.bubble?.text = held?.text            if picture, let media = held?.media { answer.bubble?.media = media }            if let bubble = answer.bubble { sentLock.withLock { retried[message] = bubble } }            return answer        default:            return nil        }    }    /// Several pictures or videos of one tap, as the core answers them (FEEDBACK-4 B3): one pending grid headed by the    /// words, each tile naming its own row (`outbox:<row>`, index 0) and drawn at once from the file just picked.    /// With `-chat-warm-wa-land`, they land later as the fixture's landed grid, each tile naming its message.    private func gridSent(_ ask: ChatActAsk, _ files: [ChatAttachment], _ n: Int) -> ChatActAnswer? {        guard files.count > 1, files.allSatisfy({ $0.kind == "photo" || $0.kind == "video" }), let fixed = fixture.whatsapp.grid,              var bubble = fixed.send.bubble, let template = bubble.media.first else { return nil }        let head = "\(ChatThreadModel.pending)seed-sent-\(n)"        bubble.message = head        bubble.text = ask.text        bubble.media = files.enumerated().map { i, file in            var part = template            part.index = 0            part.kind = ChatMark(rawValue: file.kind ?? "photo") ?? .photo            part.width = file.width ?? part.width            part.height = file.height ?? part.height            part.preview = file.preview ?? part.preview            part.message = i == 0 ? head : "\(head)-\(i)"            return part        }        var answer = fixed.send        answer.thread = ask.thread        answer.message = head        answer.bubble = bubble        sentLock.withLock {            for (part, file) in zip(bubble.media, files) { if let message = part.message { pickedFiles[message] = file.path } }            waiting[ask.thread, default: []].append(bubble)        }        if let delay = ChatWarmSeed.waLand { land(bubble, thread: ask.thread, n: n, after: delay, files: files.map(\.path)) }        return answer    }    /// The grid sent here lands: its rows leave and the landed grid stands in their place, its messages named for this    /// send, each picture still the file picked (his own media's copy, kept at the tap); the open chat is told so.    private func land(_ pending: ChatBubble, thread: String, n: Int, after delay: Double, files: [String]) {        guard var landed = fixture.whatsapp.grid?.landed else { return }        let head = "seed-landed-\(n)"        landed.message = head        landed.text = pending.text        let template = landed.media.first        landed.media = pending.media.enumerated().map { i, part in            var tile = template ?? part            tile.index = 0            tile.kind = part.kind            tile.width = part.width            tile.height = part.height            tile.preview = part.preview            tile.message = i == 0 ? nil : "\(head)-\(i)"            return tile        }        let grid = landed        Task { [weak self] in            try? await Task.sleep(for: .seconds(delay))            guard let self else { return }            let told = self.sentLock.withLock { () -> [AsyncStream<ChatChange>.Continuation] in                self.waiting[thread]?.removeAll { $0.message == pending.message }                for (tile, file) in zip(grid.media, files) { self.pickedFiles[tile.opens(in: grid)] = file }                self.sentIn[thread, default: []].append(grid)                return self.listeners            }            for listener in told { listener.yield(.arrived(thread: thread)) }        }    }    /// The pictures picked and sent here as a grid, by the message each tile opens through: the files just picked.    private var pickedFiles: [String: String] = [:]    /// A document sent to WhatsApp, as the core answers it: the words, if any, go first as their own text, and the    /// send answers that first one; the document is its own pending file bubble under the picked name. Both wait.    private func documentSent(_ ask: ChatActAsk, _ document: ChatAttachment, _ sent: ChatActAnswer) -> ChatActAnswer {        let wa = fixture.whatsapp        var answers: [ChatActAnswer] = []        if let words = ask.text, !words.isEmpty {            var text = wa.send            text.bubble?.text = words            answers.append(text)        }        var file = sent        file.bubble?.text = nil        if var part = file.bubble?.media.first {            part.name = document.name ?? part.name            file.bubble?.media = [part]        }        answers.append(file)        answers = answers.map { one in            var one = one            let n = sentLock.withLock { self.sent += 1; return self.sent }            one.thread = ask.thread            one.message = "\(ChatThreadModel.pending)seed-sent-\(n)"            one.bubble?.message = one.message ?? ""            if let bubble = one.bubble { sentLock.withLock { waiting[ask.thread, default: []].append(bubble) } }            return one        }        return answers[0]    }    /// His vote on her poll here: the poll as the core then answered it.    private var votedPoll: ChatBubble?    /// His messages edited or deleted for everyone here, by message: the bubble the core then answers (a marker's    /// for a delete).    private var changed: [String: ChatBubble] = [:]    /// Messages deleted for him only here.    private var gone: Set<String> = []    /// Making a poll, editing and deleting his own message, and Delete for me, as the core answers each in Tara's chat;    /// past WhatsApp's windows (`-chat-warm-wa-late`), refused in its words.    private func whatsAppChange(_ ask: ChatActAsk) throws -> ChatActAnswer? {        let wa = fixture.whatsapp        if ask.act == "poll", let poll = wa.poll {            if ChatWarmSeed.waPoll == "refuse" { throw CottonCallError(code: poll.refused.code, message: poll.refused.message) }            var answer = poll.send            let n = sentLock.withLock { sent += 1; return sent }            answer.thread = ask.thread            answer.message = "\(ChatThreadModel.pending)seed-sent-\(n)"            answer.bubble?.message = answer.message ?? ""            if let bubble = answer.bubble { sentLock.withLock { waiting[ask.thread, default: []].append(bubble) } }            return answer        }        guard let c = wa.changes, c.page.thread == ask.thread, let message = ask.message else { return nil }        switch ask.act {        case "edit" where message == c.edited:            if ChatWarmSeed.waLate { throw CottonCallError(code: c.tooLate.code, message: c.tooLate.message) }            if let bubble = c.edit.bubble { sentLock.withLock { changed[message] = bubble } }            return c.edit        case "delete" where message == c.deleted:            if ChatWarmSeed.waLate { throw CottonCallError(code: c.tooLateDelete.code, message: c.tooLateDelete.message) }            if let bubble = c.delete.bubble { sentLock.withLock { changed[message] = bubble } }            return c.delete        case "deleteMine" where message == c.deletedMine:            sentLock.withLock { _ = gone.insert(message) }            return c.deleteMine        case "retry" where message == c.edited:            if let bubble = c.editRetried.bubble { sentLock.withLock { changed[message] = bubble } }            return c.editRetried        case "retry" where message == c.delete.message:            if let bubble = c.deleteRetried.bubble { sentLock.withLock { changed[c.deleted] = bubble } }            return c.deleteRetried        default:            return nil        }    }    /// The WhatsApp texts sent here, by chat: they wait for a Mac the seed has none of.    private var waiting: [String: [ChatBubble]] = [:]    /// The failed texts tried again here, by message: waiting again.    private var retried: [String: ChatBubble] = [:]    /// The sends over a slow line, by message: their chat, their bubble, their files on the phone.    private var outbox: [String: (thread: String, bubble: ChatBubble, paths: [String])] = [:]    private var listeners: [AsyncStream<ChatChange>.Continuation] = []    /// A picture still going up is the phone's own file, as the core answers it (`chat.picture`).    func findPicture(message: String, index: Int) async -> ChatPictureFound {        if let paths = sentLock.withLock({ outbox[message]?.paths }), paths.indices.contains(index) { return .file(URL(fileURLWithPath: paths[index])) }        // A grid's tile, waiting or landed: the file just picked, by the message it opens through (FEEDBACK-4 B3).        if index == 0, let path = sentLock.withLock({ pickedFiles[message] }) { return .file(URL(fileURLWithPath: path)) }        if let wait = ChatWarmSeed.pictureWait { try? await Task.sleep(for: .seconds(wait)) }        if ChatWarmSeed.freed.on || ChatWarmStorage.freedHere(message) { try? await Task.sleep(for: .seconds(30)) }        if let url = await picture(media: nil, message: message, index: index) { return .file(url) }        return .notYet    }    /// The invented pictures' previews, as their senders' phones made them (`ChatPreviewMaker`), by message.    private var previews: [String: String] = [:]    /// Each picture of `items` carries its preview, as a message from a phone that makes them does.    func withPreviews(_ items: [ChatThreadItem]) async -> [ChatThreadItem] {        var out: [ChatThreadItem] = []        for item in items {            guard case .bubble(var bubble) = item, bubble.media.contains(where: { ($0.kind == .photo || $0.kind == .album) && $0.preview == nil }),                  !ChatWarmSeed.gonePictures.contains(bubble.message) else { out.append(item); continue }            var made = sentLock.withLock { previews[bubble.message] }            if made == nil, let url = await picture(media: nil, message: bubble.message, index: 0) {                made = ChatPreviewMaker.make(url)                sentLock.withLock { previews[bubble.message] = made }            }            bubble.media = bubble.media.map { part in                var part = part                if part.kind == .photo, part.preview == nil { part.preview = made }                return part            }            out.append(.bubble(bubble))        }        return out    }    private func sentBubble(_ ask: ChatActAsk) -> ChatBubble? {        let template = fixture.threads[ask.thread] ?? fixture.threads.values.filter { !$0.header.group }.max { $0.items.count < $1.items.count }        let bubbles = (template?.items ?? []).compactMap { item -> ChatBubble? in            if case .bubble(let bubble) = item { return bubble }            return nil        }        guard var bubble = bubbles.last(where: \.mine) ?? bubbles.last else { return nil }        let n = sentLock.withLock { sent += 1; return sent }        let attachments = ask.attachments ?? []        bubble.message = "seed-sent-\(n)"        bubble.mine = true        bubble.text = ask.text        bubble.media = attachments.enumerated().map { i, a in            // A voice message's length and bars, as the core draws them from the attachment.            let length = a.durationMs.map { Duration.milliseconds(Int64($0)).formatted(.time(pattern: .minuteSecond)) }            return ChatMediaPart(index: i, kind: ChatMark(rawValue: a.kind ?? "file") ?? .file, name: nil, width: a.width, height: a.height,                                 length: length, size: nil, waveform: a.waveform, preview: a.preview, contact: nil, number: nil,                                 durationMs: a.durationMs.map { Int($0) }, bars: a.waveform.flatMap(ChatWarmSeed.bars))        }        bubble.kind = attachments.count > 1 ? .album : attachments.first.flatMap { ChatBubbleKind(rawValue: $0.kind ?? "file") } ?? .text        bubble.sender = nil        // A reply quotes what it answers, as the core's send answers it; its strip goes with the send.        bubble.reply = ask.replyTo.flatMap { fixture.replies?[ask.thread]?[$0]?.quote }        sentLock.withLock { replying[ask.thread] = nil }        // The card fetched here goes with its link, as the core keeps it (meta.preview).        bubble.link = ChatWarmLinks.link(ask)        bubble.reactions = []        bubble.edited = nil        bubble.forwarded = nil        bubble.pinned = false        bubble.head = true        bubble.tail = true        bubble.tick = .sending        sentLock.withLock { sentBubbles[bubble.message] = bubble }        if let voice = attachments.first(where: { $0.kind == "voice" }) { sentLock.withLock { sentVoices[bubble.message] = voice.path } }        return bubble    }    /// The voice messages sent here, by message: their own recorded files.    private var sentVoices: [String: String] = [:]    private let marks = ChatWarmMarks()    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() }    /// Invented calls, in the core's words.    func calls(after: String?) async throws -> ChatCallsAnswer {        func w(_ key: String, _ args: [String: String] = [:]) -> String { ShellLines.line("chat", key, args) }        func row(_ id: String, _ name: String, _ initials: String, _ tint: Int, incoming: Bool, video: Bool, missed: Bool, line: String, when: String) -> ChatCallRow {            ChatCallRow(call: id, name: name, picture: ChatAvatar(photo: nil, initials: initials, tint: tint), thread: nil,                        incoming: incoming, video: video, missed: missed, group: false, line: line, when: when)        }        let voice = w("app.call.kind.voice"), video = w("app.call.kind.video")        let rows = [            row("c1", ChatWarmSeed.invented("asha"), "AV", 3, incoming: true, video: false, missed: true, line: w("app.call.missed.voice"), when: "10:42 am"),            row("c2", ChatWarmSeed.invented("ravi"), "RM", 1, incoming: false, video: true, missed: false, line: w("app.call.line", ["kind": video, "detail": "12:04"]), when: "Yesterday"),            row("c3", ChatWarmSeed.invented("meera"), "MI", 5, incoming: true, video: false, missed: false, line: w("app.call.line", ["kind": voice, "detail": "3:27"]), when: "Thursday"),            row("c4", ChatWarmSeed.invented("ravi"), "RM", 1, incoming: false, video: false, missed: false, line: w("app.call.line", ["kind": voice, "detail": w("app.call.why.no_answer")]), when: "Tuesday"),        ]        return ChatWarmRecordings.calls(ChatCallsAnswer(rows: rows, next: nil,                                                        words: ChatCallsWords(title: w("app.calls.title"), empty: w("app.calls.empty"), back: w("app.call.back"))))    }    /// The upload over a slow line (`-chat-warm-send-picture <seconds>`), then the bubble sent, as the core's change says.    func flush() async {        let going = sentLock.withLock { outbox.filter { $0.value.bubble.tick == .sending } }        guard !going.isEmpty else { return }        try? await Task.sleep(for: .seconds(ChatWarmSeed.sendPicture ?? 0))        for (id, entry) in going {            var bubble = entry.bubble            bubble.tick = .sent            bubble.quietUntil = nil            let told = sentLock.withLock { () -> [AsyncStream<ChatChange>.Continuation] in                outbox[id]?.bubble = bubble                return listeners            }            for listener in told { listener.yield(.bubble(thread: entry.thread, bubble)) }        }    }    /// The invented photos: a warm wash drawn once, the same for every photo; none for a gone one.    func picture(media: String?, message: String?, index: Int?) async -> URL? {        if let message, ChatWarmSeed.gonePictures.contains(message) { return nil }        #if canImport(UIKit)        let url = FileManager.default.temporaryDirectory.appendingPathComponent("chat-warm-photo-" + (message ?? "x") + ".png")        if FileManager.default.fileExists(atPath: url.path) { return url }        let tones: [(CGFloat, CGFloat, CGFloat)] = [(0.86, 0.6, 0.45), (0.45, 0.6, 0.55), (0.55, 0.5, 0.7)]        let tone = tones[abs((message ?? "").hashValue) % tones.count]        let image = UIGraphicsImageRenderer(size: CGSize(width: 480, height: 360)).image { context in            let colours = [UIColor(red: tone.0, green: tone.1, blue: tone.2, alpha: 1).cgColor, UIColor(red: tone.0 * 0.5, green: tone.1 * 0.5, blue: tone.2 * 0.5, alpha: 1).cgColor]            let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colours as CFArray, locations: [0, 1])!            context.cgContext.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 480, y: 360), options: [])        }        try? image.pngData()?.write(to: url)        return url        #else        return nil        #endif    }    /// A photo with its caption, a voice message and a file, after the chat's own words (Meera's chat).    static func media(after items: [ChatThreadItem]) -> [ChatThreadItem] {        guard let base = items.lazy.compactMap({ item -> ChatBubble? in            if case .bubble(let bubble) = item { return bubble }            return nil        }).last else { return [] }        func made(_ id: String, mine: Bool, kind: ChatBubbleKind, text: String?, part: ChatMediaPart) -> ChatThreadItem {            var bubble = base            bubble.message = id            bubble.mine = mine            bubble.kind = kind            bubble.text = text            bubble.media = [part]            bubble.link = nil            bubble.reply = nil            bubble.reactions = []            bubble.edited = nil            bubble.head = true            bubble.tail = true            bubble.face = true            bubble.tick = mine ? .read : nil            return .bubble(bubble)        }        let wave = (0..<40).map { 0.25 + 0.7 * abs(sin(Double($0) * 0.55)) }        let bars = ChatWarmSeed.bars(wave), reversed = ChatWarmSeed.bars(Array(wave.reversed()))        return [            made("m-media-1", mine: false, kind: .photo, text: ChatWarmSeed.invented("photo"),                 part: ChatMediaPart(index: 0, kind: .photo, name: nil, width: 480, height: 360, length: nil, size: nil, waveform: nil, preview: nil, contact: nil, number: nil)),            made("m-media-2", mine: true, kind: .voice, text: nil,                 part: ChatMediaPart(index: 0, kind: .voice, name: nil, width: nil, height: nil, length: "0:14", size: nil, waveform: wave, preview: nil, contact: nil, number: nil, bars: bars)),            made("m-media-3", mine: false, kind: .file, text: nil,                 part: ChatMediaPart(index: 0, kind: .file, name: ChatWarmSeed.invented("file"), width: nil, height: nil, length: nil, size: "240 KB", waveform: nil, preview: nil, contact: nil, number: nil)),            // Theirs, with the words their phone heard in it under the player.            made("m-media-4", mine: false, kind: .voice, text: nil,                 part: ChatMediaPart(index: 0, kind: .voice, name: nil, width: nil, height: nil, length: "0:03", size: nil, waveform: Array(wave.reversed()), preview: nil, contact: nil, number: nil,                                     transcript: ChatWarmSeed.heardWords, bars: reversed)),        ]    }    /// A voice message's file: the one recorded here, or the invented recording for the seed's own.    func file(message: String, index: Int) async throws -> ChatFileAnswer {        // A document: an invented PDF of the fixture's words, written once, as the core writes the file it fetched.        if let document = fixture.documents?[message], let part = fixtureBubble(message)?.media.first(where: { $0.kind == .file }) {            let name = part.name ?? message            let url = FileManager.default.temporaryDirectory.appendingPathComponent("chat-warm-documents/\(name)")            if !FileManager.default.fileExists(atPath: url.path) {                try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)                let page = CGRect(x: 0, y: 0, width: 612, height: 792)                try UIGraphicsPDFRenderer(bounds: page).writePDF(to: url) { context in                    context.beginPage()                    (document.title as NSString).draw(at: CGPoint(x: 56, y: 64), withAttributes: [.font: UIFont.boldSystemFont(ofSize: 28)])                    for (at, line) in document.lines.enumerated() {                        (line as NSString).draw(at: CGPoint(x: 56, y: 120 + CGFloat(at) * 30), withAttributes: [.font: UIFont.systemFont(ofSize: 17)])                    }                }            }            return ChatFileAnswer(path: url.path, mime: "application/pdf", name: name, kind: "file", kept: nil)        }        if let path = sentLock.withLock({ sentVoices[message] }) {            return ChatFileAnswer(path: path, mime: "audio/mp4", name: nil, kind: "voice", kept: nil)        }        // The voice player's notes (Ravi's chat): one can't be fetched now, in the core's words; the others are        // invented tones of their own lengths.        if let voice = fixture.voice, voice.offline.contains(message) {            try? await Task.sleep(for: .milliseconds(600))            throw CottonCallError(code: "file_offline", message: voice.refusals["file_offline"] ?? "")        }        if let part = fixtureBubble(message)?.media.first(where: { $0.kind == .voice }), let ms = part.durationMs {            // As a file on its way does: the round's arc turns a moment first.            try? await Task.sleep(for: .milliseconds(400))            guard let url = ChatWarmSeed.inventedVoice(message, seconds: Double(ms) / 1_000) else { throw CancellationError() }            return ChatFileAnswer(path: url.path, mime: "audio/mp4", name: nil, kind: "voice", kept: nil)        }        guard Self.voices.contains(message), let made = ChatWarmSeed.recordedVoice() else { throw CancellationError() }        return ChatFileAnswer(path: made.url.path, mime: "audio/mp4", name: nil, kind: "voice", kept: nil)    }    /// A message of the core's answers, by id.    private func fixtureBubble(_ message: String) -> ChatBubble? {        for page in fixture.threads.values {            if let bubble = page.items.lazy.compactMap(\.bubble).first(where: { $0.message == message }) { return bubble }        }        return nil    }    /// The voice speed as the core keeps it (the person's, synced): the fixture's, then as chosen here.    private var speed: Double?    /// Their notes played here, as the core keeps them (meta.cotton.played_at).    private var played: Set<String> = []    func voiceSpeed() async -> Double { sentLock.withLock { speed } ?? fixture.voice?.settings.voiceSpeed ?? 1 }    func linkCard(thread: String, url: String, page: String) async -> ChatLinkCardAnswer? { ChatWarmLinks.card(thread, url, page) }    func setVoiceSpeed(_ speed: Double) async { sentLock.withLock { self.speed = speed } }    /// A bubble with its notes played here drawn played, as the core answers it.    private func playedApplied(_ bubble: ChatBubble) -> ChatBubble {        guard sentLock.withLock({ played.contains(bubble.message) }) else { return bubble }        var bubble = bubble        bubble.media = bubble.media.map { part in            var part = part            if part.kind == .voice { part.played = nil }            return part        }        return bubble    }    /// The seed's own voice messages (Meera's chat).    static let voices: Set<String> = ["m-media-2", "m-media-4"]    /// A chat read here (opened) is said to the list, so it reads its rows again, as the core's book does.    func changes() -> AsyncStream<ChatChange> {        AsyncStream { continuation in            let token = NotificationCenter.default.addObserver(forName: .cottonChatRead, object: nil, queue: nil) { note in                if let thread = note.userInfo?["thread"] as? String { continuation.yield(.read(thread: thread)) }            }            let box = ChatWarmObserver(token)            continuation.onTermination = { _ in NotificationCenter.default.removeObserver(box.token) }            // A send over a slow line is said sent here too.            sentLock.withLock { listeners.append(continuation) }            // WhatsApp's deletes landing, once: the chat's newest page is stale, said to everyone watching then.            if let delay = ChatWarmSeed.revoke, let thread = fixture.revoke?.thread, !ChatWarmSeed.revokeComing.on {                ChatWarmSeed.revokeComing.set()                Task { [weak self] in                    try? await Task.sleep(for: .seconds(delay))                    ChatWarmSeed.revoked.set()                    let told = self?.sentLock.withLock { self?.listeners ?? [] } ?? []                    for listener in told { listener.yield(.arrived(thread: thread)) }                }            }            // A vote arriving, once: its chat's newest page is stale, said to everyone watching then.            if let delay = ChatWarmSeed.vote, let thread = fixture.votes?.thread, !ChatWarmSeed.voteComing.on {                ChatWarmSeed.voteComing.set()                Task { [weak self] in                    try? await Task.sleep(for: .seconds(delay))                    ChatWarmSeed.voted.set()                    let told = self?.sentLock.withLock { self?.listeners ?? [] } ?? []                    for listener in told { listener.yield(.arrived(thread: thread)) }                }            }        }    }}#endif#if os(iOS) && COTTON_DEV/// The core with the invented people's answers in front of it.struct ChatWarmSeedCore: CottonCalling {    let inner: any CottonCalling    static let answers: [String: JSONValue] = {        guard let url = Bundle.module.url(forResource: "chat-warm-people", withExtension: "json", subdirectory: "Fixtures"),              let data = try? Data(contentsOf: url) else { return [:] }        return (try? JSONDecoder().decode([String: JSONValue].self, from: data)) ?? [:]    }()    private static let route = ChatWarmSeed.load()?.route    /// Changes answered ok, changing nothing.    private static let changes: Set<String> = ["chat.profile.set", "chat.block", "chat.unblock", "chat.accept", "chat.refuse",                                               "assistant.scope", "assistant.askEachTime", "assistant.stop", "assistant.remove"]    func callRaw(_ method: String, requestJSON: String) async throws -> String {        if method == ChatWarmSeed.slow { try await Task.sleep(for: .seconds(3)) }        if method == ChatWarmSeed.refused {            return #"{"ok":false,"error":{"code":"not_connected","message":"not_connected"}}"#        }        if let answer = ChatWarmSafety.answer(method, requestJSON, people: Self.answers) { return answer }        if let answer = ChatWarmRecordings.answer(method, requestJSON) { return answer }        // Writing to a number on the linked copy: the chat the core started for it, and where its words go.        if method == ChatPeopleMethod.start, let request = try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8)),           let number = request["number"]?.string, let started = Self.route?.start(number) {            return try Self.ok(started)        }        if method == "assistant.screen", ChatWarmSeed.claudeTimed, let timed = Self.answers["seed.assistant.screen.timed"] {            return try Self.ok(timed)        }        if method == ChatAgentMethod.remove, let answer = ChatWarmAgents.removed(requestJSON) { return answer }        if let answer = ChatWarmAgents.answer(method, people: Self.answers) { return answer }        if let answer = Self.answers[method] { return try Self.ok(answer) }        // Export: the seed's chats are invented answers the core does not hold, so an invented zip in the contract's        // shape stands for the one the core writes (chat CONTRACT.md "Export").        if method == ChatExportMethod.export { return try Self.ok(Self.exported(requestJSON)) }        if let answer = ChatWarmStorage.answer(method, requestJSON) { return answer }        // Link previews: this phone's setting is the seed's, never written to the core under it.        if method == ChatYouMethod.settings, let answer = try await Self.linkPreviews(requestJSON, inner) { return answer }        if method == "shell.settings" {            var raw = try await inner.callRaw(method, requestJSON: requestJSON)            raw = ChatWarmStorage.laid(method, raw) ?? raw            if let bytes = ChatWarmSeed.freeable, !ChatWarmSeed.freed.on { raw = Self.freeable(raw, bytes) ?? raw }            return raw        }        if method == "shell.freeUp", ChatWarmSeed.freeable != nil {            ChatWarmSeed.freed.set()            return try await inner.callRaw(method, requestJSON: #"{"expected":0}"#)        }        // The seed's phone stands signed in, with an invented Claude connected: the account offers Sync now and        // Sign out, and You's rows say what the invented pages hold.        if method == "shell.account" || method == "chat.you" {            let raw = try await inner.callRaw(method, requestJSON: requestJSON)            let seeded = Self.seeded(method, raw) ?? raw            return ChatWarmStorage.laid(method, seeded) ?? seeded        }        if Self.changes.contains(method) || method.hasPrefix("chat.group.") && !Self.answers.keys.contains(method) {            return #"{"ok":true,"data":{"ok":true}}"#        }        return try await inner.callRaw(method, requestJSON: requestJSON)    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async { await inner.subscribe(handler) }    func close() async { await inner.close() }    /// `chat.settings` with the seed's link previews laid over the core's answer, and `{linkPreviews}` kept by the seed.    private static func linkPreviews(_ requestJSON: String, _ inner: any CottonCalling) async throws -> String? {        let request = (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8))) as? [String: Any] ?? [:]        if let on = request["linkPreviews"] as? Bool { ChatWarmLinks.set(on) }        let rest = request.filter { $0.key != "linkPreviews" }        let ask = (try? JSONSerialization.data(withJSONObject: rest)).map { String(decoding: $0, as: UTF8.self) } ?? "{}"        let raw = try await inner.callRaw(ChatYouMethod.settings, requestJSON: ask)        guard var whole = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any],              var data = whole["data"] as? [String: Any] else { return raw }        data["linkPreviews"] = ChatWarmLinks.on        whole["data"] = data        return (try? JSONSerialization.data(withJSONObject: whole)).map { String(decoding: $0, as: UTF8.self) }    }    private static func ok(_ answer: JSONValue) throws -> String {        #"{"ok":true,"data":"# + String(decoding: try JSONEncoder().encode(answer), as: UTF8.self) + "}"    }    /// An invented export: a chat's (or every chat's) words in a text file, zipped as the system zips a folder.    private static func exported(_ requestJSON: String) throws -> JSONValue {        let thread = (try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8)))?["thread"]?.string        let name = ChatWords.line(thread == nil ? "export.all_name" : "export.chat_name")        let root = FileManager.default.temporaryDirectory.appendingPathComponent("seed-export", isDirectory: true)        try? FileManager.default.removeItem(at: root)        let folder = root.appendingPathComponent(name, isDirectory: true)        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)        let words = name + "\n" + ChatWords.line("export.exported", ["day": ISO8601DateFormatter().string(from: Date()).prefix(10).description]) + "\n"        try words.write(to: folder.appendingPathComponent("\(name).txt"), atomically: true, encoding: .utf8)        let out = root.appendingPathComponent("\(name).zip")        var failure: NSError?        NSFileCoordinator().coordinate(readingItemAt: folder, options: .forUploading, error: &failure) { zipped in            try? FileManager.default.copyItem(at: zipped, to: out)        }        if let failure { throw failure }        return .object(["path": .string(out.path), "file_name": .string("\(name).zip"), "mime": .string("application/zip"),                        "count": .number(1), "files": .number(0), "missing": .number(0)])    }    /// Storage offering `bytes` to Free up space, asked in its own button's words.    private static func freeable(_ raw: String, _ bytes: Int64) -> String? {        guard var whole = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any],              var data = whole["data"] as? [String: Any], var storage = data["storage"] as? [String: Any],              var free = storage["free_up"] as? [String: Any], let label = free["label"] as? String else { return nil }        free["bytes"] = bytes        free["ask"] = label        free["confirm"] = label        storage["free_up"] = free        data["storage"] = storage        whole["data"] = data        return (try? JSONSerialization.data(withJSONObject: whole)).map { String(decoding: $0, as: UTF8.self) }    }    /// The core's own answer with the seed's invented parts laid over it.    private static func seeded(_ method: String, _ raw: String) -> String? {        func plain(_ value: JSONValue?) -> Any? {            value.flatMap { try? JSONEncoder().encode($0) }.flatMap { try? JSONSerialization.jsonObject(with: $0, options: [.fragmentsAllowed]) }        }        guard var whole = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any],              var data = whole["data"] as? [String: Any] else { return nil }        if method == "shell.account" {            let acts = (data["actions"] as? [[String: Any]]) ?? []            if acts.contains(where: { $0["id"] as? String == ChatYouRemembered.signIn }), let seeded = plain(answers["seed.account.acts"]) {                data["actions"] = seeded            }        } else {            let screen = ChatWarmSeed.claudeTimed ? answers["seed.assistant.screen.timed"] : answers["assistant.screen"]            let claude = screen?["reading"]?.text("row")            let privacy = answers["seed.chat.you.privacy"]?.string            data["rows"] = ((data["rows"] as? [[String: Any]]) ?? []).map { row in                var row = row                if row["id"] as? String == "claude", let claude { row["line"] = claude }                if row["id"] as? String == "privacy", let privacy { row["line"] = privacy }                return row            }            if ChatWarmSeed.unreachable, let sync = plain(answers["seed.chat.you.unreachable"]) { data["sync"] = sync }        }        whole["data"] = data        return (try? JSONSerialization.data(withJSONObject: whole)).map { String(decoding: $0, as: UTF8.self) }    }}/// Asha's safety number in Comms Dev's seed: the core's answers (`chat-warm.json`'s `safety`), and the mark held for/// the launch as the core keeps it (a matching scan or Mark as verified sets it, Clear verified clears it).enum ChatWarmSafety {    /// Asha's chat: the one whose safety answers the fixture holds.    static let thread = "11111111-1111-4111-8111-0000000000a1"    private static let fixture: JSONValue? = ChatWarmSeed.load()?.safety    private static let held = Held()    private final class Held: @unchecked Sendable {        private let lock = NSLock()        private var on = false        var verified: Bool {            get { lock.withLock { on } }            set { lock.withLock { on = newValue } }        }    }    /// An invented code by its name (`theirs`, `old`, `other`).    static func code(named name: String) -> String? {        fixture?["scans"]?.array?.first { $0["name"]?.string == name }?["code"]?.string    }    /// The envelope for a safety ask of Asha's chat (and her page's `verified`); nil for anything else.    static func answer(_ method: String, _ requestJSON: String, people: [String: JSONValue]) -> String? {        guard method.hasPrefix("chat.safety") || method == "chat.contact", let fixture,              let request = try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8)),              request["thread"]?.string == thread else { return nil }        switch method {        case "chat.safety":            guard case .object(var shown)? = held.verified ? fixture["verified"] : fixture["safety"] else { return nil }            shown["thread"] = .string(thread)            return ok(.object(shown))        case "chat.safety.scan":            let code = request["code"]?.string            guard let scanned = fixture["scans"]?.array?.first(where: { $0["code"]?.string == code })?["answer"] else {                let refused = fixture["refused"]                return refusal(refused?["code"]?.string ?? "bad_code", refused?["message"]?.string ?? "")            }            if scanned["verified"]?.bool == true { held.verified = true }            return ok(scanned)        case "chat.safety.verify":            held.verified = request["verified"]?.bool ?? false            return ok(.object(["verified": .bool(held.verified)]))        case "chat.contact":            guard case .object(var contact)? = people["chat.contact"] else { return nil }            contact["verified"] = .bool(held.verified)            return ok(.object(contact))        default:            return nil        }    }    private static func ok(_ data: JSONValue) -> String? {        guard let encoded = try? JSONEncoder().encode(data) else { return nil }        return #"{"ok":true,"data":"# + String(decoding: encoded, as: UTF8.self) + "}"    }    private static func refusal(_ code: String, _ message: String) -> String? {        let error: JSONValue = .object(["code": .string(code), "message": .string(message)])        guard let encoded = try? JSONEncoder().encode(error) else { return nil }        return #"{"ok":false,"error":"# + String(decoding: encoded, as: UTF8.self) + "}"    }}/// An agent in a chat in Comms Dev's seed (CONTRACT.md "An agent in a chat"): Hill trip holds Bimal's Claude; his own/// invented Claude is offered by Add an agent and stands first in the list once added, until removed. With/// `-chat-warm-agent connect` none is connected and the core's line says to connect one.enum ChatWarmAgents {    private static let held = Held()    private final class Held: @unchecked Sendable {        private let lock = NSLock()        private var mine = false        private var bimal = true        var yoursIn: Bool {            get { lock.withLock { mine } }            set { lock.withLock { mine = newValue } }        }        var bimalIn: Bool {            get { lock.withLock { bimal } }            set { lock.withLock { bimal = newValue } }        }    }    static func answer(_ method: String, people: [String: JSONValue]) -> String? {        switch method {        case ChatGroupMethod.info:            guard case .object(var info)? = people[method], case .array(let theirs)? = info["agents"] else { return nil }            var agents: [JSONValue] = held.bimalIn ? theirs : []            if held.yoursIn, let mine = people["seed.agent.yours"] { agents.insert(mine, at: 0) }            info["agents"] = .array(agents)            return ok(.object(info))        case ChatAgentMethod.choices:            if ChatWarmSeed.agentConnect {                return ok(.object(["agents": .array([]), "connect": .bool(true), "line": people["seed.agent.connect"] ?? .null]))            }            let mine = people["seed.agent.yours"]            return ok(.object(["agents": .array([.object(["agent": mine?["agent"] ?? .null, "name": mine?["name"] ?? .null, "in": .bool(held.yoursIn)])]),                               "connect": .bool(false), "line": .null]))        case ChatAgentMethod.add:            held.yoursIn = true            return ok(.object(["ok": .bool(true)]))        case ChatAgentMethod.remove:            // The request names which; the seed's two are his own and Bimal's.            return nil        default:            return nil        }    }    /// Remove: his own when it is in, else Bimal's.    static func removed(_ requestJSON: String) -> String? {        guard let request = try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8)) else { return nil }        if request["agent"]?.string == "agent-bimal" { held.bimalIn = false } else { held.yoursIn = false }        return ok(.object(["ok": .bool(true)]))    }    private static func ok(_ data: JSONValue) -> String? {        guard let encoded = try? JSONEncoder().encode(data) else { return nil }        return #"{"ok":true,"data":"# + String(decoding: encoded, as: UTF8.self) + "}"    }}/// Storage by chat in Comms Dev's seed: the core's answers over invented files of known sizes (`chat-warm.json`'s/// `storage`, `chat_storage_tests::warm_fixture`), laid over Storage's totals and You's Storage line so the page adds/// up. Free this chat answers the core's own words and then the core's answers after that chat was freed (one chat/// at a time: freeing another stands for that one alone), and that chat's pictures then come back slowly, as from/// the account, while their previews stand.enum ChatWarmStorage {    private static let fixture: JSONValue? = ChatWarmSeed.load()?.storage    /// Each invented chat's messages, by thread.    private static let messages: [String: Set<String>] = (ChatWarmSeed.load()?.threads ?? [:]).mapValues { Set($0.items.compactMap { $0.bubble?.message }) }    private static let held = Held()    private final class Held: @unchecked Sendable {        private let lock = NSLock()        private var chat: String?        var freed: String? {            get { lock.withLock { chat } }            set { lock.withLock { chat = newValue } }        }    }    private static var state: JSONValue? {        if let thread = held.freed, let after = fixture?["freed"]?[thread] { return after }        return fixture?["before"]    }    /// Whether `message` is in the chat freed here (Meera's invented media are the seed's own).    static func freedHere(_ message: String) -> Bool {        guard let thread = held.freed else { return false }        if thread == ChatWarmSeed.mediaThread, message.hasPrefix("m-media-") { return true }        return messages[thread]?.contains(message) ?? false    }    static func answer(_ method: String, _ requestJSON: String) -> String? {        guard let fixture else { return nil }        switch method {        case ChatYouMethod.storage:            return state?["chats"].flatMap(ok)        case ChatYouMethod.storageFree:            guard let request = try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8)),                  let thread = request["thread"]?.string, let after = fixture["freed"]?[thread], let said = after["said"] else { return nil }            held.freed = thread            return ok(said)        default:            return nil        }    }    /// The core's own answer with the fixture's totals (`shell.settings`) or Storage line (`chat.you`) laid over it.    static func laid(_ method: String, _ raw: String) -> String? {        guard let state, var whole = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any],              var data = whole["data"] as? [String: Any] else { return nil }        func plain(_ value: JSONValue?) -> Any? {            value.flatMap { try? JSONEncoder().encode($0) }.flatMap { try? JSONSerialization.jsonObject(with: $0, options: [.fragmentsAllowed]) }        }        if method == "shell.settings", let storage = plain(state["settings"]) {            data["storage"] = storage        } else if method == ChatYouMethod.you, let line = state["row"]?.string {            data["rows"] = ((data["rows"] as? [[String: Any]]) ?? []).map { row in                var row = row                if row["id"] as? String == "storage" { row["line"] = line }                return row            }        } else {            return nil        }        whole["data"] = data        return (try? JSONSerialization.data(withJSONObject: whole)).map { String(decoding: $0, as: UTF8.self) }    }    private static func ok(_ data: JSONValue) -> String? {        guard let encoded = try? JSONEncoder().encode(data) else { return nil }        return #"{"ok":true,"data":"# + String(decoding: encoded, as: UTF8.self) + "}"    }}#if canImport(UIKit)import SwiftUI/// A call engine that only draws: the preview's (`-chat-warm-call`).@MainActorfinal class ChatWarmSeedCalls: ChatCalling {    var stamp: String { "seed" }    var speaker: Bool { false }    func place(thread: String?, call: String?, video: Bool?, refused: @escaping @MainActor (String) -> Void) {}    func join(thread: String, video: Bool, refused: @escaping @MainActor (String) -> Void) {}    var flush: (@Sendable () async -> Void)?    func read(_ method: String, _ request: JSONValue) async -> JSONValue? { nil }    func answer() {}    func decline() {}    func end() {}    func toggleMute() {}    func toggleVideo() {}    func toggleSpeaker() {}    func flipCamera() {}    /// Their picture stands in for their video: an invented warm wash.    func remoteVideo() -> AnyView {        AnyView(LinearGradient(colors: [Color(red: 0.42, green: 0.33, blue: 0.27), Color(red: 0.17, green: 0.13, blue: 0.11)], startPoint: .top, endPoint: .bottom))    }    func localVideo() -> AnyView { AnyView(Color(red: 0.55, green: 0.5, blue: 0.45)) }    func memberVideo(_ member: String) -> AnyView { remoteVideo() }}#endif/// Recordings in Comms Dev's seed (CONTRACT.md "Recordings"), until the core writes them into `chat-warm.json`: invented/// answers in the contract's shapes (Fixtures/chat-warm-recordings.json): two recordings among the calls, the notes on/// Ravi's call, each page; an act answers the page again with its line (a title, Save as note, a to-do kept for the/// launch); a recording made or brought in answers as the garden party's page under its own id. The audio is the/// invented voice recording.enum ChatWarmRecordings {    private static let fixture: JSONValue? = {        guard let url = Bundle.module.url(forResource: "chat-warm-recordings", withExtension: "json", subdirectory: "Fixtures"),              let data = try? Data(contentsOf: url) else { return nil }        return try? JSONDecoder().decode(JSONValue.self, from: data)    }()    private static let held = Held()    private final class Held: @unchecked Sendable {        private let lock = NSLock()        private var pages: [String: JSONValue] = [:]        func page(_ id: String) -> JSONValue? { lock.withLock { pages[id] } }        func keep(_ id: String, _ page: JSONValue) { lock.withLock { pages[id] = page } }    }    /// Calls with the recordings by day, Record, Bring in a recording and the notes on a call.    static func calls(_ answer: ChatCallsAnswer) -> ChatCallsAnswer {        guard let calls = fixture?["calls"] else { return answer }        var out = answer        out.words.record = calls["record"]?.string        out.words.import = calls["import"]?.string        let days = calls["days"]        let notes = calls["notes"]        var rows = answer.rows.map { row -> ChatCallRow in            var row = row            row.kind = "call"            row.day = days?[row.call]?.string            row.recording = notes?[row.call]?.string            return row        }        for entry in calls["recordings"]?.array ?? [] {            guard let made = entry["row"].flatMap({ try? JSONEncoder().encode($0) }),                  let row = try? JSONDecoder().decode(ChatCallRow.self, from: made) else { continue }            if let after = entry["after"]?.string, let at = rows.firstIndex(where: { $0.call == after }) {                rows.insert(row, at: at + 1)            } else {                rows.insert(row, at: 0)            }        }        out.rows = rows        return out    }    /// The envelope for a recordings ask; nil for anything else.    static func answer(_ method: String, _ requestJSON: String) -> String? {        guard let fixture, let request = try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8)) else { return nil }        switch method {        case ChatRecordingMethod.page:            return request["id"]?.string.flatMap(page).map { tooled($0, query: request["query"]?.string) }.flatMap(ok)        case ChatRecordingMethod.act:            guard let id = request["id"]?.string, case .object(var shown)? = page(id), let act = request["act"]?.string else { return nil }            let said = fixture["said"]?[act] ?? .null            switch act {            case "export":                return exported(.object(shown), format: request["format"]?.string ?? "text")            case "delete":                return ok(.object(["deleted": .bool(true), "said": said]))            case "title":                if let title = request["title"]?.string { shown["title"] = .string(title) }            case "date":                // The moment chosen, as the core keeps it (its `when` words stay the fixture's: the core's to say).                if case .object(var buttons)? = shown["buttons"], case .object(var date)? = buttons["date"], let at = request["at"] {                    date["at"] = at                    buttons["date"] = .object(date)                    shown["buttons"] = .object(buttons)                }            case "note":                if case .object(var buttons)? = shown["buttons"], case .object(var note)? = buttons["note"] {                    note["saved"] = .bool(true)                    buttons["note"] = .object(note)                    shown["buttons"] = .object(buttons)                }            case "todo":                let action = request["action"]?.string                if case .array(let actions)? = shown["actions"] {                    shown["actions"] = .array(actions.map { item in                        guard item["id"]?.string == action, case .object(var made) = item else { return item }                        made["added"] = .bool(true)                        made["act"] = .null                        made["said"] = said                        return .object(made)                    })                }            default:                break            }            held.keep(id, .object(shown))            var answer: [String: JSONValue] = ["page": .object(shown), "said": act == "todo" ? .null : said]            if act == "share" { answer["flush"] = .bool(false) }            return ok(.object(answer))        case ChatRecordingMethod.live:            guard case .object(var live)? = fixture["live"] else { return nil }            let seconds = (request["duration_ms"]?.int ?? 0) / 1000            live["time"] = .string(String(format: "%d:%02d", seconds / 60, seconds % 60))            return ok(.object(live))        case ChatRecordingMethod.importFile:            let meeting = "rec-import-" + UUID().uuidString.prefix(8)            return ok(.object(["meeting": .string(meeting), "status": .string("waiting"), "said": fixture["said"]?["import"] ?? .null]))        case CottonMethod.mediaEnsure:            guard request["key"]?.string?.hasPrefix("seed-") == true, let path = Bundle.module.url(forResource: "chat-warm-voice", withExtension: "m4a", subdirectory: "Fixtures")?.path else { return nil }            return ok(.object(["path": .string(path)]))        case MeetingsMethod.recordStart:            let id = request["id"]?.string ?? UUID().uuidString            let path = FileManager.default.temporaryDirectory.appendingPathComponent("seed-\(id).wav").path            return ok(.object(["meeting": .string(id), "audio_path": .string(path), "started_at": .string(ISO8601DateFormatter().string(from: Date()))]))        case MeetingsMethod.recordTick, MeetingsMethod.recordStop:            return ok(.object(["ok": .bool(true)]))        default:            return nil        }    }    /// The page with the core's search, ±15 s skip and Export laid on (073c52456a's shapes, the fixture's `tools`): the    /// lines holding the words typed, cut into parts, as the core cuts them.    private static func tooled(_ shown: JSONValue, query: String?) -> JSONValue {        guard case .object(var page) = shown, let tools = fixture?["tools"], case .object(var buttons)? = page["buttons"] else { return shown }        buttons["skip"] = tools["skip"]        buttons["export"] = tools["export"]        page["buttons"] = .object(buttons)        let words = tools["search"]        let hint = words?["hint"] ?? .null        let asked = query?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""        guard !asked.isEmpty else {            page["search"] = .object(["hint": hint, "query": .null, "hits": .array([]), "line": .null])            return .object(page)        }        let fold: (String) -> String = { $0.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) }        var hits: [JSONValue] = []        for line in page["lines"]?.array ?? [] {            let text = line["text"]?.string ?? ""            let folded = fold(text) as NSString            var parts: [JSONValue] = []            var at = 0            var found = folded.range(of: fold(asked))            while found.location != NSNotFound {                if found.location > at { parts.append(.object(["text": .string((text as NSString).substring(with: NSRange(location: at, length: found.location - at))), "hit": .bool(false)])) }                parts.append(.object(["text": .string((text as NSString).substring(with: found)), "hit": .bool(true)]))                at = NSMaxRange(found)                found = folded.range(of: fold(asked), range: NSRange(location: at, length: folded.length - at))            }            guard !parts.isEmpty else { continue }            if at < folded.length { parts.append(.object(["text": .string((text as NSString).substring(from: at)), "hit": .bool(false)])) }            hits.append(.object(["line": line["line"] ?? .null, "start_ms": line["start_ms"] ?? .null, "parts": .array(parts)]))        }        let count = hits.count == 1 ? words?["one"] : hits.isEmpty ? words?["none"]            : (words?["many"]?.string).map { .string($0.replacingOccurrences(of: "{count}", with: String(hits.count))) }        page["search"] = .object(["hint": hint, "query": .string(asked), "hits": .array(hits), "line": count ?? .null])        return .object(page)    }    /// Export, as the core answers it: the transcript written to a file of this phone's (`file`), or the core's refusal    /// when the audio is asked of a recording with none.    private static func exported(_ shown: JSONValue, format: String) -> String? {        if format == "audio", shown["audio"] == nil || shown["audio"] == .null {            let words = fixture?["tools"]?["absent"]?.string ?? ""            let encoded = String(decoding: (try? JSONEncoder().encode(JSONValue.string(words))) ?? Data(), as: UTF8.self)            return #"{"ok":false,"error":{"code":"absent","message":"# + encoded + "}}"        }        let title = shown["title"]?.string ?? ""        let ext = format == "srt" ? "srt" : format == "audio" ? "m4a" : "txt"        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("seed-recording-export", isDirectory: true)        try? FileManager.default.removeItem(at: dir)        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)        let file = dir.appendingPathComponent("\(title).\(ext)")        if format == "audio", let voice = Bundle.module.url(forResource: "chat-warm-voice", withExtension: "m4a", subdirectory: "Fixtures") {            try? FileManager.default.copyItem(at: voice, to: file)        } else {            let lines = (shown["lines"]?.array ?? []).compactMap { $0["text"]?.string }            try? (title + "\n\n" + lines.joined(separator: "\n")).write(to: file, atomically: true, encoding: .utf8)        }        let type = format == "srt" ? "application/x-subrip" : format == "audio" ? "audio/mp4" : "text/plain"        return ok(.object(["file": .object(["path": .string(file.path), "name": .string(file.lastPathComponent), "type": .string(type)])]))    }    /// A page by its id: the one kept after an act, the fixture's, else (a recording made or brought in) the garden party's.    private static func page(_ id: String) -> JSONValue? {        if let kept = held.page(id) { return kept }        if let page = fixture?["pages"]?[id] { return page }        guard case .object(var made)? = fixture?["pages"]?["rec-garden"] else { return nil }        made["id"] = .string(id)        return .object(made)    }    private static func ok(_ answer: JSONValue) -> String? {        guard let data = try? JSONEncoder().encode(answer) else { return nil }        return #"{"ok":true,"data":"# + String(decoding: data, as: UTF8.self) + "}"    }}#endif