// 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.importCottonKitimportSwiftTermimportSwiftUI#if canImport(UIKit)import UIKit#endif#if os(macOS)importAppKit#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.publicstructTerminalPane: View {privatelet sessionId: Stringprivatelet writer: ScreenWriter @Environment(TerminalBus.self) privatevar 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 privatevar 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 privatevar grid: TerminalGrid = .fallbackpublicinit(sessionId: String, writer: ScreenWriter) {self.sessionId = sessionIdself.writer = writer }publicvar body: someView {Group {iflet feed { content(feed) } else {TerminalNotice( headline: ShellLines.line("chrome", "terminal.opening"), detail: nil ) } } .frame(maxWidth: .infinity, alignment: .leading) .task(id: sessionId) { awaitopen() } .onDisappear { close() } } @ViewBuilder privatefunc content(_ feed: TerminalFeed) -> someView { VStack(alignment: .leading, spacing: 10) {iflet 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.privatefuncopen() async {let made = bus.feed(for: sessionId) feed = madedo {// 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 = tryawait writer.call(CottonMethod.terminalAttach,TerminalAttachRequest(session: sessionId, grid: grid),as: TerminalAttached.self )iflet state = TerminalState.read(answer.state) { made.moveTo(state) } } catchlet error asCottonCallError { 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.privatefunc close() {let id = sessionId bus.release(id) feed = nillet writer = writerTask { _ = try? await writer.call(CottonMethod.terminalDetach,TerminalDetachRequest(session: id) ) } }privatefunc send(_ bytes: ArraySlice<UInt8>) {let id = sessionIdlet writer = writerTask { _ = 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).privatefunc measured(cols: Int, rows: Int) {guardlet measured = TerminalGrid(measuredCols: cols, measuredRows: rows) else { return } grid = measuredlet id = sessionIdlet writer = writerTask { _ = 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.structTerminalNotice: View {let headline: Stringlet detail: String?var body: someView { VStack(alignment: .leading, spacing: 6) {Text(headline).cottonType(.body)iflet 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.publicstructTerminalSurface: View {let feed: TerminalFeedlet onInput: (ArraySlice<UInt8>) -> Voidlet onSize: (Int, Int) -> Voidpublicinit( feed: TerminalFeed, onInput: @escaping (ArraySlice<UInt8>) -> Void, onSize: @escaping (Int, Int) -> Void ) {self.feed = feedself.onInput = onInputself.onSize = onSize }publicvar body: someView {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.@MainActorfinalclassTerminalCoordinator: 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.privatelet feed: TerminalFeedprivatelet onInput: (ArraySlice<UInt8>) -> Voidprivatelet onSize: (Int, Int) -> Voidprivatevar 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.weakvar 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.privatevar lastSize: (cols: Int, rows: Int)?init( feed: TerminalFeed, onInput: @escaping (ArraySlice<UInt8>) -> Void, onSize: @escaping (Int, Int) -> Void ) {self.feed = feedself.onInput = onInputself.onSize = onSizesuper.init() }func start() {guard timer == nilelse { return }let timer = Timer.scheduledTimer(withTimeInterval: terminalDrainInterval, repeats: true) { [weakself] _ inMainActor.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() {guardlet view else { return }for frame in feed.drain() { view.feed(byteArray: frame[...]) } }// ── TerminalViewDelegate ──────────────────────────────────────────────func sizeChanged(source: TerminalView, newCols: Int, newRows: Int) {iflet 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<UInt8>) { 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.structTerminalHost: NSViewRepresentable {let feed: TerminalFeedlet onInput: (ArraySlice<UInt8>) -> Voidlet onSize: (Int, Int) -> Voidfunc 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() }staticfunc 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:)`.structTerminalHost: UIViewRepresentable {let feed: TerminalFeedlet onInput: (ArraySlice<UInt8>) -> Voidlet onSize: (Int, Int) -> Voidfunc 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() }staticfunc dismantleUIView(_ view: TerminalView, coordinator: TerminalCoordinator) {MainActor.assumeIsolated { coordinator.stop() } } }#endif