// What a conversation page holds while it is on screen: the thread's// messages — the records of the definition's `conversation.table` whose link// columns name the thread — oldest first, and the one write the page makes,// a message sent from its input. The send goes through the act the layout// names (`send`) where it names one, else through the `create` verb like every// other write, and the list is read again after it.//// The messages are read narrowed by the `list` verb's `where`, once per link// column (a message names its thread on any of them, and `where` matches all// it is given), and the reads are merged by record id. Only the latest page// of messages is read at first; older history is read a page at a time on// request, and no more than a thousand messages are ever held.//// A definition's `also` tables (a session's turns beside its messages) are// read the same way and merged into one stream, `items`: by moment, a turn// before a message at the same instant, each table keeping its own order on a// tie — the order `SessionFacts.chat` drew a session's transcript in. Nothing// is ever sent into an `also` table. An `also` table whose face is `slip`// (a session's runs) takes its place in the same stream by its moment and is// drawn as its own table's slip, between the notes.importCottonValuesimportFoundationimportObservation@MainActor@ObservablepublicfinalclassConversationModel {publicenumPhase: Equatable {case loadingcase loadedcase failed }publiclet layout: ConversationLayout/// The thread's record id.publiclet thread: Stringpublicprivate(set) var messages: [TableRecord] = []/// The messages and every `also` table's records, merged into the one/// stream the page draws.publicprivate(set) var items: [ConversationItem] = []publicprivate(set) var phase: Phase = .loading/// A send on its way: the input waits for it.publicprivate(set) var sending = falsepublicprivate(set) var retrying: Set<String> = []publicprivate(set) var binning: Set<String> = []publicvar threadRecord: TableRecord?/// The message a Cotton chat's next message answers, while the composer says so.publicvar replyingTo: TableRecord?/// The newest message sent from this page, for its receipt, until it is/// dismissed or the next send replaces it.publicprivate(set) var lastChange: ChangeRecord?/// The change the receipt took back, so a receipt drawn again for it/// reads as undone rather than offering its Undo a second time.privatevar undoneChange: String?/// Whether `lastChange` was taken back by its receipt.publicvar lastChangeUndone: Bool { lastChange.map { $0.id == undoneChange } ?? false }privatelet store: any Recordsprivatevar generation = 0privatevar nextPages: [String: Int] = [:]privatevar loadingMore = false/// The `also` tables' records as last read, so a page of older messages/// merges into the same stream.privatevar others: [[TableRecord]] = []/// The message table's definition, which words a note whose body is blank.privatelet wording: TableDefinition?/// The older pages the reader asked for (`loadMore`), kept across a read again.privatevar paged: [TableRecord] = []publicvar hasMore: Bool { !nextPages.isEmpty && messages.count < 1000 }publicinit( layout: ConversationLayout, thread: String, store: any Records, threadRecord: TableRecord? = nil, wording: TableDefinition? = nil ) {self.wording = wordingself.layout = layoutself.thread = threadself.store = storeself.threadRecord = threadRecord }/// Reads the latest page of the thread's messages, leaving older history/// for an explicit request (`loadMore`), and every `also` table's records,/// replacing what is shown. A read that fails after messages were shown/// keeps them. `anchor`, the message the page opens on, is read too when/// the latest page does not hold it.publicfunc load(anchor: String? = nil) async { generation += 1let mine = generationdo {var found: [TableRecord] = []var next: [String: Int] = [:]for link in layout.links {let read = tryawait store.list(table: layout.table, project: nil, query: nil, page: 0, where: [link: .text(thread)]) found.append(contentsOf: read.records)iflet page = read.next { next[link] = page } }iflet anchor, !found.contains(where: { $0.id == anchor }),let target = tryawait store.get(table: layout.table, id: anchor), layout.links.contains(where: { target[$0].text == thread }) { found.append(target) }guard mine == generation, !Task.isCancelled else { return }// A read again (a sync, a live cadence) keeps the older pages the// reader already asked for: only the latest page was read, and// dropping the rest would throw the reader back to the foot.let all = paged.isEmpty ? merged(found) : merged(found + paged)// Nothing moved: nothing is published, so the page is not redrawn// under a reader who has scrolled up.if all != messages { messages = all }if paged.isEmpty { nextPages = next }// The newest page is drawn now, beside the `also` records last// read: a session's turns, every page of them, fill in after and// never hold its messages back. publish()guard !layout.also.isEmpty else { return }var others: [[TableRecord]] = []for source in layout.also { others.append(tryawait read(source.table, links: source.links)) }guard mine == generation, !Task.isCancelled else { return }if others != self.others { self.others = others } publish() } catch {guard mine == generation, !(error isCancellationError) else { return }if messages.isEmpty && items.isEmpty { phase = .failed } } }/// The one stream the page draws, from the messages and `also` records held.privatefunc publish() {let drawn = layout.merged(messages: messages, also: others, wording: wording)if drawn != items { items = drawn }if phase != .loaded { phase = .loaded } }/// Older history is paged, with the previous screen's thousand-message cap.publicfunc loadMore() async {guard hasMore, !loadingMore else { return } loadingMore = truedefer { loadingMore = false }do {var found: [TableRecord] = []var next = nextPagesfor (link, page) in nextPages.sorted(by: { $0.key < $1.key }) {let read = tryawait store.list(table: layout.table, project: nil, query: nil, page: page, where: [link: .text(thread)]) found.append(contentsOf: read.records) next[link] = read.next }// A read again that landed meanwhile does not throw the older// page away: it is merged into whatever is shown now.guard !Task.isCancelled else { return } paged.append(contentsOf: found) messages = merged(messages + found) nextPages = next items = layout.merged(messages: messages, also: others, wording: wording) } catch { /* A failed older-page read retains the current messages and cursor. */ } }privatefunc merged(_ records: [TableRecord]) -> [TableRecord] {var seen: Set<String> = []returnArray(layout.ordered(records.filter { seen.insert($0.id).inserted }).suffix(1000)) }/// Every record of `table` naming the thread on any of `links`, merged by/// id, in the order the reads answered.privatefunc read(_ table: String, links: [String]) asyncthrows -> [TableRecord] {var found: [TableRecord] = []var seen: Set<String> = []for link in links {var page: Int? = 0whilelet current = page {let read = tryawait store.list( table: table, project: nil, query: nil, page: current, where: [link: .text(thread)])for record in read.records where seen.insert(record.id).inserted { found.append(record) } page = read.next } }return found }/// Writes `words` as the owner's message to the thread and reads the/// thread again; nil when there is nothing to send or a send is already/// on its way. @discardableResultpublicfunc send(_ words: String) asyncthrows -> ChangeRecord? {guardlet data = layout.sent(words, thread: thread, record: threadRecord), !sending else { returnnil } sending = truedefer { sending = false }let change = tryawait store.create(table: layout.table, data: data)if layout.usesLocalQueue { receive(change, words: words.trimmingCharacters(in: .whitespacesAndNewlines)) lastChange = nil } else { lastChange = change }await load()return change }/// Failure actions require an unbinned local outgoing slip and conversation.publicfunc canRetryOrBin(_ message: TableRecord) -> Bool {iflet threadRecord, !threadRecord["trashed_at"].isNull { returnfalse }guard layout.usesLocalQueue, message["trashed_at"].isNull,case .failed? = MessageDelivery(message) else { returnfalse }returntrue }/// Retry the same failed slip. The engine validates the transition and/// owns the attempt count and external id; no new message is created. @discardableResultpublicfunc retry(_ message: TableRecord) asyncthrows -> ChangeRecord? {guard canRetryOrBin(message), !binning.contains(message.id), !retrying.contains(message.id) else { returnnil } retrying.insert(message.id)defer { retrying.remove(message.id) }let change = tryawait store.update(table: layout.table, id: message.id, patch: ["send_state": .text("queued")]) receive(change) lastChange = nilawait load()return change }/// The local engine puts only failed outgoing messages in the bin./// Remove this slip and its paged copy as soon as the write is accepted. @discardableResultpublicfunc binFailed(_ message: TableRecord) asyncthrows -> ChangeRecord? {guard canRetryOrBin(message), !retrying.contains(message.id), !binning.contains(message.id) else { returnnil } binning.insert(message.id)defer { binning.remove(message.id) }let change = tryawait store.delete(table: layout.table, id: message.id) messages.removeAll { $0.id == message.id } paged.removeAll { $0.id == message.id } items = layout.merged(messages: messages, also: others, wording: wording) lastChange = changeawait load()return change }privatefunc receive(_ change: ChangeRecord, words: String? = nil) {guardlet after = change.after else { return }var shown = messages.first { $0.id == after.id } ?? after shown.values.merge(after.values) { _, updated in updated }// A write can answer raw columns before its computed display words// are read. These are the words just accepted by the local engine.iflet words, shown[layout.body].isNull { shown.values[layout.body] = .text(words) } messages = merged(messages.filter { $0.id != after.id } + [shown]) items = layout.merged(messages: messages, also: others, wording: wording) phase = .loaded }/// The receipt took the sent message `change` (the newest, when nil) back/// through the verbs itself: remember it and read the thread again. The/// change stays, so its receipt reads as undone — even drawn again, when/// the page went and came back.publicfunc undone(_ change: ChangeRecord? = nil) async { undoneChange = (change ?? lastChange)?.idawait load() }/// Lets go of the receipt without undoing it.publicfunc dismissChange() { lastChange = nil }/// Takes back a message this page sent, through the `undo` verb, and/// reads the thread again.publicfunc undo(_ change: ChangeRecord) asyncthrows { _ = tryawait store.undo(change: change.id)await load() }}extensionConversationLayout {/// Whether the owner wrote it.publicfunc isMine(_ message: TableRecord) -> Bool { message[mine.column].text.map(mine.values.contains) ?? false }/// Oldest first by `at`; a message with no moment goes last, and ties keep/// the order they were read in.publicfunc ordered(_ messages: [TableRecord]) -> [TableRecord] {Self.oldestFirst(messages) { moment(of: $0) } }/// A delayed acknowledgement must not reorder a Cotton-sent note./// The parts of the day `moment` names.func day(of message: TableRecord) -> DayParts? {if usesLocalQueue, MessageDelivery(message) != nil, message["created_at"].text != nil { return message.dayParts("created_at") }return message.dayParts(at) }publicfunc moment(of message: TableRecord) -> String? {if usesLocalQueue, MessageDelivery(message) != nil,let created = message["created_at"].text { return created }return message[at].text }/// Oldest first by `moment`; one with no moment goes last, and ties —/// two moments that are the same instant, however each is written — keep/// the order they were given in.staticfunc oldestFirst<T>(_ items: [T], moment: (T) -> String?) -> [T] { items.enumerated().sorted { a, b inswitch (moment(a.element), moment(b.element)) {caselet (x?, y?) where x != y:// As moments where both read as one; as text otherwise (an// ISO instant sorts as its moment within one zone).iflet p = FaceText.parse(x)?.date, let q = FaceText.parse(y)?.date {return p == q ? a.offset < b.offset : p < q }return x < ycase (_?, nil): returntruecase (nil, _?): returnfalsedefault: return a.offset < b.offset } }.map(\.element) }/// The thread's one stream: the `also` tables' records first, each table/// in the order it was read, then the messages, all put oldest first —/// so at the same instant a turn comes before a message, and turns keep/// their own order.publicfunc merged(messages: [TableRecord], also others: [[TableRecord]], wording: TableDefinition? = nil) -> [ConversationItem] {var items: [ConversationItem] = []for (source, records) in zip(also, others) {for record in records { items.append(ConversationItem( id: "\(source.table):\(record.id)", table: source.table, record: record, words: source.body.flatMap { record[$0].text } ?? "", mine: source.mine.flatMap { mine in record[mine.column].text.map(mine.values.contains) } ?? false, at: record[source.at].text, isMessage: false, media: [], slip: source.face == .slip, day: record.dayParts(source.at))) } }for record in messages { items.append(ConversationItem( id: "\(table):\(record.id)", table: table, record: record, words: words(of: record, messages: wording), mine: isMine(record), at: moment(of: record), isMessage: true, media: mediaKeys(of: record), day: day(of: record))) }returnSelf.oldestFirst(items) { $0.at } }/// A message's words: its body, or where that is blank the `blank_body`/// column as the message definition words it.publicfunc words(of message: TableRecord, messages: TableDefinition?) -> String {let said = message[body].text ?? ""guard said.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, let key = blankBody,let words = FaceText.line(message[key], words: message.columnWords(key), column: messages?.column(key))else { return said }return words }/// The media keys a message carries in the `media` column, one a line.publicfunc mediaKeys(of message: TableRecord) -> [String] {guardlet media = self.media, let text = message[media].text else { return [] }return text.split(whereSeparator: \.isNewline) .map { $0.trimmingCharacters(in: .whitespaces) } .filter { !$0.isEmpty } }/// What is handwritten under a note: a message's `footer` column when it/// holds words; else its status word when it is past the column's first/// choice (an open message says nothing), then its time. A record of an/// `also` table has its time alone. `messages` is the message table's/// definition, for its status column's words.////// The definition's `footer` names one message column (a session's: its/// words are the whole line) or several (an imported chat's reactions,/// delivery and edits: their words go before the status and the time)./// An envelope's one line (`header_columns`): who it is from — the first/// envelope column that says something — and its time. The rest of the/// envelope waits behind a tap (`envelopeLines`)./// `day` says the day before the time (mail, whose sheets have no day/// lines between them); `time: false` says who alone.publicfunc envelopeHead(of message: TableRecord, messages: TableDefinition?, day: Bool = false, time: Bool = true) -> String? {// No envelope where the message says none of its columns (a// session's `header_columns` are the thread's own, not a message's).guardlet who = envelopeWho(of: message, messages: messages)?.words else { returnnil }guard time else { return who }let parts = message.dayParts(at)let clock = parts?.clock// A mail's day in the form its page head says it ("Thu 15 Oct,// 2:00 pm"), never "Yesterday" under a head that wrote the date// (walker pass 2: one email, three date forms).let date = parts?.weekdayDatelet when = day ? [date, clock].compactMap { $0 }.joined(separator: ", ") : clockreturn [who, when].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " \u{00B7} ") }privatefunc envelopeWho(of message: TableRecord, messages: TableDefinition?) -> (key: String, words: String)? {for key in headerColumns {iflet words = FaceText.line(message[key], words: message.columnWords(key), column: messages?.column(key)), !words.isEmpty { return (key, words) } }returnnil }/// The rest of an envelope, each line named: every column that says/// something, bar the one the head said and a subject the thread's own/// head already says (replies' "Re:" set aside).publicfunc envelopeLines(of message: TableRecord, messages: TableDefinition?, threadTitle: String?) -> [String] {let said = envelopeWho(of: message, messages: messages)?.keyreturn headerColumns.compactMap { key inguard key != said, let column = messages?.column(key),let line = FaceText.line(message[key], words: message.columnWords(key), column: column), !line.isEmptyelse { returnnil }iflet threadTitle, Self.bareSubject(line) == Self.bareSubject(threadTitle) { returnnil }return"\(column.name ?? key): \(line)" } }/// A subject without its reply and forward marks, for telling one/// conversation's subject from another's.staticfunc bareSubject(_ subject: String) -> String {var rest = subject.trimmingCharacters(in: .whitespaces)whilelet mark = ["re:", "fwd:", "fw:"].first(where: { rest.lowercased().hasPrefix($0) }) { rest = String(rest.dropFirst(mark.count)).trimmingCharacters(in: .whitespaces) }return rest.lowercased() }publicfunc footer(of item: ConversationItem, messages: TableDefinition?, time: Bool = true) -> String? {let delivery = item.isMessage && usesLocalQueue ? MessageDelivery(item.record) : niliflet delivery {guard delivery.isConfirmed else { returnnil }// The declared footer includes the native Sent from Cotton byline.// Keep it alongside the time after the Mac confirms acceptance. }if item.isMessage, case .one(let key)? = self.footer, let words = item.record[key].text, !words.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {return words }var parts: [String] = []if item.isMessage, case .several(let keys)? = self.footer,let words = metadata(keys, of: item.record, messages: messages) { parts.append(words) }if item.isMessage, let key = status, let column = messages?.column(key),let value = item.record[key].text, value != column.choices?.first,let word = FaceText.line(item.record[key], words: item.record.columnWords(key), column: column) { parts.append(word.lowercased()) }// Queue time keeps the row in place; the footer says when the Mac sent it.let stamp = item.isMessage ? slipDay(of: item.record) : item.dayif time, let clock = stamp?.clock { parts.append(clock) }return parts.isEmpty ? nil : parts.joined(separator: " \u{00B7} ") }/// The clock under the chat's slip and the deck's slip is the same:/// an imported moment, or the confirmed send time for a queued message.privatefunc slipDay(of message: TableRecord) -> DayParts? {if usesLocalQueue, let delivery = MessageDelivery(message) {return delivery.isConfirmed ? message.dayParts(at) : nil }return day(of: message) }/// Who wrote a message, for telling one run of notes from the next: the/// `color_by` column's value (a group's sender); nil where it holds none.publicfunc writer(of message: TableRecord) -> String? {guardlet name = message[colorBy].text?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmptyelse { returnnil }return name }/// The key of a message's sender's picture, where the layout names a/// `photo` column and the message holds one.publicfunc photoKey(of message: TableRecord) -> String? {guardlet key = photo, let value = message[key].text, !value.isEmpty else { returnnil }return value }/// Message columns' words as a face writes them, joined by a dot; nil/// when none of them holds anything.publicfunc metadata(_ keys: [String]?, of message: TableRecord, messages: TableDefinition?) -> String? {// The header can also name the thread's description. When that key// is the message body, its note already owns the words.let parts = (keys ?? []).filter { $0 != body }.compactMap { key inFaceText.line(message[key], words: message.columnWords(key), column: messages?.column(key)) }return parts.isEmpty ? nil : parts.joined(separator: " \u{00B7} ") }/// The `header` columns as the page draws them, in order: a line in/// pencil for each, and a long text — a pull request's description, its/// reviewers, its checks — whole, read as Markdown, so what the thread is/// about stands at its top rather than behind "Details". A column with/// nothing in it is left out.publicfunc headerPieces(of thread: TableRecord, in definition: TableDefinition) -> [ConversationHeaderPiece] { header.compactMap { key inlet column = definition.column(key)guardlet text = FaceText.line(thread[key], words: thread.columnWords(key), column: column)?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmptyelse { returnnil }return column?.type == .longtext ? .markdown(text) : .line(text) } }/// "started on mac-b · owner@example.com · 9:04 am" once the thread's/// `started.at` holds a moment — the `started.words` that hold a value,/// then the time; nil without one.publicfunc startedLine(of thread: TableRecord) -> String? {guardlet started = self.started, !RecordValue.isBlank(thread[started.at]) else { returnnil }let words = started.words.compactMap { key -> String? inguardlet text = thread[key].text?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty else {returnnil }return text }let time = thread.dayParts(started.at)?.clock ?? ""var line = words.isEmpty ? ShellLines.line("conversation", "started") : ShellLines.line("conversation", "started_on", ["where": words.joined(separator: " \u{00B7} ")])if !time.isEmpty { line += " \u{00B7} \(time)" }return line }/// The record a message sent from the input is created with: the fixed/// `sends` values, the owner as its writer, the words and the thread on/// the first link column. Nil for words that are only whitespace.publicfunc sent(_ words: String, thread: String, record: TableRecord? = nil) -> [String: RecordValue]? {let text = words.trimmingCharacters(in: .whitespacesAndNewlines)guard sendGate.allows(record), !text.isEmpty, let link = links.first, record.map(takesWords(on:)) ?? trueelse { returnnil }iflet input = localQueueInput(words: text, thread: thread) { return input }var data = sendsif data[mine.column] == nil, let owner = mine.values.first { data[mine.column] = .text(owner) } data[body] = .text(text) data[link] = .text(thread)return data }/// Whether the thread takes words from here: its layout sends, and the/// thread has not ended — an ended session has no one to read them.publicfunc takesWords(on thread: TableRecord) -> Bool { sendGate.allows(thread) && (ended.map { RecordValue.isBlank(thread[$0]) } ?? true) }/// "ended · 6:12 pm" once the thread's `ended` column holds a moment; nil/// before.publicfunc endedLine(of thread: TableRecord) -> String? {guardlet ended, !RecordValue.isBlank(thread[ended]) else { returnnil }let time = thread.dayParts(ended)?.clock ?? ""return time.isEmpty ? "ended" : "ended \u{00B7} \(time)" }}/// One note of a conversation: a message, or a record of one of the/// definition's `also` tables (a session's turn).publicstructConversationItem: Identifiable, Equatable, Sendable {/// The table and the record's id, so two tables' ids never meet.publiclet id: Stringpubliclet table: Stringpubliclet record: TableRecordpubliclet words: Stringpubliclet mine: Boolpubliclet at: String?/// A record of the conversation's own table, not an `also` one.publiclet isMessage: Bool/// Media keys drawn as prints above the words.publiclet media: [String]/// Drawn as its own table's slip rather than a note (an `also` table/// whose face is `slip`).publicvar slip: Bool = false/// Its moment's day as the core said it: the conversation's day lines/// and their grouping read this, never a calendar.publicvar day: DayParts? = nil}/// One piece of a conversation's header: a handwritten line, or a long text/// read as Markdown.publicenumConversationHeaderPiece: Equatable, Sendable {case line(String)case markdown(String)}