// The page styles drawn once in `Surfaces/PageStyles`: the script page's// reading of a Fountain long text, and the conversation page's thread over// the fixture verbs (the shared format's 23:10 and 00:25 additions). Every// record is invented.importCottonValuesimportFoundationimport XCTest@testable importCottonUI@MainActorfinalclassPageStylesTests: XCTestCase {/// RULE: A conversation's message body is drawn only as its note, never repeated as header metadata; a thread's own description remains in its header.func testMessageMetadataDoesNotRepeatTheBody() {var layout = Self.thread.conversation! layout.header = ["author", "body"]let message = TableRecord(id: "comment", values: ["author": .text("Example reviewer"), "body": .text("**Keep this once.**")]) XCTAssertEqual(layout.metadata(layout.header, of: message, messages: Self.message), "Example reviewer") XCTAssertNil(layout.metadata(["body"], of: message, messages: Self.message))let thread = TableRecord(id: "pull", values: ["body": .text("The pull's own description.")]) XCTAssertEqual(layout.headerPieces(of: thread, in: Self.message), [.markdown("The pull's own description.")]) }// ── The conversation page ───────────────────────────────────────────────privatestaticlet thread = TableDefinition( id: "example_thread", name: "Thread", plural: "Threads", columns: [ColumnDefinition(key: "title", type: .text), ColumnDefinition(key: "ended_at", type: .date)], title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["title"])], pageParts: [.title, .facts, .messages], conversation: ConversationLayout( table: "example_message", links: ["to_id", "from_id"], body: "body", at: "sent_at", mine: ConversationMine(column: "from", values: ["owner"]), status: "status", ended: "ended_at", sends: ["kind": .text("instruction")]) )privatestaticlet message = TableDefinition( id: "example_message", name: "Message", plural: "Messages", columns: [ColumnDefinition(key: "body", type: .longtext),ColumnDefinition(key: "to_id", type: .link, linkTo: "example_thread"),ColumnDefinition(key: "from_id", type: .link, linkTo: "example_thread"),ColumnDefinition(key: "from", type: .choice, choices: ["owner", "session"]),ColumnDefinition(key: "status", type: .choice, choices: ["open", "withdrawn"]),ColumnDefinition(key: "kind", type: .text),ColumnDefinition(key: "sent_at", type: .date), ], title: "body", slip: SlipLayout(title: "body"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["body"])] )privatefunc message(_ n: Int, _ values: [String: RecordValue]) -> TableRecord {Self.stamped(TableRecord(id: "example-message-\(n)", values: ["body": .text("Example words \(n)")].merging(values) { $1 }), "sent_at") }/// `record` as a read hands it over: its stamp `key`'s parts as the/// core says them (`@day_parts`) — here its day and clock read in UTC/// ("2026-10-01T09:05:00Z" is 9:05 am). Swift spells no clock.privatestaticfunc stamped(_ record: TableRecord, _ key: String) -> TableRecord {guardlet iso = record[key].text, iso.count >= 16,let hour = Int(iso.dropFirst(11).prefix(2)), let minute = Int(iso.dropFirst(14).prefix(2))else { return record }let clock = "\((hour + 11) % 12 + 1):\(String(format: "%02d", minute)) \(hour < 12 ? "am" : "pm")"returnCoreSaid.read(record, days: [key: CoreSaid.day(String(iso.prefix(10)), weekdayDate: "Thu 1 Oct", clock: clock)]) }privatefunc store() -> FixtureRecords {FixtureRecords(definitions: [Self.thread, Self.message], records: ["example_thread": [TableRecord(id: "example-thread-1", values: ["title": .text("An example thread")])],"example_message": [ message(1, ["to_id": .text("example-thread-1"), "from": .text("owner"), "sent_at": .text("2026-10-01T09:30:00Z")]), message(2, ["from_id": .text("example-thread-1"), "from": .text("session"), "sent_at": .text("2026-10-01T09:00:00Z")]), message(3, ["to_id": .text("example-thread-2"), "from": .text("owner"), "sent_at": .text("2026-10-01T08:00:00Z")]), ], ]) }/// RULE: A conversation page shows the thread's messages named by any of its link columns, oldest first, with the owner's known by the mine column, and another thread's never.func testAConversationReadsItsThreadsMessagesOldestFirst() asyncthrows {let layout = try XCTUnwrap(Self.thread.conversation)let model = ConversationModel(layout: layout, thread: "example-thread-1", store: store())await model.load() XCTAssertEqual(model.phase, .loaded) XCTAssertEqual(model.messages.map(\.id), ["example-message-2", "example-message-1"]) XCTAssertEqual(model.messages.map(layout.isMine), [false, true]) }/// RULE: A conversation read again (a sync, a live cadence) keeps the older pages the reader asked for, so the oldest messages stay reachable and the reader is not thrown back to the foot.func testAReadAgainKeepsTheOlderPagesTheReaderLoaded() asyncthrows {let layout = try XCTUnwrap(Self.thread.conversation)let many = (10..<(10 + FixtureRecords.pageSize + 5)).map { message($0, ["to_id": .text("example-thread-1"), "from": .text("owner"), "sent_at": .text("2026-09-01T09:00:\($0)Z")]) }let records = FixtureRecords(definitions: [Self.thread, Self.message], records: ["example_thread": [TableRecord(id: "example-thread-1", values: ["title": .text("An example thread")])],"example_message": many, ])let model = ConversationModel(layout: layout, thread: "example-thread-1", store: records)await model.load() XCTAssertEqual(model.messages.count, FixtureRecords.pageSize) XCTAssertTrue(model.hasMore)await model.loadMore() XCTAssertEqual(model.messages.count, many.count)await model.load() XCTAssertEqual(model.messages.count, many.count, "a read again drops no page the reader loaded") XCTAssertFalse(model.hasMore) }/// RULE: A conversation takes words only while it can be sent to and has not ended — an ended session shows no composer.func testAnEndedConversationTakesNoWords() throws {var layout = try XCTUnwrap(Self.thread.conversation) layout.ended = "ended_at" XCTAssertTrue(layout.takesWords(on: TableRecord(id: "a", values: [:]))) XCTAssertFalse(layout.takesWords(on: TableRecord(id: "a", values: ["ended_at": .text("2026-10-01T09:00:00Z")]))) layout.canSend = false XCTAssertFalse(layout.takesWords(on: TableRecord(id: "a", values: [:]))) }/// RULE: An envelope is one line, who it is from and when; the address, the recipients and a subject the thread does not already say wait behind a tap.func testAnEnvelopeIsOneLineAndTheRestWaits() throws {var layout = try XCTUnwrap(Self.thread.conversation) layout.headerColumns = ["from", "body"]let mail = message(1, ["from": .text("owner"), "sent_at": .text("2026-10-01T09:30:00Z")])let head = try XCTUnwrap(layout.envelopeHead(of: mail, messages: Self.message)) XCTAssertTrue(head.hasPrefix("Owner \u{B7} "), head) XCTAssertEqual(layout.envelopeLines(of: mail, messages: Self.message, threadTitle: nil).count, 1, "the body's line; the head's own column is not said again") XCTAssertEqual(layout.envelopeLines(of: mail, messages: Self.message, threadTitle: "Re: example words 1"), [], "a subject the thread's head says is not said again") XCTAssertEqual(ConversationLayout.bareSubject("Re: Fwd: Grant letter"), "grant letter") layout.headerColumns = ["title"] XCTAssertNil(layout.envelopeHead(of: mail, messages: Self.message), "columns the message does not hold make no envelope") }/// RULE: The conversation's input sends the owner's words to the thread through the create verb with the definition's fixed values, and sends nothing for blank words.func testTheConversationsInputSendsTheOwnersWords() asyncthrows {let layout = try XCTUnwrap(Self.thread.conversation)let records = store()let model = ConversationModel(layout: layout, thread: "example-thread-1", store: records)await model.load()let none = tryawait model.send(" ") XCTAssertNil(none)let change = tryawait model.send(" Example reply ")let sent = try XCTUnwrap(change?.after) XCTAssertEqual(sent["body"], .text("Example reply")) XCTAssertEqual(sent["to_id"], .text("example-thread-1")) XCTAssertEqual(sent["from"], .text("owner")) XCTAssertEqual(sent["kind"], .text("instruction")) XCTAssertTrue(model.messages.contains { $0.id == sent.id }, "the thread is read again after a send") }/// RULE: A message sent from the conversation's input is taken back by the undo its receipt offers, and the thread then reads without it.func testASentMessageIsTakenBackByItsUndo() asyncthrows {let layout = try XCTUnwrap(Self.thread.conversation)let model = ConversationModel(layout: layout, thread: "example-thread-1", store: store())await model.load()let reply = tryawait model.send("Example reply")let change = try XCTUnwrap(reply)let sent = try XCTUnwrap(change.after) XCTAssertTrue(model.messages.contains { $0.id == sent.id })tryawait model.undo(change) XCTAssertFalse(model.messages.contains { $0.id == sent.id }) XCTAssertEqual(model.messages.map(\.id), ["example-message-2", "example-message-1"]) }/// RULE: A sent message's receipt is kept until dismissed or replaced, and the conversation remembers once it was taken back — a receipt drawn again reads undone.func testASentMessagesReceiptRemembersItsUndo() asyncthrows {let layout = try XCTUnwrap(Self.thread.conversation)let records = store()let model = ConversationModel(layout: layout, thread: "example-thread-1", store: records)await model.load()let sent = tryawait model.send("Example reply")let change = try XCTUnwrap(sent) XCTAssertEqual(model.lastChange?.id, change.id) XCTAssertFalse(model.lastChangeUndone) _ = tryawait records.undo(change: change.id)await model.undone(change) XCTAssertTrue(model.lastChangeUndone) XCTAssertFalse(model.messages.contains { $0.id == change.after?.id })let again = tryawait model.send("Example second reply")let next = try XCTUnwrap(again) XCTAssertEqual(model.lastChange?.id, next.id) XCTAssertFalse(model.lastChangeUndone) model.dismissChange() XCTAssertNil(model.lastChange) }/// RULE: A conversation is closed by a handwritten ended line once the thread's ended column holds a moment, and has none before.func testAnEndedThreadSaysSo() throws {let layout = try XCTUnwrap(Self.thread.conversation)letopen = TableRecord(id: "example-thread-1", values: [:]) XCTAssertNil(layout.endedLine(of: open))let ended = TableRecord(id: "example-thread-1", values: ["ended_at": .text("2026-10-01T18:12:00Z")]) XCTAssertNotNil(layout.endedLine(of: ended)) }// ── A conversation over two tables (a session's turns beside its messages) ──privatestaticlet turn = TableDefinition( id: "example_turn", name: "Turn", plural: "Turns", columns: [ColumnDefinition(key: "thread_id", type: .link, linkTo: "example_thread"),ColumnDefinition(key: "seq", type: .number),ColumnDefinition(key: "at", type: .date),ColumnDefinition(key: "role", type: .choice, choices: ["user", "assistant"]),ColumnDefinition(key: "text", type: .longtext), ], title: "text", slip: SlipLayout(title: "text"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["text"])] )privatestaticlet messageWithFooter: TableDefinition = {var definition = message definition.columns.append(ColumnDefinition(key: "footer", type: .text)) definition.columns.append(ColumnDefinition(key: "media", type: .text))return definition }()privatestaticlet session: TableDefinition = {var definition = thread definition.columns += [ColumnDefinition(key: "started_at", type: .date),ColumnDefinition(key: "machine", type: .text),ColumnDefinition(key: "account", type: .text),ColumnDefinition(key: "state_line", type: .text),ColumnDefinition(key: "notice", type: .text), ] definition.conversation?.footer = "footer" definition.conversation?.media = "media" definition.conversation?.started = ConversationStarted(at: "started_at", words: ["machine", "account"]) definition.conversation?.header = ["state_line", "notice"] definition.conversation?.placeholder = "Send an instruction" definition.conversation?.also = [ConversationSource( table: "example_turn", links: ["thread_id"], body: "text", at: "at", mine: ConversationMine(column: "role", values: ["user"]))]return definition }()privatefunc turn(_ seq: Int, _ at: String, role: String, thread: String = "example-thread-1") -> TableRecord {Self.stamped(TableRecord(id: "example-turn-\(seq)", values: ["thread_id": .text(thread), "seq": .number(Double(seq)), "at": .text(at), "role": .text(role),"text": .text("Example turn \(seq)"), ]), "at") }privatefunc sessionStore( _ session: TableDefinition = PageStylesTests.session, adding more: [TableDefinition] = [], records extra: [String: [TableRecord]] = [:] ) -> FixtureRecords {FixtureRecords(definitions: [session, Self.messageWithFooter, Self.turn] + more, records: extra.merging(["example_thread": [TableRecord(id: "example-thread-1", values: ["title": .text("An example thread")])],"example_message": [// At the same instant as turn 2 — and written with another// spelling of that instant. message(1, ["to_id": .text("example-thread-1"), "from": .text("owner"), "status": .text("open"),"sent_at": .text("2026-10-01T09:01:00.000Z"), "footer": .text("Example footer words"),"media": .text("example-key-1\n\nexample-key-2\n")]), message(2, ["from_id": .text("example-thread-1"), "from": .text("session"), "status": .text("withdrawn"),"sent_at": .text("2026-10-01T09:05:00Z")]), ],"example_turn": [ turn(3, "2026-10-01T09:01:00Z", role: "assistant"), turn(1, "2026-10-01T09:00:00Z", role: "user"), turn(2, "2026-10-01T09:01:00Z", role: "user"), turn(9, "2026-10-01T09:00:00Z", role: "user", thread: "example-thread-2"), ], ]) { mine, _ in mine }) }/// RULE: A conversation's also tables merge into its thread by moment — a turn before a message at the same instant, and turns at one instant keep the order they were read in.func testTheAlsoTablesMergeIntoTheThreadByMoment() asyncthrows {let layout = try XCTUnwrap(Self.session.conversation)let model = ConversationModel(layout: layout, thread: "example-thread-1", store: sessionStore())await model.load() XCTAssertEqual(model.phase, .loaded) XCTAssertEqual(model.items.map(\.id), ["example_turn:example-turn-1",// Read in the store's order (2 before 3), and kept so on the tie."example_turn:example-turn-2", "example_turn:example-turn-3","example_message:example-message-1","example_message:example-message-2", ])// The turns' own `mine` is their role; the messages' is theirs. XCTAssertEqual(model.items.map(\.mine), [true, true, false, true, false])// `messages` is kept for callers, the messages alone. XCTAssertEqual(model.messages.map(\.id), ["example-message-1", "example-message-2"]) }// ── An also table drawn as slips (a session's runs between its turns) ──privatestaticlet run = TableDefinition( id: "example_run", name: "Run", plural: "Runs", columns: [ColumnDefinition(key: "thread_id", type: .link, linkTo: "example_thread"),ColumnDefinition(key: "name", type: .text),ColumnDefinition(key: "state", type: .choice, choices: ["queued", "passed", "failed"]),ColumnDefinition(key: "queued_at", type: .date), ], title: "name", slip: SlipLayout(title: "name", subtitle: "state"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["name", "state"])] )/// RULE: An also table whose face is slip is read through the same list verb and stands in the one stream by its moment, marked to be drawn as its own table's slip — nobody's side of the chat, with no words of its own.func testASlipSourceStandsInTheStreamByItsMoment() asyncthrows {var definition = Self.session definition.conversation?.also.append(ConversationSource( table: "example_run", links: ["thread_id"], at: "queued_at", face: .slip))let runs = [TableRecord(id: "example-run-1", values: ["thread_id": .text("example-thread-1"), "name": .text("Example check"), "state": .text("passed"),"queued_at": .text("2026-10-01T09:03:00Z"), ]),TableRecord(id: "example-run-2", values: ["thread_id": .text("example-thread-2"), "name": .text("Another thread's run"),"queued_at": .text("2026-10-01T09:02:00Z"), ]), ].map { Self.stamped($0, "queued_at") }let withRuns = sessionStore(definition, adding: [Self.run], records: ["example_run": runs])let layout = try XCTUnwrap(definition.conversation)let model = ConversationModel(layout: layout, thread: "example-thread-1", store: withRuns)await model.load() XCTAssertEqual(model.items.map(\.id), ["example_turn:example-turn-1","example_turn:example-turn-2", "example_turn:example-turn-3","example_message:example-message-1","example_run:example-run-1","example_message:example-message-2", ])let run = try XCTUnwrap(model.items.first { $0.table == "example_run" }) XCTAssertTrue(run.slip) XCTAssertFalse(run.mine) XCTAssertEqual(run.words, "") XCTAssertFalse(model.items.filter { $0.table != "example_run" }.contains(where: \.slip))// Its footer is its time alone, as any also table's. XCTAssertEqual(layout.footer(of: run, messages: Self.messageWithFooter)?.contains("\u{00B7}"), false)// Nothing is sent into it: a send still writes the conversation's own table. XCTAssertEqual(layout.table, "example_message") }/// RULE: A message's footer column is the whole line under its note; without one it is the status word and the time, and an also table's note has its time alone.func testTheFooterColumnOverridesTheStatusWord() asyncthrows {let layout = try XCTUnwrap(Self.session.conversation)let model = ConversationModel(layout: layout, thread: "example-thread-1", store: sessionStore())await model.load()let byID = Dictionary(uniqueKeysWithValues: model.items.map { ($0.id, $0) })let owner = try XCTUnwrap(byID["example_message:example-message-1"]) XCTAssertEqual(layout.footer(of: owner, messages: Self.messageWithFooter), "Example footer words")let session = try XCTUnwrap(byID["example_message:example-message-2"]) XCTAssertEqual(layout.footer(of: session, messages: Self.messageWithFooter)?.hasPrefix("withdrawn \u{00B7} "), true)let turn = try XCTUnwrap(byID["example_turn:example-turn-1"])let footer = try XCTUnwrap(layout.footer(of: turn, messages: Self.messageWithFooter)) XCTAssertFalse(footer.contains("\u{00B7}"), "a turn's footer is its time alone: \(footer)")// The media keys, one a line, blank lines dropped. XCTAssertEqual(owner.media, ["example-key-1", "example-key-2"]) XCTAssertEqual(turn.media, []) }/// RULE: A long text named in a conversation's header is drawn whole, read as Markdown, where its column falls among the header's lines — so a description stands at the top of the thread, not behind Details — and an empty one is left out.func testALongTextInTheHeaderIsDrawnWholeAsMarkdown() throws {var definition = Self.session definition.columns.append(ColumnDefinition(key: "description", type: .longtext)) definition.conversation?.header = ["state_line", "description", "notice"]let layout = try XCTUnwrap(definition.conversation)let thread = TableRecord(id: "example-thread-1", values: ["state_line": .text("Running"), "description": .text("## Example\n- one\n- two\n"), "notice": .text("Example notice"), ]) XCTAssertEqual(layout.headerPieces(of: thread, in: definition), [ .line("Running"), .markdown("## Example\n- one\n- two"), .line("Example notice"), ])var blank = thread blank.values["description"] = .text(" \n ") XCTAssertEqual(layout.headerPieces(of: blank, in: definition), [.line("Running"), .line("Example notice")]) }/// RULE: A conversation's started line reads the started words that hold a value, then the time.func testTheStartedLineReadsItsWords() throws {let layout = try XCTUnwrap(Self.session.conversation)let thread = TableRecord(id: "example-thread-1", values: ["state_line": .text("Running"), "notice": .text(" "),"started_at": .text("2026-10-01T09:04:00Z"), "machine": .text("Example Mac"), ])let started = try XCTUnwrap(layout.startedLine(of: thread)) XCTAssertTrue(started.contains("Example Mac"), started)var both = thread both.values["account"] = .text("owner@example.com")let withAccount = try XCTUnwrap(layout.startedLine(of: both)) XCTAssertTrue(withAccount.contains("Example Mac") && withAccount.contains("owner@example.com"), withAccount) XCTAssertNil(layout.startedLine(of: TableRecord(id: "example-thread-1", values: [:]))) }/// RULE: A one-table conversation decodes and draws as it did before also, footer, media, started, header and placeholder: its items are its messages, footed by status and time.func testAOneTableConversationDrawsAsBefore() asyncthrows {let json = #"{"table":"example_message","links":["to_id"],"body":"body","at":"sent_at","mine":{"column":"from","values":["owner"]}}"#let decoded = try JSONDecoder().decode(ConversationLayout.self, from: Data(json.utf8)) XCTAssertEqual(decoded.also, []) XCTAssertEqual(decoded.header, []) XCTAssertNil(decoded.footer) XCTAssertNil(decoded.media) XCTAssertNil(decoded.started) XCTAssertNil(decoded.placeholder)let layout = try XCTUnwrap(Self.thread.conversation)let model = ConversationModel(layout: layout, thread: "example-thread-1", store: store())await model.load() XCTAssertEqual(model.items.map(\.record), model.messages) XCTAssertTrue(model.items.allSatisfy { $0.isMessage && $0.media.isEmpty }) XCTAssertNil(layout.startedLine(of: TableRecord(id: "example-thread-1", values: ["title": .text("x")]))) }}