// The terminal's wire, this half. The other half is `cotton-ffi`. // // **The defect this file exists for.** The four terminal methods were built in // two languages from one design page and never met: the core decoded // `{session, bytes, cols, rows}`, the pane sent `{sessionId, data}` with no // size at all. Every `terminal.attach` answered `bad_request`, the Terminal tab // drew "No terminal for this session" about a session that was running fine, // and NOTHING WAS RED — the Rust tests asserted the core's own shape and the // Swift tests asserted the pane's, and neither could see the other. It is the // same failure `MeetingAudioContractTests` was written for, one method later // (Cotton note "Repo landmines — why the build's rules exist"). // // So the wire is written down once, in `crates/cotton-ffi/src/phone/ // terminal-wire.json`, and both halves are held to THAT FILE. The crate's own // tests feed every `request` in it to the core and every `refused` shape too; // this file builds the same requests out of `CottonKit`'s boundary types and // reads the same events through `TerminalBus`. Rename a field on either side // and one of the two goes red. // // The path belongs to the RUST FFI lane. AGENTS.md's three rules for a by-path // guard are `SourceSweep.mustRead`'s: the read fails LOUDLY with the path in // the message, the lane is named here, and the path is grepped repo-wide before // it moves. // // Every value in the fixture is synthetic // ([nothing-real-ever-goes-in-cotton-s-public-tree]). import CottonKit import Foundation import XCTest @testable import CottonUI @MainActor final class TerminalWireTests: XCTestCase { private static let wirePath = "crates/cotton-ffi/src/phone/terminal-wire.json" private static let lane = "Rust FFI (the terminal's four methods, `phone/terminal.rs`)" // MARK: - The fixture private struct Wire: Decodable { struct Call: Decodable { let name: String let method: String let given: JSONValue let request: JSONValue enum CodingKeys: String, CodingKey { case name = "case" case method, given, request } } /// A shape the core answers `bad_request` to. No `given`: nothing in /// this app can produce one, which is the point of the array. struct Refused: Decodable { let name: String let method: String let request: JSONValue enum CodingKeys: String, CodingKey { case name = "case" case method, request } } struct Event: Decodable { let name: String let kind: String let given: JSONValue let payload: JSONValue enum CodingKeys: String, CodingKey { case name = "case" case kind, given, payload } } let calls: [Call] let refused: [Refused] let events: [Event] } private func wire() throws -> Wire { let text = try SourceSweep.mustRead(Self.wirePath, ownedBy: Self.lane) return try JSONDecoder().decode(Wire.self, from: Data(text.utf8)) } /// What one of this app's request types encodes to, as JSON. private func encoded(_ request: some Encodable) throws -> JSONValue { let data = try JSONEncoder().encode(request) return try JSONDecoder().decode(JSONValue.self, from: data) } /// The request the pane would send for one fixture case, built the way the /// pane builds it — through the boundary's own types, never by spelling the /// keys here. private func request(for call: Wire.Call) throws -> JSONValue { let session = try XCTUnwrap(call.given["session"]?.string, call.name) switch call.method { case CottonMethod.terminalAttach: return try encoded(TerminalAttachRequest(session: session, grid: grid(call.given))) case CottonMethod.terminalResize: return try encoded(TerminalResizeRequest(session: session, grid: grid(call.given))) case CottonMethod.terminalWrite: let bytes = (call.given["keyBytes"]?.array ?? []).compactMap(\.int).map { UInt8($0) } return try encoded(TerminalWriteRequest(session: session, bytes: bytes)) case CottonMethod.terminalDetach: return try encoded(TerminalDetachRequest(session: session)) default: XCTFail("\(call.name): \(call.method) is not one of the four verbs") return .null } } /// The grid a case measured — or the fallback, which is what an attach asks /// for before the emulator has been laid out. private func grid(_ given: JSONValue) -> TerminalGrid { guard let measured = TerminalGrid( measuredCols: given["measuredCols"]?.int ?? 0, measuredRows: given["measuredRows"]?.int ?? 0 ) else { return .fallback } return measured } // MARK: - The requests /// **Every call this pane makes, byte for byte what the core decodes.** func testEveryRequestIsTheOneTheCoreDecodes() throws { let wire = try wire() // Anti-vacuity: a loop over an empty array passes on nothing. XCTAssertGreaterThanOrEqual(wire.calls.count, 7, "the fixture read as almost nothing") for call in wire.calls { XCTAssertEqual( try request(for: call), call.request, """ \(call.name): this app encodes a shape the core does not read. \ The crate feeds the same fixture to `phone/terminal.rs`; if that half \ is green and this one is red, the boundary's request type is wrong. """ ) } } /// **The four verbs, and the shapes that are NOT sent.** /// /// The fixture's `refused` array is what the core answers `bad_request` to, /// and the whole of the old pane is in it. Nothing this app encodes may /// look like one of them. func testNothingThisAppEncodesIsAShapeTheCoreRefuses() throws { let wire = try wire() XCTAssertGreaterThanOrEqual(wire.refused.count, 5, "the fixture read as almost nothing") let refusedKeys = Set( wire.refused.flatMap { refused -> [String] in guard case .object(let members) = refused.request else { return [] } return Array(members.keys) } ) XCTAssertTrue(refusedKeys.contains("sessionId"), "the fixture no longer carries the old shape") XCTAssertTrue(refusedKeys.contains("data"), "the fixture no longer carries the old shape") // Every key of every request this app sends, against the two words the // core has never read. for call in wire.calls { guard case .object(let members) = try request(for: call) else { XCTFail("\(call.name): a request is not an object") continue } XCTAssertFalse(members.keys.contains("sessionId"), "\(call.name): the id is `session`") XCTAssertFalse(members.keys.contains("data"), "\(call.name): the bytes are `bytes`") } } // MARK: - The size /// **A view that measured nothing sends nothing** — not a 1×1 terminal. func testAViewWithNoSizeYieldsNoGrid() { XCTAssertNil(TerminalGrid(measuredCols: 0, measuredRows: 24)) XCTAssertNil(TerminalGrid(measuredCols: 80, measuredRows: 0)) XCTAssertNil(TerminalGrid(measuredCols: -1, measuredRows: -1)) } /// And a runaway measurement is clamped to the band the core accepts, /// rather than refused: a terminal a person is reading must not stop /// resizing because a layout pass reported something silly. func testAMeasurementOutsideTheBandIsClampedToTheCoresCeiling() throws { let clamped = try XCTUnwrap(TerminalGrid(measuredCols: 5_000, measuredRows: 4_000)) XCTAssertEqual(clamped.cols, TerminalGrid.maxDimension) XCTAssertEqual(clamped.rows, TerminalGrid.maxDimension) XCTAssertEqual(TerminalGrid.maxDimension, 1_000, "the core's own MAX_DIMENSION") } // MARK: - The events /// **Every event the core emits, read by the field names it emits them /// under.** func testEveryEventTheCoreEmitsReachesTheFeedThatIsWatching() throws { let wire = try wire() XCTAssertGreaterThanOrEqual(wire.events.count, 4, "the fixture read as almost nothing") for event in wire.events { let bus = TerminalBus() let session = try XCTUnwrap(event.payload["session"]?.string, event.name) let feed = bus.feed(for: session) bus.receive(CottonEvent(kind: event.kind, payload: event.payload)) switch event.kind { case TerminalEventKind.data: let expected = (event.given["bytes"]?.array ?? []).compactMap(\.int).map { UInt8($0) } XCTAssertEqual( feed.drain(), [expected], "\(event.name): the bytes did not reach the feed by the name the core sends them under" ) case TerminalEventKind.state: let word = try XCTUnwrap(event.given["state"]?.string, event.name) let expected = try XCTUnwrap( TerminalState(rawValue: word), "\(event.name): `\(word)` is a state the core sends and this build cannot read" ) XCTAssertEqual(feed.state, expected, event.name) default: XCTFail("\(event.name): \(event.kind) is not one of the two event kinds") } } } /// What `terminal.attach` ANSWERS, decoded by the shape the pane declares — /// the answer is what moves the pane off "Opening the terminal", so a build /// that could not read it would spin over a live terminal. func testTheAttachAnswerDecodesIntoTheShapeThePaneDeclares() throws { let answered = #"{"session":"s-1","state":"attached"}"# let attached = try JSONDecoder().decode(TerminalAttached.self, from: Data(answered.utf8)) XCTAssertEqual(attached.session, "s-1") XCTAssertEqual(TerminalState.read(attached.state), .attached) } }