// 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]).importCottonKitimportFoundationimport XCTest@testable importCottonUI@MainActorfinalclassTerminalWireTests: XCTestCase {privatestaticlet wirePath = "crates/cotton-ffi/src/phone/terminal-wire.json"privatestaticlet lane = "Rust FFI (the terminal's four methods, `phone/terminal.rs`)"// MARK: - The fixtureprivatestructWire: Decodable {structCall: Decodable {let name: Stringlet method: Stringlet given: JSONValuelet request: JSONValueenumCodingKeys: 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.structRefused: Decodable {let name: Stringlet method: Stringlet request: JSONValueenumCodingKeys: String, CodingKey {case name = "case"case method, request } }structEvent: Decodable {let name: Stringlet kind: Stringlet given: JSONValuelet payload: JSONValueenumCodingKeys: String, CodingKey {case name = "case"case kind, given, payload } }let calls: [Call]let refused: [Refused]let events: [Event] }privatefunc wire() throws -> Wire {let text = trySourceSweep.mustRead(Self.wirePath, ownedBy: Self.lane)returntry JSONDecoder().decode(Wire.self, from: Data(text.utf8)) }/// What one of this app's request types encodes to, as JSON.privatefunc encoded(_ request: someEncodable) throws -> JSONValue {let data = try JSONEncoder().encode(request)returntry 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.privatefunc request(for call: Wire.Call) throws -> JSONValue {let session = try XCTUnwrap(call.given["session"]?.string, call.name)switch call.method {caseCottonMethod.terminalAttach:returntry encoded(TerminalAttachRequest(session: session, grid: grid(call.given)))caseCottonMethod.terminalResize:returntry encoded(TerminalResizeRequest(session: session, grid: grid(call.given)))caseCottonMethod.terminalWrite:let bytes = (call.given["keyBytes"]?.array ?? []).compactMap(\.int).map { UInt8($0) }returntry encoded(TerminalWriteRequest(session: session, bytes: bytes))caseCottonMethod.terminalDetach:returntry 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.privatefunc grid(_ given: JSONValue) -> TerminalGrid {guardlet 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] inguardcase .object(let members) = refused.request else { return [] }returnArray(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 {guardcase .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 {caseTerminalEventKind.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" )caseTerminalEventKind.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) }}