Cotton code
290 lines · 12.3 KB · SwiftRaw
// What a session is CALLED and how its conversation is laid out.//// The SECTIONS are `Settings/SessionCutsTests`' subject, not this file's:// `/code` is the session table's one list and `CodeFacts` is what cuts it. What lived// here — listening / not listening / earlier, the day groups, the row's own// meta line — went with the second list.//// `now` is passed into every case here, never read from a clock: a fixed-NOW// test over a wall-clock reader is a time bomb with a computable detonation// date.//// Every fixture is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]).import CottonKitimport CottonValuesimport Foundationimport SwiftUIimport XCTest@testable import CottonUIfinal class SessionFactsTests: XCTestCase {    private let now = CottonDate.parse("2026-09-04T12:00:00.000Z")!    /// A stamp this many seconds before `now`, written the way the crate    /// writes one.    ///    /// The formatter is built per call rather than held as a `static let`:    /// `ISO8601DateFormatter` is not `Sendable`, so a shared one is a    /// concurrency error under this package's strict checking, and a formatter    /// in a test is not a cost worth a `nonisolated(unsafe)`.    private func ago(_ seconds: TimeInterval) -> String {        let formatter = ISO8601DateFormatter()        formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]        formatter.timeZone = TimeZone(identifier: "UTC")        return formatter.string(from: now.addingTimeInterval(-seconds))    }    /// A run that is still going, which every case narrows from.    private func session(_ overrides: [String: JSONValue] = [:]) -> JSONValue {        var row: [String: JSONValue] = [            "id": .string("s-1"),            "machine": .string("mac-b"),            "account": .string("owner@example.invalid"),            "title": .string("export lane"),            "repoUrl": .string("git.example.invalid/team/tinmen"),            "branch": .string("main"),            "startedAt": .string(ago(7200)),            "lastActiveAt": .string(ago(120)),            "endedAt": .null,            "promptCount": .number(4),        ]        for (key, value) in overrides { row[key] = value }        return .object(row)    }    // ── the clock this screen reads ───────────────────────────────────────    func testTheInstantIsFlooredToTheMinuteSoTheSectionsDoNotReCutEveryFrame() {        // Elapsed time moves once a minute at most. A `Date()` per body pass        // would hand a new value to every memo on the screen, re-cutting the        // sections for a change nobody could see.        let at = Date(timeIntervalSince1970: 1_757_000_045.75)        XCTAssertEqual(            SessionFacts.minuteFloor(at).timeIntervalSince1970,            1_757_000_040        )        // Already on a minute, and it stays there — flooring is idempotent.        let floored = SessionFacts.minuteFloor(at)        XCTAssertEqual(SessionFacts.minuteFloor(floored), floored)    }    // ── what a row is called ──────────────────────────────────────────────    // ── when ──────────────────────────────────────────────────────────────    // ── one session's conversation ────────────────────────────────────────    private func message(_ overrides: [String: JSONValue] = [:]) -> JSONValue {        var row: [String: JSONValue] = [            "id": .string("msg-1"),            "toKind": .string("session"),            "toSessionId": .string("s-1"),            "fromKind": .string("session"),            "fromSessionId": .string("s-1"),            "kind": .string("report"),            "status": .string("done"),            "createdAt": .string(ago(600)),        ]        for (key, value) in overrides { row[key] = value }        return .object(row)    }    private func turn(seq: Int, at: String, role: String) -> JSONValue {        .object([            "seq": .number(Double(seq)),            "ts": .string(at),            "role": .string(role),            "text": .string("a line nobody typed"),        ])    }    private func keys(_ items: [SessionFacts.ChatItem]) -> [String] {        items.map(\.id)    }    private func mine(_ item: SessionFacts.ChatItem) -> Bool? {        switch item {        case .turn(_, _, let mine), .message(_, _, let mine): return mine        case .started, .ended: return nil        }    }    func testTheConversationOpensWithStartedAndClosesWithEnded() {        let items = SessionFacts.chat(            session(["endedAt": .string(ago(60))]), messages: [], turns: []        )        XCTAssertEqual(keys(items), ["started", "ended"])    }    func testAStillRunningSessionHasNoEndedRowToDraw() {        let items = SessionFacts.chat(session(), messages: [], turns: [])        XCTAssertEqual(keys(items), ["started"])    }    func testTurnsAndMessagesAreOneTimelineWithTheTurnFirstAtTheSameInstant() {        // The prompt was typed, then the report about it was posted. Among        // turns the transcript's own order settles a tie, so a run that logged        // two turns in one second still reads in the order they happened.        let items = SessionFacts.chat(            session(),            messages: [                message([                    "id": .string("m-report"), "fromKind": .string("session"),                    "createdAt": .string("2026-08-23T08:05:00.000Z"),                ])            ],            turns: [                turn(seq: 3, at: "2026-08-23T08:04:00.000Z", role: "assistant"),                turn(seq: 1, at: "2026-08-23T08:01:00.000Z", role: "user"),                turn(seq: 5, at: "2026-08-23T08:05:00.000Z", role: "assistant"),            ]        )        XCTAssertEqual(keys(items), ["started", "turn-1", "turn-3", "turn-5", "m-report"])        XCTAssertEqual(items.compactMap(mine), [true, false, false, false])    }    func testAMessageThisSessionMerelyWroteElsewhereIsNotDrawnHere() {        // `listForSession` widens on purpose: an instruction addressed to the        // project and CLAIMED by this session is work it was asked to do. What        // must not appear is a report this session wrote into somebody else's        // thread.        let items = SessionFacts.chat(            session(),            messages: [                message([                    "id": .string("m-kept"), "fromKind": .string("owner"),                    "fromSessionId": .null, "createdAt": .string(ago(3000)),                ]),                message([                    "id": .string("m-claimed"), "toKind": .string("project"),                    "toSessionId": .null, "fromKind": .string("owner"),                    "fromSessionId": .null, "claimedBySessionId": .string("s-1"),                    "createdAt": .string(ago(2000)),                ]),                message([                    "id": .string("m-alien"), "toKind": .string("owner"),                    "toSessionId": .null, "fromSessionId": .string("s-9"),                    "createdAt": .string(ago(1000)),                ]),            ],            turns: []        )        XCTAssertEqual(keys(items), ["started", "m-kept", "m-claimed"])    }    func testTheOwnersOwnLinesAreMarkedAsTheirsAndTheSessionsAreNot() {        let items = SessionFacts.chat(            session(),            messages: [                message([                    "id": .string("m-1"), "fromKind": .string("owner"),                    "fromSessionId": .null, "createdAt": .string(ago(3000)),                ]),                message(["id": .string("m-2"), "createdAt": .string(ago(2000))]),            ],            turns: []        )        XCTAssertEqual(items.compactMap(mine), [true, false])    }    func testAMessageBelongsToASessionItWasSentToSentFromOrClaimedBy() {        XCTAssertTrue(SessionFacts.belongs(message(), to: "s-1"))        XCTAssertTrue(            SessionFacts.belongs(                message(["toSessionId": .null, "fromSessionId": .null,                         "claimedBySessionId": .string("s-1")]),                to: "s-1"            )        )        XCTAssertFalse(            SessionFacts.belongs(                message(["toSessionId": .string("s-9"), "fromSessionId": .string("s-9")]),                to: "s-1"            )        )    }    // ── whose terminal, and which agent ───────────────────────────────────    /// Every session Cotton wrote carries the flag; the rows without one are    /// the rows this answer is about, so ABSENT reads as "not ours".    func testASessionIsOursOnlyWhenTheRowSaysSo() {        XCTAssertTrue(SessionFacts.isOurs(.object(["hostOwned": .bool(true)])))        XCTAssertFalse(SessionFacts.isOurs(.object(["hostOwned": .bool(false)])))        XCTAssertFalse(SessionFacts.isOurs(.object([:])))    }    // ── what a bubble says underneath it ──────────────────────────────────    // ── a project's standing conversation ─────────────────────────────────    private func conversation(_ overrides: [String: JSONValue] = [:]) -> JSONValue {        var row: [String: JSONValue] = [            "id": .string("conv-1"),            "kind": .string("conversation"),            "state": .string("running"),            "project": .string("cottondb"),            "projectName": .string("CottonDB"),            "hostOwned": .bool(true),            "title": .string("You are this project's standing conversation."),        ]        for (key, value) in overrides { row[key] = value }        return .object(row)    }    // ── the agent's own task list ─────────────────────────────────────────    /// `read.session`'s own shape: `tasks` is a TOP-LEVEL sibling of `prompts`    /// and `messages`, not a column on the session row.    private func answer(tasks: [JSONValue]) -> JSONValue {        .object([            "session": session(),            "prompts": .array([]),            "messages": .array([]),            "tasks": .array(tasks),        ])    }    func testTheTaskListIsDrawnInTheAgentsOwnOrderWithAMarkPerState() {        let row = answer(tasks: [            .object(["seq": .number(2), "text": .string("wire the read"), "state": .string("active")]),            .object(["seq": .number(1), "text": .string("read the contract"), "state": .string("done")]),            .object(["seq": .number(3), "text": .string("write the tests"), "state": .string("open")]),        ])        let tasks = SessionFacts.tasks(row)        XCTAssertEqual(tasks.map(\.seq), [1, 2, 3])        XCTAssertEqual(tasks.map(\.symbol), ["checkmark", "circle.fill", "circle"])        XCTAssertEqual(SessionFacts.taskCount(tasks), "1/3")    }    func testATaskWithNoWordsIsNotATaskAndAnUnknownStateReadsAsOpen() {        // A SESSION LOG MUST NEVER FAIL, the mirror included — so the phone        // draws what it can rather than a gap where a list should be.        let row = answer(tasks: [            .object(["seq": .number(0), "text": .string("  "), "state": .string("done")]),            .object(["seq": .number(1), "text": .string("ship it"), "state": .string("later")]),            .object(["seq": .number(2), "text": .string("no state named")]),        ])        let tasks = SessionFacts.tasks(row)        XCTAssertEqual(tasks.map(\.text), ["ship it", "no state named"])        XCTAssertEqual(tasks.map(\.state), ["open", "open"])        XCTAssertEqual(SessionFacts.taskCount(tasks), "0/2")    }    func testASessionWithNoTaskListDrawsNoTaskList() {        XCTAssertTrue(SessionFacts.tasks(answer(tasks: [])).isEmpty)        // And an answer with no `tasks` key at all — a session whose agent        // keeps no list, which is most of them.        XCTAssertTrue(SessionFacts.tasks(.object(["session": session()])).isEmpty)    }}