// The session's terminal, on the phone and on the Mac. // // SwiftTerm's `TerminalView` (MIT, pinned in `Package.swift`) is the emulator: // it reads the control sequences, holds the grid and paints it. This file is // everything around it — the attach, the bytes in, the keys out, the size, and // the three things a person needs to be told when there is no picture. // // **The wrapper is ours and the emulator is not.** SwiftTerm ships a UIKit // `TerminalView` and an AppKit one with the same API, which is exactly why it // is a dependency of `CottonUI`: the phone and the Mac render the same // session's terminal, and a second emulator would be a second answer to what a // control sequence means. The two hosts below are the only platform branch, // and they are a BINDING to a framework rather than a layout decision — which // is why this file lives under `Terminal/` and not under `Screens/` // (`ScreenPlatformSweepTests`). // // **Nothing here holds a socket.** The phone opens none: `terminal.attach` // asks the core, the client dials the Mac, and the bytes arrive as // `terminal.data` events which `TerminalBus` routes to this session's feed. // Keys go back as `terminal.write`, the size as `terminal.resize`, and leaving // the tab is `terminal.detach`. // // **A build with no session host must not hang.** Until the client can reach // the helper the attach refuses, and a refusal is a sentence on the page — not // a spinner, and not an empty black rectangle that looks like a terminal // waiting for something. import CottonKit import SwiftTerm import SwiftUI #if canImport(UIKit) import UIKit #endif #if os(macOS) import AppKit #endif // The four method names and the four request shapes are `CottonKit`'s // (`Boundary+Terminal.swift`), not this file's. They were spelled here, beside // the view that sends them, and what that cost is the whole reason this pane // never drew a terminal: the names were right and every FIELD was wrong // (`{sessionId, data}` against the core's `{session, bytes, cols, rows}`), so // every attach came back `bad_request` and the pane said "No terminal for this // session" about a session that was running. A shape declared beside its view // is a shape no sweep can see; `TerminalWireTests` holds the boundary's types // to the crate's own fixture instead. // MARK: - The pane /// One session's terminal: the emulator, or the sentence saying why not. public struct TerminalPane: View { private let sessionId: String private let writer: ScreenWriter @Environment(TerminalBus.self) private var bus /// The feed this pane draws. Made on appear so a session nobody opened /// holds no bytes, and released on disappear for the same reason. @State private var feed: TerminalFeed? /// The grid last reported by the emulator, and what the next attach asks /// for. /// /// `@ObservationIgnored` in spirit — nothing draws from it — but it has to /// survive a redraw, so it is `@State`. It starts at the fallback because /// the emulator is only mounted AFTER the attach succeeds: the first attach /// cannot know the real grid, the view's first `sizeChanged` sends it a /// frame later, and a reattach (a new session id on the same pane) asks for /// the size this pane actually has. @State private var grid: TerminalGrid = .fallback public init(sessionId: String, writer: ScreenWriter) { self.sessionId = sessionId self.writer = writer } public var body: some View { Group { if let feed { content(feed) } else { TerminalNotice( headline: ShellLines.line("chrome", "terminal.opening"), detail: nil ) } } .frame(maxWidth: .infinity, alignment: .leading) .task(id: sessionId) { await open() } .onDisappear { close() } } @ViewBuilder private func content(_ feed: TerminalFeed) -> some View { VStack(alignment: .leading, spacing: 10) { if let refusal = feed.refusal { TerminalNotice(headline: ShellLines.line("chrome", "terminal.none"), detail: refusal) } else { switch feed.state { case .idle: TerminalNotice(headline: ShellLines.line("chrome", "terminal.opening"), detail: nil) case .closed: TerminalNotice( headline: ShellLines.line("chrome", "terminal.closed"), detail: ShellLines.line("chrome", "terminal.closed_detail") ) case .attached, .catchingUp: if feed.state == .catchingUp { Text("Catching up") .cottonType(.caption, ink: .tertiary) .accessibilityIdentifier("terminal-catching-up") } TerminalSurface( feed: feed, onInput: { bytes in send(bytes) }, onSize: { cols, rows in measured(cols: cols, rows: rows) } ) .frame(minHeight: 320) .accessibilityIdentifier("terminal-surface") } } } } /// Ask the core to attach, and keep the feed whatever it answers. /// /// A refusal is KEPT rather than thrown away: "this build has no session /// host" is the most useful thing the pane can say until phase 3 lands, and /// a pane that swallowed it would show an empty black rectangle instead. private func open() async { let made = bus.feed(for: sessionId) feed = made do { // THE ANSWER IS READ, not discarded: `{session, state}` is the // first word that the terminal is live, and the stream's own // `terminal.state` may not arrive until the scrollback has been // replayed. A pane that waited for it would draw "Opening the // terminal" over a terminal already painting. let answer = try await writer.call( CottonMethod.terminalAttach, TerminalAttachRequest(session: sessionId, grid: grid), as: TerminalAttached.self ) if let state = TerminalState.read(answer.state) { made.moveTo(state) } } catch let error as CottonCallError { made.refused(error.message) } catch { made.refused(String(describing: error)) } } /// Leaving the tab detaches. The helper keeps the session and its /// scrollback — detaching is this phone saying it has stopped watching, not /// anything happening to the run. private func close() { let id = sessionId bus.release(id) feed = nil let writer = writer Task { _ = try? await writer.call( CottonMethod.terminalDetach, TerminalDetachRequest(session: id) ) } } private func send(_ bytes: ArraySlice) { let id = sessionId let writer = writer Task { _ = try? await writer.call( CottonMethod.terminalWrite, TerminalWriteRequest(session: id, bytes: bytes) ) } } /// The emulator laid itself out. Keep the grid — it is what the next attach /// asks for — and tell the far end. /// /// **A view that measured nothing sends nothing.** `TerminalGrid` refuses a /// zero rather than clamping it to one: a 1×1 terminal would make the agent's /// output reflow into a single column and back again a frame later, and the /// core would refuse a zero anyway (`dimension()`, 1…1000). private func measured(cols: Int, rows: Int) { guard let measured = TerminalGrid(measuredCols: cols, measuredRows: rows) else { return } grid = measured let id = sessionId let writer = writer Task { _ = try? await writer.call( CottonMethod.terminalResize, TerminalResizeRequest(session: id, grid: measured) ) } } } /// What the pane says when there is no picture. One headline and, where the /// core gave one, its own sentence under it. struct TerminalNotice: View { let headline: String let detail: String? var body: some View { VStack(alignment: .leading, spacing: 6) { Text(headline).cottonType(.body) if let detail { Text(detail) .cottonType(.caption, ink: .tertiary) .fixedSize(horizontal: false, vertical: true) } } .frame(maxWidth: .infinity, alignment: .leading) .accessibilityIdentifier("terminal-notice") } } // MARK: - The emulator, bound to each platform's view /// The emulator itself: SwiftTerm's `TerminalView`, drained from the feed and /// reporting keys and size back. /// /// ONE coordinator, two hosts. The coordinator holds everything that is not /// `UIView`/`NSView`: the drain timer, the delegate conformance and the two /// closures. Both hosts below are five lines of framework binding over it, so /// there is no second copy of the behaviour to drift. public struct TerminalSurface: View { let feed: TerminalFeed let onInput: (ArraySlice) -> Void let onSize: (Int, Int) -> Void public init( feed: TerminalFeed, onInput: @escaping (ArraySlice) -> Void, onSize: @escaping (Int, Int) -> Void ) { self.feed = feed self.onInput = onInput self.onSize = onSize } public var body: some View { TerminalHost(feed: feed, onInput: onInput, onSize: onSize) } } /// How often the undrawn bytes are handed to the emulator. /// /// Thirty a second, which is the rate the stream coalesces at on the other /// side: a drain per frame would be a main-thread hop per PTY write, and a /// terminal writing a build log writes thousands. let terminalDrainInterval: TimeInterval = 1.0 / 30.0 /// Everything the two hosts share. @MainActor final class TerminalCoordinator: NSObject, @preconcurrency TerminalViewDelegate { // `@preconcurrency`: SwiftTerm's delegate is a pre-concurrency protocol // with no isolation of its own, and every one of its callbacks is raised // from the view's own main-thread work. Declaring the conformance as // pre-concurrency is what says so; the alternative — a nonisolated // coordinator hopping to the main actor per keystroke — would put a task // between a key and the wire for no safety anybody gains. private let feed: TerminalFeed private let onInput: (ArraySlice) -> Void private let onSize: (Int, Int) -> Void private var timer: Timer? /// The view being fed. Weak: the host owns it, and a coordinator that /// outlived a torn-down view would keep painting into it. weak var view: TerminalView? /// The last size reported, so a redraw that did not change the grid does /// not send a `terminal.resize` the far end has to act on. private var lastSize: (cols: Int, rows: Int)? init( feed: TerminalFeed, onInput: @escaping (ArraySlice) -> Void, onSize: @escaping (Int, Int) -> Void ) { self.feed = feed self.onInput = onInput self.onSize = onSize super.init() } func start() { guard timer == nil else { return } let timer = Timer.scheduledTimer(withTimeInterval: terminalDrainInterval, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.drain() } } // Common modes, so a scroll in progress does not stop the terminal: // a person dragging the page while a build runs would otherwise watch // it freeze. RunLoop.main.add(timer, forMode: .common) self.timer = timer drain() } func stop() { timer?.invalidate() timer = nil } /// Hand the emulator everything that has arrived since the last tick. func drain() { guard let view else { return } for frame in feed.drain() { view.feed(byteArray: frame[...]) } } // ── TerminalViewDelegate ────────────────────────────────────────────── func sizeChanged(source: TerminalView, newCols: Int, newRows: Int) { if let last = lastSize, last.cols == newCols, last.rows == newRows { return } lastSize = (newCols, newRows) onSize(newCols, newRows) } func setTerminalTitle(source: TerminalView, title: String) {} func hostCurrentDirectoryUpdate(source: TerminalView, directory: String?) {} /// Keys, and everything else the emulator wants to send upstream. func send(source: TerminalView, data: ArraySlice) { onInput(data) } func scrolled(source: TerminalView, position: Double) {} func requestOpenLink(source: TerminalView, link: String, params: [String: String]) {} func bell(source: TerminalView) {} func clipboardCopy(source: TerminalView, content: Data) {} func rangeChanged(source: TerminalView, startY: Int, endY: Int) {} } #if os(macOS) /// The Mac's host — AppKit's `TerminalView` in a column. struct TerminalHost: NSViewRepresentable { let feed: TerminalFeed let onInput: (ArraySlice) -> Void let onSize: (Int, Int) -> Void func makeCoordinator() -> TerminalCoordinator { TerminalCoordinator(feed: feed, onInput: onInput, onSize: onSize) } func makeNSView(context: Context) -> TerminalView { let view = TerminalView(frame: .zero) view.terminalDelegate = context.coordinator context.coordinator.view = view context.coordinator.start() return view } func updateNSView(_ view: TerminalView, context: Context) { context.coordinator.view = view context.coordinator.start() } static func dismantleNSView(_ view: TerminalView, coordinator: TerminalCoordinator) { MainActor.assumeIsolated { coordinator.stop() } } } #elseif canImport(UIKit) /// The phone's host — UIKit's `TerminalView`, which is also the keyboard /// responder: typing on it is what raises `send(source:data:)`. struct TerminalHost: UIViewRepresentable { let feed: TerminalFeed let onInput: (ArraySlice) -> Void let onSize: (Int, Int) -> Void func makeCoordinator() -> TerminalCoordinator { TerminalCoordinator(feed: feed, onInput: onInput, onSize: onSize) } func makeUIView(context: Context) -> TerminalView { let view = TerminalView(frame: .zero) view.terminalDelegate = context.coordinator view.backgroundColor = .clear context.coordinator.view = view context.coordinator.start() return view } func updateUIView(_ view: TerminalView, context: Context) { context.coordinator.view = view context.coordinator.start() } static func dismantleUIView(_ view: TerminalView, coordinator: TerminalCoordinator) { MainActor.assumeIsolated { coordinator.stop() } } } #endif