// Cotton Chat's screen models: what the list and a thread hold of the // core's answers, and how a change lands — one row or one bubble, never the // whole screen. The models decide nothing the core says; they only keep // pages, cursors and what is in flight. #if os(iOS) import CottonKit import Foundation import Observation import os /// How long the screens took, kept for the lane's report and a walk. enum ChatSpeed { static let log = Logger(subsystem: "com.cottondb.chat", category: "speed") @MainActor static var marks: [String: Double] = [:] @MainActor static func mark(_ name: String, since start: ContinuousClock.Instant) { let ms = Double((ContinuousClock.now - start).components.attoseconds) / 1e15 + Double((ContinuousClock.now - start).components.seconds) * 1000 marks[name] = ms log.notice("\(name, privacy: .public) \(ms, format: .fixed(precision: 1), privacy: .public) ms") } } // MARK: the list @MainActor @Observable final class ChatListModel { private(set) var filter: String private(set) var search = "" private(set) var rows: [ChatListRow] = [] private(set) var words: ChatListWords? private(set) var fan: [ChatFanTile] = [] /// The filters above the list, as the core answers them. private(set) var filters: [ChatFanTile] = [] /// How many conversations are archived (Archived stands at the foot when any are). private(set) var archived = 0 private(set) var next: String? private(set) var failed: String? /// Bumped whenever rows change; the table diffs against it. private(set) var revision = 0 /// When a chat's next message goes by its timer (the core's `erasesIn`, from when the answer came): asked again then. private(set) var erasesAt: Date? private let book: any ChatBook private var asks = 0 private var loadingMore = false /// The last answer per filter, so a list opened again draws at once. private static var warm: [String: ChatListAnswer] = [:] init(book: any ChatBook, filter: String) { self.book = book self.filter = filter if let warm = Self.warm[filter] { take(warm) } } func load() async { let start = ContinuousClock.now await read() ChatSpeed.mark("list.drawn", since: start) } /// Something landed: the list is asked again and only rows that changed move. func refresh() async { await read() } func set(search: String) async { guard search != self.search else { return } self.search = search await read() } private func read() async { asks += 1 let asked = asks do { let answer = try await book.list(ChatListAsk(filter: filter, search: search.isEmpty ? nil : search)) guard asked == asks else { return } if search.isEmpty { Self.warm[filter] = answer } take(answer) // Who is no longer on Cotton, said on their rows (CIRCLE 2). let people = rows.filter { !$0.group }.map(\.thread) Task { await ChatCircleGone.shared.read(threads: people) } } catch { failed = String(describing: error) } } func loadMore() async { guard let next, !loadingMore else { return } loadingMore = true defer { loadingMore = false } guard let answer = try? await book.list(ChatListAsk(filter: filter, search: search.isEmpty ? nil : search, after: next)) else { return } let have = Set(rows.map(\.thread)) rows += answer.rows.filter { !have.contains($0.thread) } self.next = answer.next revision += 1 } private func take(_ answer: ChatListAnswer) { rows = answer.rows words = answer.words fan = answer.fan filters = answer.filters archived = answer.counts.archived next = answer.next erasesAt = answer.erasesIn.map { Date().addingTimeInterval($0 / 1_000) } failed = nil revision += 1 } /// One row changed: replaced where it stands when its place holds, else /// the list is asked again and only the rows that moved move. func apply(_ row: ChatListRow) async { if let at = rows.firstIndex(where: { $0.thread == row.thread }) { let old = rows[at] let samePlace = old.pinned == row.pinned && old.archived == row.archived && old.when == row.when && old.lastLine == row.lastLine && keeps(row) if samePlace { rows[at] = row revision += 1 return } } await read() } private func keeps(_ row: ChatListRow) -> Bool { switch filter { case "unread": row.unread > 0 || row.markedUnread case "archived": row.archived default: !row.archived } } /// A swipe's act; the row the core answers replaces the old one. A deleted chat leaves the list the moment the /// core answers (FEEDBACK-4 B2), before the list is asked again; a refusal is said, never swallowed. func act(_ swipe: ChatSwipe, on row: ChatListRow) async -> String? { let answer: ChatActAnswer do { answer = try await book.act(ChatActAsk(act: swipe.act, thread: row.thread)) } catch let refusal as CottonCallError { return refusal.message } catch { return nil } if swipe.act == "deleteChat" { rows.removeAll { $0.thread == row.thread } revision += 1 } if let row = answer.row { await apply(row) } else { await read() } return answer.said } func row(_ thread: String) -> ChatListRow? { rows.first { $0.thread == thread } } } // MARK: a thread /// One item as the thread's table draws it, with an identity that holds /// across pages (a divider is named by what follows it). struct ChatDrawn: Hashable, Sendable { var id: String var item: ChatThreadItem } @MainActor @Observable final class ChatThreadModel { struct Page: Sendable { var items: [ChatDrawn] var older: String? var newer: String? } let thread: String private(set) var header: ChatHeader? /// Not on Cotton yet, and how many of the person's messages wait (`chat.thread`'s `reach`). private(set) var reach: ChatReach? private(set) var pinned: ChatPinnedBar? private(set) var actions: ChatActionWords? private(set) var composer: ChatComposeAnswer? private(set) var readOnly: String? /// "Loading this chat…" while the first pull runs and nothing of this chat has come (`chat.thread`'s `loading`). private(set) var loading: String? private(set) var request: ChatAskCard? private(set) var jump: ChatJump? /// Pages oldest first; the window holds at most `window` of them. private(set) var pages: [Page] = [] /// The message to scroll to and flash. private(set) var focus: String? /// Bumped each time the person's own message lands here from Send: the chat goes down to it, wherever the /// reader stood (a reply written to a message far above is seen, with its quote, once sent). private(set) var sentHere = 0 /// Bumped on every change to the items; carries what changed. private(set) var revision = 0 private(set) var change: Change = .all /// Messages that came in below the window while the reader was away. private(set) var arrivedBelow = 0 private(set) var said: String? /// How `said` stands: a refusal is an error's toast, which takes the lines a long reason needs at the largest /// text (a notice's three cut "Only pictures, videos and voice notes go to WhatsApp for now."). private(set) var saidTone: CottonToast.Tone = .notice /// Pictures picked and waiting in the writing box: Send takes them with what is written as their caption. private(set) var attached: [ChatAttachment] = [] /// Bumped each time the core refuses a send: the writing box puts back what was written. private(set) var refusedSends = 0 /// The chat's disappearing timer, as `chat.thread` answers it (none where the core answers none). private(set) var timer: ChatTimerCard? /// When this chat's next message goes (the core's `erasesIn`, counted from when the answer came): asked again then. private(set) var erasesAt: Date? /// The card fetched here for the link in what is written (FEEDBACK-4 B4): it stands above the writing box and goes /// with the send. private(set) var card: ChatLinkCard? /// Links whose card he closed: offered none again in this message. private var closedLinks: Set = [] enum Change: Equatable { case all case appendedOlder case appendedNewer case bubbles(Set) } static let window = 8 /// The id a WhatsApp text on its way through the Mac carries until it stands as a message. nonisolated static let pending = "outbox:" private let book: any ChatBook private var loadingOlder = false private var loadingNewer = false private var composeAsks = 0 private static var warm: [String: ChatThreadAnswer] = [:] init(book: any ChatBook, thread: String) { self.book = book self.thread = thread if let warm = Self.warm[thread] { take(warm) } } var items: [ChatDrawn] { pages.flatMap(\.items) } var older: String? { pages.first?.older } var newer: String? { pages.last?.newer } var atNewest: Bool { pages.last.map { $0.newer == nil } ?? true } /// The bubble with this message, wherever it is in the window. func bubble(_ message: String) -> ChatBubble? { for page in pages { for d in page.items where d.id == message { return d.item.bubble } } return nil } func open() async { let start = ContinuousClock.now guard let answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { return } Self.warm[thread] = answer take(answer) ChatSpeed.mark("thread.drawn", since: start) } private func take(_ answer: ChatThreadAnswer) { header = answer.header reach = answer.reach pinned = answer.pinned actions = answer.actions composer = answer.composer ?? composer.flatMap { answer.readOnly == nil ? $0 : nil } readOnly = answer.readOnly request = answer.request loading = answer.loading jump = answer.jump focus = answer.focus timer = answer.timer erasesAt = answer.erasesIn.map { Date().addingTimeInterval($0 / 1_000) } pages = [Page(items: Self.drawn(answer.items), older: answer.older, newer: answer.newer)] arrivedBelow = 0 change = .all revision += 1 } /// The page above the oldest held, asked ahead of the finger. func loadOlder() async { guard let older, !loadingOlder else { return } loadingOlder = true defer { loadingOlder = false } guard let answer = try? await book.thread(ChatThreadAsk(thread: thread, before: older)) else { return } pages.insert(Page(items: Self.drawn(answer.items), older: answer.older, newer: answer.newer), at: 0) if pages.count > Self.window { pages.removeLast(pages.count - Self.window) } change = .appendedOlder revision += 1 } /// The page below the newest held (after a jump into the past). func loadNewer() async { guard let newer, !loadingNewer else { return } loadingNewer = true defer { loadingNewer = false } guard let answer = try? await book.thread(ChatThreadAsk(thread: thread, after: newer)) else { return } pages.append(Page(items: Self.drawn(answer.items), older: answer.older, newer: answer.newer)) if pages.count > Self.window { pages.removeFirst(pages.count - Self.window) } jump = answer.jump if answer.newer == nil { arrivedBelow = 0 } change = .appendedNewer revision += 1 } func jumpToLatest() async { guard let answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { return } take(answer) jump = nil } func go(to message: String) async { guard let answer = try? await book.thread(ChatThreadAsk(thread: thread, around: message)) else { return } take(answer) } func flashed() { focus = nil } // MARK: composing private var attachedCount: Int? { attached.isEmpty ? nil : attached.count } func type(_ text: String) async { composeAsks += 1 let asked = composeAsks // While an edit's strip stands, the words are that message's new words (the core keeps no edit between asks). let editing = composer?.strip.flatMap { $0.kind == .edit ? $0.message : nil } guard let answer = try? await book.compose(ChatComposeAsk(thread: thread, text: text, edit: editing, attached: attachedCount)) else { return } if asked == composeAsks { composer = answer } } func reply(to message: String) async { if let answer = try? await book.compose(ChatComposeAsk(thread: thread, replyTo: message, attached: attachedCount)) { composer = answer } } /// The edit strip over the writing box, the message's words in the field; a refusal is said in the core's words. func edit(_ message: String) async { do { composer = try await book.compose(ChatComposeAsk(thread: thread, edit: message)) } catch let refusal as CottonCallError { refused(refusal.message) } catch {} } func cancelStrip() async { if let answer = try? await book.compose(ChatComposeAsk(thread: thread, cancel: true, attached: attachedCount)) { composer = answer } } /// Pictures picked: they wait in the writing box for their caption, and the core says Send is live. func attach(_ files: [ChatAttachment]) async { guard !files.isEmpty else { return } attached += files await type(composer?.text ?? "") } /// The waiting pictures taken out of the box (its Cancel). func unattach() async { attached = [] await type(composer?.text ?? "") } /// What waits in the box, taken once by Send. func takeAttached() -> [ChatAttachment] { defer { attached = [] } return attached } /// A voice message let go: it goes at once, like any message (never /// waiting for its words). Then the words this phone hears in it, on the /// device only, follow as a change to it (`chat.act transcript`), and its /// bubble carries them under the player. None heard, nothing follows. func sendVoice(_ voice: ChatAttachment) async { guard let message = await send("", attachments: [voice]) else { return } let file = URL(fileURLWithPath: voice.path) Task { [weak self] in guard let words = await ChatVoiceWords.heard(in: file), let self else { return } guard let answer = try? await self.book.act(ChatActAsk(act: "transcript", thread: self.thread, message: message, text: words)) else { return } if let bubble = answer.bubble { self.replace(bubble) } if answer.flush { Task.detached(priority: .utility) { [book = self.book] in await book.flush() } } } } /// Sends what is written. The bubble the core answers lands at once, /// before the network; the flush goes off the main thread. Answers the message sent. /// With the core's reply strip standing, the send answers that message (`replyTo`), so the bubble quotes it; /// with its edit strip, the words change that message instead (`chat.act edit`). @discardableResult func send(_ text: String, attachments: [ChatAttachment] = []) async -> String? { let start = ContinuousClock.now composeAsks += 1 let strip = composer?.strip if let strip, strip.kind == .edit, attachments.isEmpty { do { let answer = try await book.act(ChatActAsk(act: "edit", thread: thread, message: strip.message, text: text)) if let bubble = answer.bubble { replace(bubble) } if answer.flush { Task.detached(priority: .utility) { [book] in await book.flush() } } } catch let refusal as CottonCallError { refused(refusal.message) } catch {} if let composer = try? await book.compose(ChatComposeAsk(thread: thread, text: "", cancel: true)) { self.composer = composer } return strip.message } // The card standing for a link still in the words goes with them (FEEDBACK-4 B4); the core checks it. // A file sent at once with no words of its own leaves the words still being written, and their card, standing. let card = self.card.flatMap { text.contains($0.url) ? $0 : nil } if !text.isEmpty { self.card = nil closedLinks = [] } let ask = ChatActAsk(act: "send", thread: thread, text: text.isEmpty ? nil : text, attachments: attachments.isEmpty ? nil : attachments, replyTo: strip?.kind == .reply ? strip?.message : nil, preview: card) let answer: ChatActAnswer do { answer = try await book.act(ask) } catch let refusal as CottonCallError { // Refused (a file too large for WhatsApp, a kind it does not take yet): said in the core's words, and what // was picked goes back in the box beside the words, so a second tap sends them (as Android, a592647355). attached = attachments.filter { $0.kind != "voice" } + attached refused(refusal.message) refusedSends += 1 // A file picked with Files goes at once with no words of its own, so the words still being written stay // the draft; a Send from the box gives its words back. await type(text.isEmpty ? composer?.text ?? "" : text) return nil } catch { return nil } if let bubble = answer.bubble { if answer.message.map({ self.bubble($0) != nil }) ?? false { replace(bubble) } else if atNewest { place(bubble) } else { await jumpToLatest() } sentHere += 1 } // One tap to WhatsApp can be several messages (a file a message; a document's words go first as their own // text), and the core answers the first one's bubble only: the chat is read again, so each stands at once. if answer.message?.hasPrefix(Self.pending) == true, !attachments.isEmpty { await reread() } if let composer = try? await book.compose(ChatComposeAsk(thread: thread, text: "")) { self.composer = composer } ChatSpeed.mark("send.drawn", since: start) if answer.flush { Task.detached(priority: .utility) { [book] in await book.flush() } } return answer.message } // MARK: link previews /// The card for the link the core offers in what is written (`composer.preview`, FEEDBACK-4 B4): fetched by this /// phone (the page, read by the core; then its picture, made small), unless he closed it. A link no longer offered /// drops its card. Run as the writing box's task for that link, so a link changed mid-fetch is never shown. func fetchCard(_ url: String?) async { guard let url, !closedLinks.contains(url) else { card = nil; return } if card?.url == url { return } card = nil guard let page = await ChatLinkFetch.page(url), !Task.isCancelled, let read = await book.linkCard(thread: thread, url: url, page: page), let title = read.title, !Task.isCancelled else { return } var thumb: String? if let image = read.image { thumb = await ChatLinkFetch.thumb(image) } guard !Task.isCancelled, composer?.preview?.url == url, !closedLinks.contains(url) else { return } card = ChatLinkCard(url: url, site: read.site, title: title, description: read.description, thumb: thumb) } /// He closed the card: that link offers none again in this message. func closeCard() { if let url = card?.url { closedLinks.insert(url) } card = nil } /// Any of `chat.act`'s acts on a message: the bubble answered replaces its own. A refusal (a delete for everyone /// past WhatsApp's window) is said in the core's words. func act(_ act: String, message: String? = nil, messages: [String]? = nil, emoji: String? = nil, to: [String]? = nil) async { let answer: ChatActAnswer do { answer = try await book.act(ChatActAsk(act: act, thread: thread, message: message, messages: messages, emoji: emoji, to: to)) } catch let refusal as CottonCallError { refused(refusal.message) return } catch { return } if let bubble = answer.bubble { replace(bubble) } saidTone = .notice said = answer.said if act == "pin" || act == "unpin" { // The pinned bar is the thread's, not the bubble's: read it again. if let fresh = try? await book.thread(ChatThreadAsk(thread: thread, around: message)) { pinned = fresh.pinned } } // A WhatsApp message deleted is erased, a marker in its place (the answer names the marker, not the message), // or nothing at all for Delete for me: the chat is read again (CONTRACT.md "Editing and deleting his own message"). if act == "deleteMine" || (act == "delete" && answer.message != nil && answer.message != message) { await reread() } } /// A poll he made on its sheet (`chat.act poll`, CONTRACT.md "Making a poll"): the core checks it and queues it, /// and its card stands at once, "Waiting to send". A refusal is said in the core's words. Whether it went. func makePoll(question: String, options: [String], many: Bool) async -> Bool { var ask = ChatActAsk(act: "poll", thread: thread) ask.question = question ask.options = options ask.many = many let answer: ChatActAnswer do { answer = try await book.act(ask) } catch let refusal as CottonCallError { refused(refusal.message) return false } catch { return false } if let bubble = answer.bubble { if atNewest { place(bubble) } else { await jumpToLatest() } sentHere += 1 } if answer.flush { Task.detached(priority: .utility) { [book] in await book.flush() } } return true } /// A tap on option `option` of a WhatsApp poll he can vote on (`chat.act vote`, CONTRACT.md "A vote"): the core /// works out his choice and draws it at once on the poll it answers, "Vote waiting to send"; a refusal is said in /// the core's words. The phone decides nothing. func vote(_ message: String, option: Int) async { var ask = ChatActAsk(act: "vote", thread: thread, message: message) ask.option = option do { let answer = try await book.act(ask) if let bubble = answer.bubble { replace(bubble) } if answer.flush { Task.detached(priority: .utility) { [book] in await book.flush() } } } catch let refusal as CottonCallError { refused(refusal.message) } catch {} } func heard() { said = nil } /// A refusal, said in the core's words as an error. private func refused(_ words: String) { saidTone = .error said = words } /// The chat's disappearing timer set (`chat.act timer`, CONTRACT.md "Disappearing messages"): the core writes the /// chat's line at once and what it queued for the other side goes with the next flush; the chat is read again, /// its line, its header's status and its timer with it. A refusal is said in the core's words. func setTimer(_ seconds: Int) async { do { var ask = ChatActAsk(act: "timer", thread: thread) ask.seconds = seconds let answer = try await book.act(ask) if answer.flush { Task.detached(priority: .utility) { [book] in await book.flush() } } } catch { refused(ActionRefused.words(for: error)) } guard let answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { return } Self.warm[thread] = answer if atNewest { mergeNewest(answer) } else { header = answer.header; timer = answer.timer } } /// A failed message tried again: back in the outbox (`chat.act retry`), /// its bubble answered at once, then sent off the main thread. /// A refusal (a WhatsApp text still waiting is `cannot`) is said in the core's words. func retry(_ message: String) async { let answer: ChatActAnswer do { answer = try await book.act(ChatActAsk(act: "retry", thread: thread, message: message)) } catch let refusal as CottonCallError { refused(refusal.message) return } catch { return } if let bubble = answer.bubble { replace(bubble) } if answer.flush { Task.detached(priority: .utility) { [book] in await book.flush() } } } /// The chat asked again as it shows and on sync (a WhatsApp text's state moves on the Mac, and its pending /// bubble leaves once the sent message stands): the newest page merged, only what changed drawn again. func reread() async { guard atNewest, !pages.isEmpty, let answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { return } Self.warm[thread] = answer mergeNewest(answer) } /// The thread is on screen: theirs are stamped read (`chat.act read`), /// and when the core answers `flush` the person's other phones are told /// by the next `chat.flush`, off the main thread as a send's is. What /// the read changed is said to the list (its row) and to the /// notifications, which ask `chat.notices` again. func markRead() async { guard let answer = try? await book.act(ChatActAsk(act: "read", thread: thread)) else { return } if answer.flush { Task.detached(priority: .utility) { [book] in await book.flush() } } var info: [String: Any] = ["thread": thread] if let row = answer.row { info["row"] = row } NotificationCenter.default.post(name: .cottonChatRead, object: nil, userInfo: info) } private func place(_ bubble: ChatBubble) { // The bubble before it, if its run lost its tail, arrives as its own // change from the core: the phone never regroups. guard !pages.isEmpty else { return } pages[pages.count - 1].items.append(ChatDrawn(id: bubble.message, item: .bubble(bubble))) change = .appendedNewer revision += 1 } private func replace(_ bubble: ChatBubble) { for p in pages.indices { if let at = pages[p].items.firstIndex(where: { $0.id == bubble.message }) { pages[p].items[at].item = .bubble(bubble) change = .bubbles([bubble.message]) revision += 1 return } } } /// A change the core streamed: one bubble, or news below. func apply(_ change: ChatChange) async { switch change { case .bubble(let thread, let bubble) where thread == self.thread: replace(bubble) case .arrived(let thread) where thread == self.thread: guard atNewest, let answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { arrivedBelow += 1 return } mergeNewest(answer) default: break } } /// The newest page read again: what is new is appended and what changed is replaced, so only those bubbles draw /// again. What the page no longer names has left (erased by its timer, deleted in WhatsApp, a text on its way that /// now stands as a message), and a new item amid the held ones (a deleted message's marker, in its place) means the /// span is laid again in the core's order: a message never lingers after the core has erased it. private func mergeNewest(_ answer: ChatThreadAnswer) { let fresh = Self.drawn(answer.items) let held = Dictionary(items.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) guard let firstHeld = fresh.firstIndex(where: { held[$0.id] != nil }) else { take(answer) return } defer { header = answer.header reach = answer.reach timer = answer.timer erasesAt = answer.erasesIn.map { Date().addingTimeInterval($0 / 1_000) } } let tail = Array(fresh[firstHeld...]) if let (p, i) = position(of: tail[0].id), Self.laidAgain(held: pages[p...].enumerated().flatMap { k, page in (k == 0 ? Array(page.items[i...]) : page.items).map(\.id) }, tail: tail.map(\.id)) { pages[p].items = Array(pages[p].items[.. = [] var appended: [ChatDrawn] = [] for d in tail { if let old = held[d.id] { if old != d { changed.insert(d.id) } } else { appended.append(d) } } for id in changed { if let d = tail.first(where: { $0.id == id }), let bubble = d.item.bubble { replace(bubble) } } if !appended.isEmpty, !pages.isEmpty { pages[pages.count - 1].items += appended change = .appendedNewer revision += 1 } } /// Where an item stands in the window: its page and its place there. private func position(of id: String) -> (Int, Int)? { for p in pages.indices { if let i = pages[p].items.firstIndex(where: { $0.id == id }) { return (p, i) } } return nil } /// Whether the newest span must be laid again from the core's answer: something held there is no longer named, /// the held ones stand in another order, or something new stands amid them rather than after them. nonisolated static func laidAgain(held: [String], tail: [String]) -> Bool { let now = Set(tail) if held.contains(where: { !now.contains($0) }) { return true } let had = Set(held) if tail.filter({ had.contains($0) }) != held { return true } guard let last = tail.lastIndex(where: { had.contains($0) }) else { return false } return tail[.. [ChatDrawn] { var out: [ChatDrawn] = [] out.reserveCapacity(items.count) var pending: [ChatThreadItem] = [] for item in items { switch item { case .day, .unread: pending.append(item) case .event(let message, _, _, _, _): for p in pending { out.append(ChatDrawn(id: "\(prefix(p))\(message)", item: p)) } pending = [] out.append(ChatDrawn(id: "event:\(message)", item: item)) case .bubble(let b): for p in pending { out.append(ChatDrawn(id: "\(prefix(p))\(b.message)", item: p)) } pending = [] out.append(ChatDrawn(id: b.message, item: item)) } } for (i, p) in pending.enumerated() { out.append(ChatDrawn(id: "\(prefix(p))end\(i)", item: p)) } return out } private static func prefix(_ item: ChatThreadItem) -> String { if case .unread = item { return "unread@" } return "day@" } } #endif