Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Tests/TerminalTests/EngineTests.swift10// Module : TerminalTests11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteTerminal89import Foundation90import SwiftTerm91import Testing9293/// Headless host for the emulation engine: records what the terminal sends back to the program.94final class Host: TerminalDelegate {95 var sent: [UInt8] = []96 var title = ""97 var bells = 098 func send(source: Terminal, data: ArraySlice<UInt8>) { sent.append(contentsOf: data) }99 func setTerminalTitle(source: Terminal, title: String) { self.title = title }100 func bell(source: Terminal) { bells += 1 }101 func showCursor(source: Terminal) {}102 func hideCursor(source: Terminal) {}103 func scrolled(source: Terminal, yDisp: Int) {}104 func linefeed(source: Terminal) {}105 func mouseModeChanged(source: Terminal) {}106 func hostCurrentDirectoryUpdated(source: Terminal) {}107 func colorChanged(source: Terminal, idx: Int?) {}108 func rangeChanged(source: Terminal, startY: Int, endY: Int) {}109 var sentText: String { String(decoding: sent, as: UTF8.self) }110}111112func makeTerminal(cols: Int = 80, rows: Int = 24, scrollback: Int = 1000) -> (Terminal, Host) {113 let host = Host()114 var options = TerminalOptions.default115 options.cols = cols116 options.rows = rows117 options.scrollback = scrollback118 return (Terminal(delegate: host, options: options), host)119}120121extension Terminal {122 func line(_ row: Int) -> String { getLine(row: row)?.translateToString(trimRight: true, skipNullCellsFollowingWide: true) ?? "" }123 var cursor: (x: Int, y: Int) { getCursorLocation() }124}125126/// The same sink contract as the real view sink, on a headless engine.127final class HeadlessSink: TerminalOutputSink, @unchecked Sendable {128 let lock = NSLock()129 let terminal: Terminal130 let host: Host131 init(cols: Int = 80, rows: Int = 24) { (terminal, host) = makeTerminal(cols: cols, rows: rows) }132 func reset() { lock.withLock { terminal.feed(text: TerminalReset.sequence) } }133 func feed(_ bytes: ArraySlice<UInt8>) { lock.withLock { terminal.feed(buffer: bytes) } }134 func read<T>(_ body: (Terminal) -> T) -> T { lock.withLock { body(terminal) } }135}136137/// Pins the behaviour the kit relies on from SwiftTerm 1.99.2, fed with the kind of bytes the138/// server sends (history replay + tmux repaint in the normal buffer).139@Suite("SwiftTerm engine, headless")140struct EngineTests {141 let esc = "\u{1B}"142143 @Test func sgrColours16_256AndTrueColor() {144 let (t, _) = makeTerminal()145 t.feed(text: "\(esc)[31mR\(esc)[92mG\(esc)[38;5;208mI\(esc)[38;2;12;34;56mT\(esc)[48;2;200;100;50mB\(esc)[44mb\(esc)[0mN")146 #expect(t.getCharData(col: 0, row: 0)?.attribute.fg == .ansi256(code: 1))147 #expect(t.getCharData(col: 1, row: 0)?.attribute.fg == .ansi256(code: 10))148 #expect(t.getCharData(col: 2, row: 0)?.attribute.fg == .ansi256(code: 208))149 #expect(t.getCharData(col: 3, row: 0)?.attribute.fg == .trueColor(red: 12, green: 34, blue: 56))150 #expect(t.getCharData(col: 4, row: 0)?.attribute.bg == .trueColor(red: 200, green: 100, blue: 50))151 #expect(t.getCharData(col: 5, row: 0)?.attribute.bg == .ansi256(code: 4))152 #expect(t.getCharData(col: 6, row: 0)?.attribute.fg == .defaultColor)153 #expect(t.getCharData(col: 6, row: 0)?.attribute.bg == .defaultColor)154 #expect(t.line(0) == "RGITBbN")155 }156157 @Test func boldItalicUnderlineStyles() {158 let (t, _) = makeTerminal()159 t.feed(text: "\(esc)[1mb\(esc)[0;3mi\(esc)[0;4mu\(esc)[0;7mr\(esc)[0mn")160 #expect(t.getCharData(col: 0, row: 0)?.attribute.style.contains(.bold) == true)161 #expect(t.getCharData(col: 1, row: 0)?.attribute.style.contains(.italic) == true)162 #expect(t.getCharData(col: 2, row: 0)?.attribute.style.contains(.underline) == true)163 #expect(t.getCharData(col: 3, row: 0)?.attribute.style.contains(.inverse) == true)164 #expect(t.getCharData(col: 4, row: 0)?.attribute.style.isEmpty == true)165 }166167 @Test func cursorMovementAndPosition() {168 let (t, _) = makeTerminal()169 t.feed(text: "hello\r\nworld")170 #expect(t.line(0) == "hello" && t.line(1) == "world")171 #expect(t.cursor.x == 5 && t.cursor.y == 1)172 t.feed(text: "\(esc)[H")173 #expect(t.cursor.x == 0 && t.cursor.y == 0)174 t.feed(text: "\(esc)[10;20H")175 #expect(t.cursor.x == 19 && t.cursor.y == 9)176 t.feed(text: "\(esc)[3A\(esc)[5C\(esc)[2B\(esc)[4D")177 #expect(t.cursor.x == 20 && t.cursor.y == 8)178 t.feed(text: "\(esc)[999;999H")179 #expect(t.cursor.x == 79 && t.cursor.y == 23)180 t.feed(text: "\(esc)[2;1H\(esc)[K")181 #expect(t.line(1) == "")182 }183184 @Test func cursorPositionReportGoesBackToTheProgram() {185 let (t, host) = makeTerminal()186 t.feed(text: "\(esc)[5;7H\(esc)[6n")187 #expect(host.sentText == "\(esc)[5;7R")188 }189190 @Test func alternateScreenEnterAndLeave() {191 let (t, _) = makeTerminal()192 t.feed(text: "normal")193 #expect(!t.isCurrentBufferAlternate)194 t.feed(text: "\(esc)[?1049h\(esc)[Hfullscreen")195 #expect(t.isCurrentBufferAlternate)196 #expect(t.line(0) == "fullscreen")197 t.feed(text: "\(esc)[?1049l")198 #expect(!t.isCurrentBufferAlternate)199 #expect(t.line(0) == "normal")200 }201202 @Test func fullResetReturnsToAClearedNormalBuffer() {203 let (t, _) = makeTerminal()204 t.feed(text: "before\(esc)[?1049h\(esc)[Halt\(esc)[?2004h\(esc)[?1h\(esc)[31m")205 #expect(t.isCurrentBufferAlternate && t.bracketedPasteMode && t.applicationCursor)206 t.feed(text: TerminalReset.sequence)207 #expect(!t.isCurrentBufferAlternate)208 #expect(!t.bracketedPasteMode)209 #expect(!t.applicationCursor)210 #expect(t.line(0) == "")211 #expect(t.cursor.x == 0 && t.cursor.y == 0)212 t.feed(text: "x")213 #expect(t.getCharData(col: 0, row: 0)?.attribute.fg == .defaultColor)214 }215216 @Test func unicodeEmojiAndWideCharacters() {217 let (t, _) = makeTerminal()218 t.feed(text: "é漢字")219 #expect(t.line(0) == "é漢字")220 #expect(t.cursor.x == 5, "two wide characters take two cells each")221 t.feed(text: "\r\na😀b")222 #expect(t.line(1) == "a😀b")223 #expect(t.cursor.x == 4)224 t.feed(text: "\r\n╭─╮ ✻ ⠋ →")225 #expect(t.line(2) == "╭─╮ ✻ ⠋ →")226 // UTF-8 split across two feeds (frame boundary in the stream).227 let bytes = Array("\r\nñandú".utf8)228 t.feed(buffer: bytes[0..<3])229 t.feed(buffer: bytes[3...])230 #expect(t.line(3) == "ñandú")231 }232233 @Test func bracketedPasteAndApplicationCursorModes() {234 let (t, _) = makeTerminal()235 #expect(!t.bracketedPasteMode && !t.applicationCursor)236 t.feed(text: "\(esc)[?2004h")237 #expect(t.bracketedPasteMode)238 t.feed(text: "\(esc)[?2004l")239 #expect(!t.bracketedPasteMode)240 t.feed(text: "\(esc)[?1h")241 #expect(t.applicationCursor)242 #expect(KeyEncoder.sequence(for: .up, applicationCursor: t.applicationCursor) == "\(esc)OA")243 t.feed(text: "\(esc)[?1l")244 #expect(!t.applicationCursor)245 }246247 @Test func scrollbackGrowsAndIsBounded() {248 let (t, _) = makeTerminal(cols: 40, rows: 10, scrollback: 50)249 for i in 0..<30 { t.feed(text: "line \(i)\r\n") }250 #expect(t.buffer.yDisp == 21, "30 lines + the cursor line on a 10-row screen")251 #expect(t.line(0) == "line 21")252 #expect(t.getScrollInvariantLine(row: 0)?.translateToString(trimRight: true) == "line 0")253 for i in 30..<200 { t.feed(text: "line \(i)\r\n") }254 #expect(t.buffer.yDisp == 50, "history is capped at the configured scrollback")255 #expect(t.line(8) == "line 199")256 }257258 /// Why `TerminalReset.sequence` is more than `ESC c`.259 @Test func bareRISFromTheAlternateScreenKeepsTheCursorColumn() {260 let (t, _) = makeTerminal()261 t.feed(text: "before\(esc)[?1049h\(esc)[Halt\(esc)c")262 #expect(!t.isCurrentBufferAlternate && t.line(0) == "")263 withKnownIssue("SwiftTerm 1.99.2: RIS issued on the alternate screen keeps the cursor column") {264 #expect(t.cursor.x == 0)265 }266 }267268 @Test func titleAndBell() {269 let (t, host) = makeTerminal()270 t.feed(text: "\(esc)]0;claude — project\u{07}")271 #expect(host.title == "claude — project")272 t.feed(text: "\(esc)]2;second\(esc)\\")273 #expect(host.title == "second")274 t.feed(text: "\u{07}\u{07}")275 #expect(host.bells == 2)276 }277278 @Test func reattachResetThenReplayLeavesExactlyTheReplay() {279 let sink = HeadlessSink(cols: 40, rows: 10)280 // First attach: history, a full-screen program, modes set by the program.281 sink.reset()282 for i in 0..<40 { sink.feed(Array("old \(i)\r\n".utf8)[...]) }283 sink.feed(Array("\(esc)[?1049h\(esc)[?2004h\(esc)[?1h\(esc)[41mjunk".utf8)[...])284 #expect(sink.read { $0.isCurrentBufferAlternate })285 // Re-attach: the server replays the history then repaints the live screen (normal buffer).286 sink.reset()287 sink.read { t in288 #expect(t.buffer.yDisp == 0, "the old scrollback is gone")289 #expect(t.cursor.x == 0 && t.cursor.y == 0)290 }291 sink.feed(Array("replayed 1\r\nreplayed 2\r\n$ live prompt".utf8)[...])292 sink.read { t in293 #expect(!t.isCurrentBufferAlternate && !t.bracketedPasteMode && !t.applicationCursor)294 #expect(t.buffer.yDisp == 0)295 #expect(t.line(0) == "replayed 1" && t.line(1) == "replayed 2" && t.line(2) == "$ live prompt")296 #expect(t.line(3) == "")297 #expect(t.getCharData(col: 0, row: 0)?.attribute.bg == .defaultColor)298 for row in 0..<10 { #expect(!t.line(row).contains("old") && !t.line(row).contains("junk")) }299 }300 }301}302