Cotton code
194 lines · 8.2 KB · SwiftRaw
// The bytes of one session's terminal, on their way from the core to a view.//// **Rows for facts, streams for bytes** (Cotton note "The Code tool — why a Mac holds the sessions"). Every// other thing a session screen draws is a synced row and arrives through a// `read.*`; the terminal is the one thing that does not, because a pseudo-// terminal's output is not a record of anything — it is the screen the agent is// painting, thirty frames a second, and a row per frame would be a database of// cursor moves.//// So it arrives as EVENTS: `terminal.data {session, bytes}` carrying base64 PTY// bytes, and `terminal.state {session, state}` carrying one of `attached`,// `catchingUp`, `closed`. The phone opens no socket of its own — the client// holds the connection and hands Swift the frames.//// ## Why there is a bus at all//// `cotton_subscribe` takes ONE handler and a second call replaces the first// (`CottonCore.subscribe`), so `RootView` owns the subscription and fans events// out to the models it built. A pushed screen is not alive when that runs, and// a terminal is always a pushed screen. The bus is the seam: `RootView` hands// it every raw event, it keeps one `TerminalFeed` per session the app has asked// for, and the pane finds its own by id.//// It is NOT a buffer of the session's scrollback. The helper replays the// scrollback tail on attach and the emulator holds the result; the feed carries// only what has not been drawn yet, and it is drained the moment a view takes// it. A view that never mounts is a session nothing attached to, so nothing// accumulates.import CottonKitimport Foundation/// Where one session's terminal stands, as the far end reports it.////// The four words are the contract's own, plus `idle` — which is not a state/// the stream ever sends. It is what a feed says before anything has been/// heard, and it is why a pane that attaches to a build with no session host/// shows "not available" rather than spinning for ever.public enum TerminalState: String, Sendable, Equatable {    /// Nothing heard yet — the pane has asked and no frame has come back.    case idle    /// Live: what the agent paints reaches this screen.    case attached    /// The stream is behind and dropping frames to catch up. The bytes still    /// arrive in order; some of them arrive late.    case catchingUp    /// The far end closed — the session ended, or the Mac holding it went away.    case closed    /// Read one off the wire. An unknown word is `nil` rather than a guess:    /// the core may be one build ahead, and a word this build cannot read is    /// not a reason to redraw the pane as something it is not.    public static func read(_ word: String?) -> TerminalState? {        guard let word else { return nil }        return TerminalState(rawValue: word)    }}/// One session's undrawn bytes and its state.////// `@Observable` so the pane redraws when the state moves; the BYTES are not/// observed — a view that redrew on every frame would redraw thirty times a/// second for a picture the emulator has already painted itself. The pane/// drains them on a timer of its own.@MainActor@Observablepublic final class TerminalFeed {    public let sessionId: String    public private(set) var state: TerminalState = .idle    /// Why the pane is not showing a terminal, when that is a sentence rather    /// than a state — a refusal from `terminal.attach`, said as the core said    /// it. Never invented here.    public private(set) var refusal: String?    /// The frames that have arrived and not been drawn, oldest first.    ///    /// `@ObservationIgnored`: appending is what a stream does constantly, and    /// a view that observed it would invalidate itself on every frame.    @ObservationIgnored private var pending: [[UInt8]] = []    public init(sessionId: String) {        self.sessionId = sessionId    }    /// Bytes off the wire, still base64 as the event carried them.    ///    /// An UNDECODABLE frame is dropped and nothing else changes. The    /// alternative — feeding the emulator whatever the string's UTF-8 happens    /// to be — would paint garbage on a screen a person is reading, which is    /// worse than a missing frame.    public func receive(base64 encoded: String) {        guard let data = Data(base64Encoded: encoded) else { return }        pending.append([UInt8](data))    }    /// Bytes, already decoded — what a test feeds, and what a caller that    /// decoded them itself hands over.    public func receive(bytes: [UInt8]) {        guard !bytes.isEmpty else { return }        pending.append(bytes)    }    public func moveTo(_ state: TerminalState) {        self.state = state        // A state the far end reports is an ANSWER, so whatever sentence stood        // in for one goes: a pane showing both "closed" and a refusal from the        // attach that preceded it is two explanations for one screen.        if state != .idle { refusal = nil }    }    /// The core refused to attach. The sentence is the core's own.    public func refused(_ sentence: String) {        refusal = sentence        state = .closed    }    /// Take everything undrawn, oldest first, and leave the feed empty.    public func drain() -> [[UInt8]] {        defer { pending.removeAll(keepingCapacity: true) }        return pending    }    /// How many frames are waiting. For the tests and for nothing else.    public var pendingCount: Int { pending.count }}/// Every terminal this app is listening to, by session id.////// One per app, built by `RootView` and handed down the environment. It is fed/// RAW `CottonEvent`s — before `ClientEvent.from`, which knows the `client` and/// `data` kinds and drops everything else, terminal frames included.@MainActor@Observablepublic final class TerminalBus {    /// The two event kinds this bus reads, spelled at the BOUNDARY    /// (`Boundary+Terminal.swift`) beside the four method names and held to the    /// crate's own fixture by `TerminalWireTests`. A kind spelled here would be    /// a second copy of a wire string, which is the drift the terminal already    /// shipped once.    public static let dataKind = TerminalEventKind.data    public static let stateKind = TerminalEventKind.state    @ObservationIgnored private var feeds: [String: TerminalFeed] = [:]    public init() {}    /// The feed for one session, made on first ask.    ///    /// A feed is made by the PANE, not by an arriving frame: a frame for a    /// session nobody is watching is a frame with nowhere to go, and keeping it    /// would be an unbounded buffer for a screen that may never open.    @discardableResult    public func feed(for sessionId: String) -> TerminalFeed {        if let found = feeds[sessionId] { return found }        let made = TerminalFeed(sessionId: sessionId)        feeds[sessionId] = made        return made    }    /// The feed for one session, or nothing — the reader that must not create.    public func existing(_ sessionId: String) -> TerminalFeed? { feeds[sessionId] }    /// Forget a session's feed. Called when a pane goes away, so a session    /// nobody is watching holds no bytes.    public func release(_ sessionId: String) {        feeds.removeValue(forKey: sessionId)    }    /// One event off the stream. Everything that is not a terminal frame is    /// ignored here and read by `ClientEvent` as it always was.    public func receive(_ event: CottonEvent) {        switch event.kind {        case TerminalBus.dataKind:            guard                let session = event.payload["session"]?.string,                let bytes = event.payload["bytes"]?.string,                let feed = feeds[session]            else { return }            feed.receive(base64: bytes)        case TerminalBus.stateKind:            guard                let session = event.payload["session"]?.string,                let state = TerminalState.read(event.payload["state"]?.string),                let feed = feeds[session]            else { return }            feed.moveTo(state)        default:            return        }    }    /// How many sessions are being listened to. For the tests.    public var count: Int { feeds.count }}