// 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 AVFoundationimportCottonKitimportFoundation#if canImport(UIKit)import UIKit#endif/// A switch the seed's core and book share, set once from any thread.finalclassChatWarmFlag: @unchecked Sendable {privatelet lock = NSLock()privatevar value = falsevar on: Bool { lock.withLock { value } }func set() { lock.withLock { value = true } }}enumChatWarmSeed {staticvar asked: Bool { UserDefaults.standard.bool(forKey: "chat-warm-seed") }staticvar long: Int { UserDefaults.standard.integer(forKey: "chat-warm-long") }/// `-chat-warm-open <thread>` opens that chat over the list.staticvaropen: String? { UserDefaults.standard.string(forKey: "chat-warm-open") }staticlet longThread = "chat-warm-long"/// Meera's chat carries an invented photo, voice message and file.staticlet mediaThread = "11111111-1111-4111-8111-0000000000e1"/// Ravi's chat stands for someone not on Cotton yet.staticlet 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.staticlet gonePictures: Set<String> = ["m-w7"]/// `-chat-warm-place calls|you` opens that place.staticvar 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.staticvar 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.staticvar 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.staticvar 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.staticvar unreachable: Bool { UserDefaults.standard.bool(forKey: "chat-warm-unreachable") }/// `-chat-warm-person YES` opens the opened chat's person page.staticvar 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.staticvar timer: Int? { UserDefaults.standard.object(forKey: "chat-warm-timer").flatMap { Int("\($0)") } }staticvar timerSheet: Bool { UserDefaults.standard.bool(forKey: "chat-warm-timer-sheet") }/// `-chat-warm-new YES` opens New chat.staticvar 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.staticvar refused: String? { UserDefaults.standard.string(forKey: "chat-warm-refuse") }/// `-chat-warm-slow <method>` answers that method three seconds late, as a server far away.staticvar 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.staticlet 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.staticvar 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.staticvar 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.staticvar freeable: Int64? { UserDefaults.standard.string(forKey: "chat-warm-freeable").flatMap { Int64($0) } }staticlet 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.staticvar vote: Double? { UserDefaults.standard.string(forKey: "chat-warm-vote").flatMap(Double.init) }staticlet voted = ChatWarmFlag()staticlet 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.staticvar revoke: Double? { UserDefaults.standard.string(forKey: "chat-warm-revoke").flatMap(Double.init) }staticlet revoked = ChatWarmFlag()staticlet revokeComing = ChatWarmFlag()/// `-chat-warm-pictures N`: the long chat (`-chat-warm-long`) carries a picture in every third message.staticvar longPictures: Bool { UserDefaults.standard.bool(forKey: "chat-warm-pictures") }/// An invented picture written into the outbox's folder, as a picked photo is.staticfunc 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)) != nilelse { returnnil }returnChatOutbox.attachment(at: url) #elsereturnnil #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.staticfunc inventedHill() -> Data? {let size = CGSize(width: 1200, height: 800)let format = UIGraphicsImageRendererFormat() format.scale = 1let image = UIGraphicsImageRenderer(size: size, format: format).image { context inlet 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]iflet 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).staticvar 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.staticvar 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).staticvar 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) staticvar picked = 0/// `-chat-warm-linked YES`: the list is the linked copy's (WhatsApp through the Mac), as the core answers it.staticvar 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.staticvar 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).staticvar 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).staticvar 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.staticvar 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.staticvar 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.staticvar 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.staticvar 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`).staticvar 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`).staticvar microphone: CapabilityAccess? {switchUserDefaults.standard.string(forKey: "chat-warm-mic") {case"notDetermined": .notDeterminedcase"denied": .deniedcase"authorized": .authorizeddefault: nil } }/// A new account, none of the person's chats yet (`-chat-warm-fresh YES`).staticvar fresh: Bool { UserDefaults.standard.bool(forKey: "chat-warm-fresh") }/// `-chat-warm-voice YES`: the microphone held records the invented recording.staticvar 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.staticvar 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).staticvar voiceWords: String { ChatWarmSeedCore.answers["seed.voice.said"]?.string ?? "" }/// The words under the voice message Meera's chat ends with (invented).staticvar heardWords: String { ChatWarmSeedCore.answers["seed.voice.heard"]?.string ?? "" }/// The invented recording, copied where a recorded voice message waits, and its length.staticfunc recordedVoice() -> (url: URL, seconds: Double)? {guardlet source = Bundle.module.url(forResource: "chat-warm-voice", withExtension: "m4a", subdirectory: "Fixtures") else { returnnil }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 { returnnil }return (url, Double(file.length) / file.processingFormat.sampleRate) }/// The invented picture Photos and videos hands over: a warm wash written where an attachment waits.staticfunc 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 += 1let image = UIGraphicsImageRenderer(size: CGSize(width: 480, height: 360)).image { context inlet 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]guardlet 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)) != nilelse { returnnil }returnChatOutbox.attachment(at: url) #elsereturnnil #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.staticfunc 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) inChatWarmSeedCore.answers[key]?.string ?? "" }let url = folder.appendingPathComponent(said(large ? "seed.file.large" : "seed.file.name"))do {tryFileManager.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 = tryFileHandle(forWritingTo: url)try handle.truncate(atOffset: (100 << 20) + 1)try handle.close() } } catch { returnnil }return url }/// The call screen as the core would answer it, over invented Asha.staticfunc 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"returnChatCallScreen( 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) }staticfunc groupCallScreen(_ state: String) -> ChatCallScreen? {guardlet 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 { returnnil }guardvar screen = try? JSONDecoder().decode(ChatCallScreen.self, from: raw) else { returnnil }// 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 }structFixture: Decodable {var list: ChatListAnswervar unread: ChatListAnswervar groups: ChatListAnswervar 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).structDocument: 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`).structRevokeFixture: Decodable {var thread: Stringvar before: ChatThreadAnswer }/// A poll's bubble after a vote arrived (`write_chat_warm_fixture`'s `votes`).structVotesFixture: Decodable {var thread: Stringvar 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`.structTimerFixture: Decodable {var act: ChatActAnswer?var timer: ChatTimerCard?var header: ChatHeader?var lines: [ChatThreadItem]?var day: ChatThreadItem?init(from decoder: Decoder) throws {iflet day = try? ChatThreadItem(from: decoder), case .day = day {self.day = dayreturn }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) }privateenumKeys: String, CodingKey { case act, timer, header, lines } }/// The voice player's answers (`write_chat_warm_fixture`).structVoiceFixture: 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: SettingsstructSettings: 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.staticfunc bars(_ wave: [Double]) -> [Double]? {guard !wave.isEmpty else { returnnil }let n = 36let 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() ?? 0return 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.staticfunc inventedVoice(_ message: String, seconds: Double) -> URL? {let ms = Int(seconds * 1000)let url = FileManager.default.temporaryDirectory.appendingPathComponent("chat-warm-voice-\(message)-\(ms).m4a")ifFileManager.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.0let settings: [String: Any] = [AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: rate, AVNumberOfChannelsKey: 1, AVEncoderBitRateKey: 32_000]guardlet format = AVAudioFormat(standardFormatWithSampleRate: rate, channels: 1),let file = try? AVAudioFile(forWriting: making, settings: settings, commonFormat: .pcmFormatFloat32, interleaved: false) else { returnnil }let total = Int(seconds * rate), chunk = 8_192var at = 0while at < total {let count = min(chunk, total - at)guardlet buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(count)), let out = buffer.floatChannelData?[0] else { returnnil } buffer.frameLength = AVAudioFrameCount(count)for i in0..<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 { returnnil } at += count } file.close()try? FileManager.default.moveItem(at: making, to: url)returnFileManager.default.fileExists(atPath: url.path) ? url : nil }/// One message replied to, as the core answers it (`write_chat_warm_fixture`).structReplyFixture: Decodable {var composer: ChatComposeAnswervar quote: ChatQuote }/// The core's answers over a WhatsApp chat that sends through the Mac (`write_chat_warm_fixture`).structWhatsAppFixture: 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?structVoteFixture: Decodable {/// The poll's message, and the option the fixture's tap chose.var message: Stringvar 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: ChatThreadItemvar 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?structPollFixture: 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 }structChangesFixture: Decodable {/// The message edited, the one deleted for everyone, and hers deleted for him only.var edited: Stringvar deleted: Stringvar 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: ChatComposeAnswervar editTyping: ChatComposeAnswer/// `chat.act edit`: the new words at once, "Edit waiting to send".var edit: ChatActAnswervar editCancelled: ChatComposeAnswer/// The edit the Mac could not send ("Edit not sent: <why>", Retry), and its retry.var editFailed: ChatThreadItemvar 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: ChatActAnswervar deleteFailed: ChatThreadItemvar 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?structGridFixture: 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 }structDocumentFixture: 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 }structRefusal: Decodable {var code: Stringvar 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.structRouteFixture: 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.privatestaticlet words: [String: String] = {guardlet 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 }()staticfunc invented(_ key: String) -> String { words[key] ?? key }staticfunc load() -> Fixture? {guardlet url = Bundle.module.url(forResource: "chat-warm", withExtension: "json", subdirectory: "Fixtures"),let data = try? Data(contentsOf: url) else { returnnil }// 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.finalclassDecoded: @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 }}privatefinalclassChatWarmObserver: @unchecked Sendable {let token: any NSObjectProtocolinit(_ 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.finalclassChatWarmMarks: @unchecked Sendable {privatelet lock = NSLock()privatevar held: [String: Bool] = [:]/// Chats deleted this launch: gone from every list, as the core's `cleared_before` keeps them.privatevar 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.privatevar 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() }guardlet unread = held[row.thread] else { return row }var row = rowif unread { row.markedUnread = true } else { row.unread = 0; row.markedUnread = false }let now = row.unread > 0 || row.markedUnreadlet act = now ? "read" : "unread"let turned = { (swipe: ChatSwipe, words: String) -> ChatSwipein 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.finalclassChatWarmSeedBook: ChatBook, @unchecked Sendable {privatelet fixture: ChatWarmSeed.Fixtureprivatelet long: Intprivatelet page = 60init?(long: Int) {guardlet fixture = ChatWarmSeed.load() else { returnnil }self.fixture = fixtureself.long = long// His vote the Mac could not send, standing as the core then answers the poll.ifChatWarmSeed.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.ifChatWarmSeed.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`).privatefunc changesPage(_ thread: String) -> ChatThreadAnswer? {guardChatWarmSeed.waChanges != nil, let c = fixture.whatsapp.changes, c.page.thread == thread else { returnnil }return c.page }var photosByKey: Bool { true }func list(_ ask: ChatListAsk) asyncthrows -> ChatListAnswer {var answer: ChatListAnswerswitch ask.filter {case"unread": answer = fixture.unreadcase"groups": answer = fixture.groupscase"archived": answer = fixture.archiveddefault:ifChatWarmSeed.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) }iflet 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.iflet 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) asyncthrows -> ChatThreadAnswer {guard ask.thread == ChatWarmSeed.longThread,let template = fixture.threads.values.filter({ !$0.header.group }).max(by: { $0.items.count < $1.items.count }) else {guardvar answer = votePage(ask.thread) ?? changesPage(ask.thread) ?? fixture.threads[ask.thread] else { throwCancellationError() }if ask.thread == ChatWarmSeed.mediaThread { answer.items += Self.media(after: answer.items) }iflet words = wordsOnly(ask.thread) { answer.composer = words }// Opened around a message (a quote tapped): the core's page stands on it.iflet around = ask.around { answer.focus = around }// Deleted while he looks: until the deletes land, the chat as it stood before them.ifChatWarmSeed.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.ifChatWarmSeed.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.iflet 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.iflet 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 inguardlet bubble = item.bubble else { return item }if removed.contains(bubble.message) { returnnil }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? inifcase .bubble(let bubble) = item, bubble.tick != .failed { return bubble }returnnil }guard !bubbles.isEmpty else { return template }var hi = long, lo = max(0, long - page)iflet before = ask.before.flatMap(Int.init) { hi = before; lo = max(0, before - page) }iflet 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 invar 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`).privatefunc votePage(_ thread: String) -> ChatThreadAnswer? {guardChatWarmSeed.waVote != nil, let vote = fixture.whatsapp.vote, vote.page.thread == thread else { returnnil }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.privatefunc voted(_ ask: ChatActAsk) throws -> ChatActAnswer? {guardlet vote = fixture.whatsapp.vote, vote.page.thread == ask.thread, ask.message == vote.message else { returnnil }switch ask.act {case"vote":ifChatWarmSeed.waVote == "refuse" { throwCottonCallError(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 { returnChatActAnswer(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.votecase"retry": sentLock.withLock { votedPoll = vote.retried.bubble }return vote.retrieddefault:returnnil } }privatefunc wordsOnly(_ thread: String) -> ChatComposeAnswer? {ifChatWarmSeed.waPoll == "alone", let alone = fixture.whatsapp.poll?.alone, alone.thread == thread { return alone }guardChatWarmSeed.waWordsOnly, let words = fixture.whatsapp.wordsOnly, words.thread == thread else { returnnil }return words }/// The edit strip, as the core answers it while he edits his message (`chat.compose { edit }`), or nil.privatefunc editing(_ ask: ChatComposeAsk) -> ChatComposeAnswer? {guardlet c = fixture.whatsapp.changes, c.page.thread == ask.thread else { returnnil }if ask.cancel == true { returnnil }guardlet message = ask.edit, message == c.edited else { returnnil }guardlet 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 : .idlereturn typing }func compose(_ ask: ChatComposeAsk) asyncthrows -> ChatComposeAnswer {iflet edit = editing(ask) { return edit }guardvar composer = wordsOnly(ask.thread) ?? fixture.threads[ask.thread]?.composer ?? fixture.threads.values.compactMap(\.composer).first else { throwCancellationError() }// 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? inif ask.cancel == true { replying[ask.thread] = nil }iflet 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.guardlet text = ask.text else { return composer }// A link written offers its card, as the core answered these words (none with the setting off).iflet offered = ChatWarmLinks.composer(ask.thread, text) { composer.preview = offered.preview } composer.text = textif !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 }privatelet sentLock = NSLock()privatevar sent = 0/// What was sent in each chat (not over a slow line), standing at its foot when the chat is read again.privatevar sentIn: [String: [ChatBubble]] = [:]/// The reply strip standing on each chat, until cancelled or sent.privatevar replying: [String: ChatStrip] = [:]/// What Send answered, by message, for the acts that follow it (a voice message's words).privatevar sentBubbles: [String: ChatBubble] = [:]/// Disappearing messages chosen in each chat: the core's timer and header after the last choice, and every line.privatevar 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.privatefunc 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 { returnnil } 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 inguardcase .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) asyncthrows -> 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)returnChatActAnswer(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] {returnChatActAnswer(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? inguardvar bubble = sentBubbles[message], bubble.kind == .voice, bubble.media.first?.transcript == nilelse { returnnil } bubble.media[0].transcript = words sentBubbles[message] = bubblereturn bubble }returnChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: message, bubble: bubble, row: nil, sentTo: nil, flush: false, said: nil) }iflet 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)returnChatActAnswer(ok: true, act: ask.act, thread: ask.thread, message: message, bubble: bubble, row: nil, sentTo: nil, flush: false, said: nil) }iflet answer = try voted(ask) { return answer }iflet answer = try whatsAppChange(ask) { return answer }iflet answer = try whatsApp(ask) { return answer }guard ask.act == "send", let bubble = sentBubble(ask) else {returnChatActAnswer(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).guardChatWarmSeed.sendPicture != nilelse { sentLock.withLock { sentIn[ask.thread, default: []].append(bubble) }returnChatActAnswer(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)) }returnChatActAnswer(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`).privatefunc whatsApp(_ ask: ChatActAsk) throws -> ChatActAnswer? {guardlet page = fixture.threads[ask.thread], page.header.source == "whatsapp" || page.header.place?.id == "whatsapp"else { returnnil }let wa = fixture.whatsappswitch ask.act {case"send":let files = ask.attachments ?? []if !files.isEmpty, ChatWarmSeed.waRefuse, let refused = wa.tooLarge { throwCottonCallError(code: refused.code, message: refused.message) }iflet document = files.first(where: { $0.kind == "file" }), let doc = wa.document {ifChatWarmSeed.waNoDocuments { throwCottonCallError(code: doc.notYet.code, message: doc.notYet.message) }let bytes = (try? FileManager.default.attributesOfItem(atPath: document.path)[.size] as? NSNumber)?.int64Value ?? 0if bytes > 100 << 20 { throwCottonCallError(code: doc.tooLarge.code, message: doc.tooLarge.message) }return documentSent(ask, document, doc.send) }let n = sentLock.withLock { sent += 1; return sent }iflet grid = gridSent(ask, files, n) { return grid }let first = files.firstvar 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.textiflet 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.previewiflet ms = first.durationMs { part.durationMs = Int(ms) part.length = Duration.milliseconds(Int64(ms)).formatted(.time(pattern: .minuteSecond)) }iflet 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.iflet bubble = answer.bubble { sentLock.withLock { waiting[ask.thread, default: []].append(bubble) } }return answercase"retry":guardlet message = ask.message, message.hasPrefix(ChatThreadModel.pending) else { returnnil }let held = page.items.lazy.compactMap(\.bubble).first { $0.message == message }guard held?.actions.first == "retry"else { throwCottonCallError(code: wa.refused.code, message: wa.refused.message) }let picture = held.map { [.photo, .video, .album].contains($0.kind) } ?? falsevar answer = (picture ? wa.retryPicture : nil) ?? wa.retry answer.thread = ask.thread answer.message = message answer.bubble?.message = message answer.bubble?.text = held?.textif picture, let media = held?.media { answer.bubble?.media = media }iflet bubble = answer.bubble { sentLock.withLock { retried[message] = bubble } }return answerdefault:returnnil } }/// 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.privatefunc 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 { returnnil }let head = "\(ChatThreadModel.pending)seed-sent-\(n)" bubble.message = head bubble.text = ask.text bubble.media = files.enumerated().map { i, file invar 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) { iflet message = part.message { pickedFiles[message] = file.path } } waiting[ask.thread, default: []].append(bubble) }iflet 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.privatefunc land(_ pending: ChatBubble, thread: String, n: Int, after delay: Double, files: [String]) {guardvar landed = fixture.whatsapp.grid?.landed else { return }let head = "seed-landed-\(n)" landed.message = head landed.text = pending.textlet template = landed.media.first landed.media = pending.media.enumerated().map { i, part invar 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 = landedTask { [weakself] intry? awaitTask.sleep(for: .seconds(delay))guardletselfelse { return }let told = self.sentLock.withLock { () -> [AsyncStream<ChatChange>.Continuation] inself.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)returnself.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.privatevar 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.privatefunc documentSent(_ ask: ChatActAsk, _ document: ChatAttachment, _ sent: ChatActAnswer) -> ChatActAnswer {let wa = fixture.whatsappvar answers: [ChatActAnswer] = []iflet words = ask.text, !words.isEmpty {var text = wa.send text.bubble?.text = words answers.append(text) }var file = sent file.bubble?.text = nilifvar part = file.bubble?.media.first { part.name = document.name ?? part.name file.bubble?.media = [part] } answers.append(file) answers = answers.map { one invar one = onelet n = sentLock.withLock { self.sent += 1; returnself.sent } one.thread = ask.thread one.message = "\(ChatThreadModel.pending)seed-sent-\(n)" one.bubble?.message = one.message ?? ""iflet 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.privatevar votedPoll: ChatBubble?/// His messages edited or deleted for everyone here, by message: the bubble the core then answers (a marker's/// for a delete).privatevar changed: [String: ChatBubble] = [:]/// Messages deleted for him only here.privatevar 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.privatefunc whatsAppChange(_ ask: ChatActAsk) throws -> ChatActAnswer? {let wa = fixture.whatsappif ask.act == "poll", let poll = wa.poll {ifChatWarmSeed.waPoll == "refuse" { throwCottonCallError(code: poll.refused.code, message: poll.refused.message) }var answer = poll.sendlet n = sentLock.withLock { sent += 1; return sent } answer.thread = ask.thread answer.message = "\(ChatThreadModel.pending)seed-sent-\(n)" answer.bubble?.message = answer.message ?? ""iflet bubble = answer.bubble { sentLock.withLock { waiting[ask.thread, default: []].append(bubble) } }return answer }guardlet c = wa.changes, c.page.thread == ask.thread, let message = ask.message else { returnnil }switch ask.act {case"edit"where message == c.edited:ifChatWarmSeed.waLate { throwCottonCallError(code: c.tooLate.code, message: c.tooLate.message) }iflet bubble = c.edit.bubble { sentLock.withLock { changed[message] = bubble } }return c.editcase"delete"where message == c.deleted:ifChatWarmSeed.waLate { throwCottonCallError(code: c.tooLateDelete.code, message: c.tooLateDelete.message) }iflet bubble = c.delete.bubble { sentLock.withLock { changed[message] = bubble } }return c.deletecase"deleteMine"where message == c.deletedMine: sentLock.withLock { _ = gone.insert(message) }return c.deleteMinecase"retry"where message == c.edited:iflet bubble = c.editRetried.bubble { sentLock.withLock { changed[message] = bubble } }return c.editRetriedcase"retry"where message == c.delete.message:iflet bubble = c.deleteRetried.bubble { sentLock.withLock { changed[c.deleted] = bubble } }return c.deleteRetrieddefault:returnnil } }/// The WhatsApp texts sent here, by chat: they wait for a Mac the seed has none of.privatevar waiting: [String: [ChatBubble]] = [:]/// The failed texts tried again here, by message: waiting again.privatevar retried: [String: ChatBubble] = [:]/// The sends over a slow line, by message: their chat, their bubble, their files on the phone.privatevar outbox: [String: (thread: String, bubble: ChatBubble, paths: [String])] = [:]privatevar 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 {iflet 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)) }iflet wait = ChatWarmSeed.pictureWait { try? awaitTask.sleep(for: .seconds(wait)) }ifChatWarmSeed.freed.on || ChatWarmStorage.freedHere(message) { try? awaitTask.sleep(for: .seconds(30)) }iflet 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.privatevar 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 {guardcase .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 invar part = partif part.kind == .photo, part.preview == nil { part.preview = made }return part } out.append(.bubble(bubble)) }return out }privatefunc 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? inifcase .bubble(let bubble) = item { return bubble }returnnil }guardvar bubble = bubbles.last(where: \.mine) ?? bubbles.last else { returnnil }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)) }returnChatMediaPart(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 }iflet 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.privatevar sentVoices: [String: String] = [:]privatelet marks = ChatWarmMarks()func decide(_ thread: String, _ method: String) asyncthrows {}func themes() asyncthrows -> ChatThemesAnswer { throwCancellationError() }func choose(theme: String, dark: Bool) asyncthrows -> ChatThemesAnswer { throwCancellationError() }func setText(_ id: String) asyncthrows -> ChatThemesAnswer { throwCancellationError() }func setGround(_ ground: String) asyncthrows -> ChatThemesAnswer { throwCancellationError() }/// Invented calls, in the core's words.func calls(after: String?) asyncthrows -> 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"), ]returnChatWarmRecordings.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? awaitTask.sleep(for: .seconds(ChatWarmSeed.sendPicture ?? 0))for (id, entry) in going {var bubble = entry.bubble bubble.tick = .sent bubble.quietUntil = nillet told = sentLock.withLock { () -> [AsyncStream<ChatChange>.Continuation] in outbox[id]?.bubble = bubblereturn 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? {iflet message, ChatWarmSeed.gonePictures.contains(message) { returnnil } #if canImport(UIKit)let url = FileManager.default.temporaryDirectory.appendingPathComponent("chat-warm-photo-" + (message ?? "x") + ".png")ifFileManager.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 inlet 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 #elsereturnnil #endif }/// A photo with its caption, a voice message and a file, after the chat's own words (Meera's chat).staticfunc media(after items: [ChatThreadItem]) -> [ChatThreadItem] {guardlet base = items.lazy.compactMap({ item -> ChatBubble? inifcase .bubble(let bubble) = item { return bubble }returnnil }).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 : nilreturn .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) asyncthrows -> ChatFileAnswer {// A document: an invented PDF of the fixture's words, written once, as the core writes the file it fetched.iflet document = fixture.documents?[message], let part = fixtureBubble(message)?.media.first(where: { $0.kind == .file }) {let name = part.name ?? messagelet 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)]) } } }returnChatFileAnswer(path: url.path, mime: "application/pdf", name: name, kind: "file", kept: nil) }iflet path = sentLock.withLock({ sentVoices[message] }) {returnChatFileAnswer(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.iflet voice = fixture.voice, voice.offline.contains(message) {try? awaitTask.sleep(for: .milliseconds(600))throwCottonCallError(code: "file_offline", message: voice.refusals["file_offline"] ?? "") }iflet 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? awaitTask.sleep(for: .milliseconds(400))guardlet url = ChatWarmSeed.inventedVoice(message, seconds: Double(ms) / 1_000) else { throwCancellationError() }returnChatFileAnswer(path: url.path, mime: "audio/mp4", name: nil, kind: "voice", kept: nil) }guardSelf.voices.contains(message), let made = ChatWarmSeed.recordedVoice() else { throwCancellationError() }returnChatFileAnswer(path: made.url.path, mime: "audio/mp4", name: nil, kind: "voice", kept: nil) }/// A message of the core's answers, by id.privatefunc fixtureBubble(_ message: String) -> ChatBubble? {for page in fixture.threads.values {iflet bubble = page.items.lazy.compactMap(\.bubble).first(where: { $0.message == message }) { return bubble } }returnnil }/// The voice speed as the core keeps it (the person's, synced): the fixture's, then as chosen here.privatevar speed: Double?/// Their notes played here, as the core keeps them (meta.cotton.played_at).privatevar 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.privatefunc playedApplied(_ bubble: ChatBubble) -> ChatBubble {guard sentLock.withLock({ played.contains(bubble.message) }) else { return bubble }var bubble = bubble bubble.media = bubble.media.map { part invar part = partif part.kind == .voice { part.played = nil }return part }return bubble }/// The seed's own voice messages (Meera's chat).staticlet 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 inlet token = NotificationCenter.default.addObserver(forName: .cottonChatRead, object: nil, queue: nil) { note iniflet thread = note.userInfo?["thread"] as? String { continuation.yield(.read(thread: thread)) } }let box = ChatWarmObserver(token) continuation.onTermination = { _ inNotificationCenter.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.iflet delay = ChatWarmSeed.revoke, let thread = fixture.revoke?.thread, !ChatWarmSeed.revokeComing.on {ChatWarmSeed.revokeComing.set()Task { [weakself] intry? awaitTask.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.iflet delay = ChatWarmSeed.vote, let thread = fixture.votes?.thread, !ChatWarmSeed.voteComing.on {ChatWarmSeed.voteComing.set()Task { [weakself] intry? awaitTask.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.structChatWarmSeedCore: CottonCalling {let inner: any CottonCallingstaticlet answers: [String: JSONValue] = {guardlet 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)) ?? [:] }()privatestaticlet route = ChatWarmSeed.load()?.route/// Changes answered ok, changing nothing.privatestaticlet 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) asyncthrows -> String {if method == ChatWarmSeed.slow { tryawaitTask.sleep(for: .seconds(3)) }if method == ChatWarmSeed.refused {return #"{"ok":false,"error":{"code":"not_connected","message":"not_connected"}}"# }iflet answer = ChatWarmSafety.answer(method, requestJSON, people: Self.answers) { return answer }iflet 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) {returntrySelf.ok(started) }if method == "assistant.screen", ChatWarmSeed.claudeTimed, let timed = Self.answers["seed.assistant.screen.timed"] {returntrySelf.ok(timed) }if method == ChatAgentMethod.remove, let answer = ChatWarmAgents.removed(requestJSON) { return answer }iflet answer = ChatWarmAgents.answer(method, people: Self.answers) { return answer }iflet answer = Self.answers[method] { returntrySelf.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 { returntrySelf.ok(Self.exported(requestJSON)) }iflet 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 = tryawaitSelf.linkPreviews(requestJSON, inner) { return answer }if method == "shell.settings" {var raw = tryawait inner.callRaw(method, requestJSON: requestJSON) raw = ChatWarmStorage.laid(method, raw) ?? rawiflet bytes = ChatWarmSeed.freeable, !ChatWarmSeed.freed.on { raw = Self.freeable(raw, bytes) ?? raw }return raw }if method == "shell.freeUp", ChatWarmSeed.freeable != nil {ChatWarmSeed.freed.set()returntryawait 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 = tryawait inner.callRaw(method, requestJSON: requestJSON)let seeded = Self.seeded(method, raw) ?? rawreturnChatWarmStorage.laid(method, seeded) ?? seeded }ifSelf.changes.contains(method) || method.hasPrefix("chat.group.") && !Self.answers.keys.contains(method) {return #"{"ok":true,"data":{"ok":true}}"# }returntryawait 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.privatestaticfunc linkPreviews(_ requestJSON: String, _ inner: any CottonCalling) asyncthrows -> String? {let request = (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8))) as? [String: Any] ?? [:]iflet 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 = tryawait inner.callRaw(ChatYouMethod.settings, requestJSON: ask)guardvar 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"] = datareturn (try? JSONSerialization.data(withJSONObject: whole)).map { String(decoding: $0, as: UTF8.self) } }privatestaticfunc 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.privatestaticfunc exported(_ requestJSON: String) throws -> JSONValue {let thread = (try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8)))?["thread"]?.stringlet 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)tryFileManager.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 intry? FileManager.default.copyItem(at: zipped, to: out) }iflet 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.privatestaticfunc freeable(_ raw: String, _ bytes: Int64) -> String? {guardvar 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? Stringelse { returnnil } free["bytes"] = bytes free["ask"] = label free["confirm"] = label storage["free_up"] = free data["storage"] = storage whole["data"] = datareturn (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.privatestaticfunc 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]) } }guardvar whole = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any],var data = whole["data"] as? [String: Any] else { returnnil }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 invar row = rowif row["id"] as? String == "claude", let claude { row["line"] = claude }if row["id"] as? String == "privacy", let privacy { row["line"] = privacy }return row }ifChatWarmSeed.unreachable, let sync = plain(answers["seed.chat.you.unreachable"]) { data["sync"] = sync } } whole["data"] = datareturn (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).enumChatWarmSafety {/// Asha's chat: the one whose safety answers the fixture holds.staticlet thread = "11111111-1111-4111-8111-0000000000a1"privatestaticlet fixture: JSONValue? = ChatWarmSeed.load()?.safetyprivatestaticlet held = Held()privatefinalclassHeld: @unchecked Sendable {privatelet lock = NSLock()privatevar on = falsevar verified: Bool { get { lock.withLock { on } } set { lock.withLock { on = newValue } } } }/// An invented code by its name (`theirs`, `old`, `other`).staticfunc 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.staticfunc 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 { returnnil }switch method {case"chat.safety":guardcase .object(var shown)? = held.verified ? fixture["verified"] : fixture["safety"] else { returnnil } shown["thread"] = .string(thread)return ok(.object(shown))case"chat.safety.scan":let code = request["code"]?.stringguardlet 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 ?? falsereturn ok(.object(["verified": .bool(held.verified)]))case"chat.contact":guardcase .object(var contact)? = people["chat.contact"] else { returnnil } contact["verified"] = .bool(held.verified)return ok(.object(contact))default:returnnil } }privatestaticfunc ok(_ data: JSONValue) -> String? {guardlet encoded = try? JSONEncoder().encode(data) else { returnnil }return #"{"ok":true,"data":"# + String(decoding: encoded, as: UTF8.self) + "}" }privatestaticfunc refusal(_ code: String, _ message: String) -> String? {let error: JSONValue = .object(["code": .string(code), "message": .string(message)])guardlet encoded = try? JSONEncoder().encode(error) else { returnnil }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.enumChatWarmAgents {privatestaticlet held = Held()privatefinalclassHeld: @unchecked Sendable {privatelet lock = NSLock()privatevar mine = falseprivatevar bimal = truevar yoursIn: Bool { get { lock.withLock { mine } } set { lock.withLock { mine = newValue } } }var bimalIn: Bool { get { lock.withLock { bimal } } set { lock.withLock { bimal = newValue } } } }staticfunc answer(_ method: String, people: [String: JSONValue]) -> String? {switch method {caseChatGroupMethod.info:guardcase .object(var info)? = people[method], case .array(let theirs)? = info["agents"] else { returnnil }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))caseChatAgentMethod.choices:ifChatWarmSeed.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]))caseChatAgentMethod.add: held.yoursIn = truereturn ok(.object(["ok": .bool(true)]))caseChatAgentMethod.remove:// The request names which; the seed's two are his own and Bimal's.returnnildefault:returnnil } }/// Remove: his own when it is in, else Bimal's.staticfunc removed(_ requestJSON: String) -> String? {guardlet request = try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8)) else { returnnil }if request["agent"]?.string == "agent-bimal" { held.bimalIn = false } else { held.yoursIn = false }return ok(.object(["ok": .bool(true)])) }privatestaticfunc ok(_ data: JSONValue) -> String? {guardlet encoded = try? JSONEncoder().encode(data) else { returnnil }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.enumChatWarmStorage {privatestaticlet fixture: JSONValue? = ChatWarmSeed.load()?.storage/// Each invented chat's messages, by thread.privatestaticlet messages: [String: Set<String>] = (ChatWarmSeed.load()?.threads ?? [:]).mapValues { Set($0.items.compactMap { $0.bubble?.message }) }privatestaticlet held = Held()privatefinalclassHeld: @unchecked Sendable {privatelet lock = NSLock()privatevar chat: String?var freed: String? { get { lock.withLock { chat } } set { lock.withLock { chat = newValue } } } }privatestaticvar state: JSONValue? {iflet 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).staticfunc freedHere(_ message: String) -> Bool {guardlet thread = held.freed else { returnfalse }if thread == ChatWarmSeed.mediaThread, message.hasPrefix("m-media-") { returntrue }return messages[thread]?.contains(message) ?? false }staticfunc answer(_ method: String, _ requestJSON: String) -> String? {guardlet fixture else { returnnil }switch method {caseChatYouMethod.storage:return state?["chats"].flatMap(ok)caseChatYouMethod.storageFree:guardlet 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 { returnnil } held.freed = threadreturn ok(said)default:returnnil } }/// The core's own answer with the fixture's totals (`shell.settings`) or Storage line (`chat.you`) laid over it.staticfunc laid(_ method: String, _ raw: String) -> String? {guardlet state, var whole = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any],var data = whole["data"] as? [String: Any] else { returnnil }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 } elseif method == ChatYouMethod.you, let line = state["row"]?.string { data["rows"] = ((data["rows"] as? [[String: Any]]) ?? []).map { row invar row = rowif row["id"] as? String == "storage" { row["line"] = line }return row } } else {returnnil } whole["data"] = datareturn (try? JSONSerialization.data(withJSONObject: whole)).map { String(decoding: $0, as: UTF8.self) } }privatestaticfunc ok(_ data: JSONValue) -> String? {guardlet encoded = try? JSONEncoder().encode(data) else { returnnil }return #"{"ok":true,"data":"# + String(decoding: encoded, as: UTF8.self) + "}" }}#if canImport(UIKit)importSwiftUI/// A call engine that only draws: the preview's (`-chat-warm-call`).@MainActorfinalclassChatWarmSeedCalls: 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.enumChatWarmRecordings {privatestaticlet fixture: JSONValue? = {guardlet url = Bundle.module.url(forResource: "chat-warm-recordings", withExtension: "json", subdirectory: "Fixtures"),let data = try? Data(contentsOf: url) else { returnnil }returntry? JSONDecoder().decode(JSONValue.self, from: data) }()privatestaticlet held = Held()privatefinalclassHeld: @unchecked Sendable {privatelet lock = NSLock()privatevar 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.staticfunc calls(_ answer: ChatCallsAnswer) -> ChatCallsAnswer {guardlet calls = fixture?["calls"] else { return answer }var out = answer out.words.record = calls["record"]?.string out.words.import = calls["import"]?.stringlet days = calls["days"]let notes = calls["notes"]var rows = answer.rows.map { row -> ChatCallRowinvar row = row row.kind = "call" row.day = days?[row.call]?.string row.recording = notes?[row.call]?.stringreturn row }for entry in calls["recordings"]?.array ?? [] {guardlet made = entry["row"].flatMap({ try? JSONEncoder().encode($0) }),let row = try? JSONDecoder().decode(ChatCallRow.self, from: made) else { continue }iflet 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 = rowsreturn out }/// The envelope for a recordings ask; nil for anything else.staticfunc answer(_ method: String, _ requestJSON: String) -> String? {guardlet fixture, let request = try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8)) else { returnnil }switch method {caseChatRecordingMethod.page:return request["id"]?.string.flatMap(page).map { tooled($0, query: request["query"]?.string) }.flatMap(ok)caseChatRecordingMethod.act:guardlet id = request["id"]?.string, case .object(var shown)? = page(id), let act = request["act"]?.string else { returnnil }let said = fixture["said"]?[act] ?? .nullswitch act {case"export":return exported(.object(shown), format: request["format"]?.string ?? "text")case"delete":return ok(.object(["deleted": .bool(true), "said": said]))case"title":iflet 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).ifcase .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":ifcase .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"]?.stringifcase .array(let actions)? = shown["actions"] { shown["actions"] = .array(actions.map { item inguard item["id"]?.string == action, case .object(var made) = item else { return item } made["added"] = .bool(true) made["act"] = .null made["said"] = saidreturn .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))caseChatRecordingMethod.live:guardcase .object(var live)? = fixture["live"] else { returnnil }let seconds = (request["duration_ms"]?.int ?? 0) / 1000 live["time"] = .string(String(format: "%d:%02d", seconds / 60, seconds % 60))return ok(.object(live))caseChatRecordingMethod.importFile:let meeting = "rec-import-" + UUID().uuidString.prefix(8)return ok(.object(["meeting": .string(meeting), "status": .string("waiting"), "said": fixture["said"]?["import"] ?? .null]))caseCottonMethod.mediaEnsure:guard request["key"]?.string?.hasPrefix("seed-") == true, let path = Bundle.module.url(forResource: "chat-warm-voice", withExtension: "m4a", subdirectory: "Fixtures")?.path else { returnnil }return ok(.object(["path": .string(path)]))caseMeetingsMethod.recordStart:let id = request["id"]?.string ?? UUID().uuidStringlet path = FileManager.default.temporaryDirectory.appendingPathComponent("seed-\(id).wav").pathreturn ok(.object(["meeting": .string(id), "audio_path": .string(path), "started_at": .string(ISO8601DateFormatter().string(from: Date()))]))caseMeetingsMethod.recordTick, MeetingsMethod.recordStop:return ok(.object(["ok": .bool(true)]))default:returnnil } }/// 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.privatestaticfunc tooled(_ shown: JSONValue, query: String?) -> JSONValue {guardcase .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"] ?? .nulllet 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 NSStringvar parts: [JSONValue] = []var at = 0var 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.privatestaticfunc 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.privatestaticfunc page(_ id: String) -> JSONValue? {iflet kept = held.page(id) { return kept }iflet page = fixture?["pages"]?[id] { return page }guardcase .object(var made)? = fixture?["pages"]?["rec-garden"] else { returnnil } made["id"] = .string(id)return .object(made) }privatestaticfunc ok(_ answer: JSONValue) -> String? {guardlet data = try? JSONEncoder().encode(answer) else { returnnil }return #"{"ok":true,"data":"# + String(decoding: data, as: UTF8.self) + "}" }}#endif