SPB Git

Repository Public

ControllerTests.swift 15.2 KB 326 lines swift

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/ControllerTests.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 ClaudeRemoteAPI89import ClaudeRemoteModels90import ClaudeRemoteTerminal91import ClaudeRemoteTestSupport92import Foundation93import SwiftTerm94import SwiftUI95import Testing9697/// The controller with a real SwiftTerm view (no window), a stub API and a scripted socket.98@MainActor99struct ControllerRig {100    let server = StubServer()101    let sockets = FakeWebSocketTransport()102    let sleeper = ManualSleeper()103    let client: APIClient104    let controller: TerminalSessionController105106    init() async throws {107        client = try APIClient(baseURL: server.baseURL, client: .test, configuration: server.configuration, webSocketTransport: sockets)108        await client.setCredential(token: "crn_test", expiresAt: .distantFuture)109        controller = TerminalSessionController(sessionId: sessionID, client: client, policy: ReconnectPolicy(random: { 0.5 }), sleeper: sleeper)110    }111112    func open() async throws -> FakeWebSocket {113        controller.connect()114        let ws = try #require(await sockets.waitForConnection(count: 1))115        #expect(await waitFor { controller.state == .open })116        return ws117    }118119    func waitFor(timeout: TimeInterval = 2, _ condition: @MainActor () -> Bool) async -> Bool {120        let deadline = Date().addingTimeInterval(timeout)121        while Date() < deadline {122            if condition() { return true }123            try? await Task.sleep(for: .milliseconds(5))124        }125        return condition()126    }127128    func sentText(_ ws: FakeWebSocket) -> String { String(decoding: ws.sentData, as: UTF8.self) }129}130131@Suite("TerminalSessionController", .serialized)132@MainActor133struct ControllerTests {134    let esc = "\u{1B}"135136    @Test func attachesWithTheViewSizeAndRendersOutput() async throws {137        let rig = try await ControllerRig()138        #expect(rig.controller.cols >= 20 && rig.controller.rows >= 5)139        #expect(rig.controller.state == .idle)140        let ws = try await rig.open()141        let url = try #require(rig.sockets.requests.first?.url?.absoluteString)142        #expect(url.contains("cols=\(rig.controller.cols)") && url.contains("rows=\(rig.controller.rows)"))143        ws.serverSend(bytes: "hello from the pty\r\n\(esc)[32mgreen\(esc)[0m")144        #expect(await rig.waitFor { rig.controller.visibleText() == "hello from the pty\ngreen" })145        #expect(rig.controller.recentText(scrollbackRows: 10).hasSuffix("green"))146        rig.controller.disconnect()147        #expect(await rig.waitFor { rig.controller.state == .idle })148        #expect(ws.clientClose?.code == 1000)149    }150151    @Test func reattachShowsOnlyTheReplayedContent() async throws {152        let rig = try await ControllerRig()153        let first = try await rig.open()154        first.serverSend(bytes: "stale line 1\r\nstale line 2\r\n\(esc)[?1049hfull screen app")155        #expect(await rig.waitFor { rig.controller.visibleText().contains("full screen app") })156        first.serverClose(code: 1006)157        #expect(await rig.waitFor { rig.sleeper.requested.contains(0.5) })158        rig.sleeper.advance(by: 0.5)159        let second = try #require(await rig.sockets.waitForConnection(count: 2))160        second.serverSend(bytes: "replayed history\r\n$ prompt")161        #expect(await rig.waitFor { rig.controller.visibleText() == "replayed history\n$ prompt" })162        #expect(await rig.waitFor { rig.controller.reconnectCount == 1 })163        #expect(rig.controller.terminalView.terminalInputStateSnapshot()?.isAlternateBuffer == false)164        rig.controller.disconnect()165    }166167    @Test func accessoryKeysHonourStickyModifiersAndApplicationCursor() async throws {168        let rig = try await ControllerRig()169        let ws = try await rig.open()170        rig.controller.send(key: .up)171        rig.controller.send(key: .ctrl)172        #expect(rig.controller.modifiers.ctrl == .oneShot)173        rig.controller.send(key: "c")174        #expect(!rig.controller.modifiers.hasAny, "a one-shot modifier is consumed by the key")175        rig.controller.send(key: .alt, doubleTap: false)176        rig.controller.send(key: .alt, doubleTap: true)177        #expect(rig.controller.modifiers.alt == .locked)178        rig.controller.send(keys: ["x", .left])179        #expect(rig.controller.modifiers.alt == .locked)180        rig.controller.send(key: .alt)181        #expect(!rig.controller.modifiers.hasAny)182        // The program switches to application cursor keys (vim, less, the agent's TUI).183        ws.serverSend(bytes: "\(esc)[?1h")184        #expect(await rig.waitFor { rig.controller.terminalView.terminalInputStateSnapshot()?.applicationCursor == true })185        rig.controller.send(key: .up)186        rig.controller.send(text: "raw")187        let expected = "\(esc)[A" + "\u{03}" + "\(esc)x" + "\(esc)[1;3D" + "\(esc)OA" + "raw"188        #expect(await ws.waitForSent { _ in ws.sentData.count == expected.utf8.count })189        #expect(rig.sentText(ws) == expected)190        rig.controller.disconnect()191    }192193    @Test func keyboardInputPassesThroughStickyModifiers() async throws {194        let rig = try await ControllerRig()195        let ws = try await rig.open()196        var typed = 0197        rig.controller.onUserInput = { typed += $0 }198        let view = rig.controller.terminalView199        // What SwiftTerm calls for soft / hardware keyboard text.200        rig.controller.send(source: view, data: Array("a".utf8)[...])201        rig.controller.modifiers.tap(.ctrl)202        rig.controller.send(source: view, data: Array("d".utf8)[...])203        rig.controller.modifiers.tap(.ctrl)204        rig.controller.send(source: view, data: Array("\(esc)[A".utf8)[...]) // sequences are left untouched205        #expect(rig.controller.modifiers.ctrl == .oneShot)206        rig.controller.modifiers = .none207        let expected = "a\u{04}\(esc)[A"208        #expect(await ws.waitForSent { _ in ws.sentData.count == expected.utf8.count })209        #expect(rig.sentText(ws) == expected)210        #expect(typed == expected.utf8.count)211        rig.controller.disconnect()212    }213214    @Test func pasteIsBracketedOnlyWhenTheProgramAsksForIt() async throws {215        let rig = try await ControllerRig()216        let ws = try await rig.open()217        rig.controller.modifiers.tap(.ctrl)218        rig.controller.paste("x")219        #expect(rig.controller.modifiers.ctrl == .oneShot, "a paste is not a key press")220        rig.controller.modifiers = .none221        #expect(await ws.waitForSent { _ in ws.sentData.count == 1 })222        ws.serverSend(bytes: "\(esc)[?2004h")223        #expect(await rig.waitFor { rig.controller.terminalView.terminalInputStateSnapshot()?.bracketedPasteMode == true })224        rig.controller.paste("echo hi\nls")225        let bracketed = "x\(esc)[200~echo hi\rls\(esc)[201~"226        #expect(await ws.waitForSent { _ in ws.sentData.count >= bracketed.utf8.count })227        let sent = rig.sentText(ws)228        #expect(sent.hasPrefix("x\(esc)[200~echo hi") && sent.hasSuffix("ls\(esc)[201~"))229        rig.controller.paste("")230        rig.controller.disconnect()231    }232233    @Test func titleBellExitAndLatencyAreObservable() async throws {234        let rig = try await ControllerRig()235        var bells = 0236        rig.controller.onBell = { bells += 1 }237        let ws = try await rig.open()238        ws.serverSend(bytes: "\(esc)]0;claude ✻ project\u{07}")239        #expect(await rig.waitFor { rig.controller.title == "claude ✻ project" })240        ws.serverSend(bytes: "\u{07}")241        #expect(await rig.waitFor { rig.controller.bellCount == 1 && bells == 1 })242        rig.sleeper.advance(by: 0.025)243        ws.serverSend(text: #"{"t":"pong","n":1}"#)244        #expect(await rig.waitFor { rig.controller.latencyMs == 25 })245        ws.serverSend(text: #"{"t":"error","code":"x","message":"something"}"#)246        ws.serverSend(text: #"{"t":"exit","code":0}"#)247        ws.serverClose(code: 4410)248        #expect(await rig.waitFor { rig.controller.state == .ended(exitCode: 0) })249        #expect(rig.controller.exitCode == 0)250        #expect(rig.controller.detail == "something")251        #expect(rig.controller.latencyMs == nil)252    }253254    @Test func untrustedProgramRequestsAreFiltered() async throws {255        let rig = try await ControllerRig()256        let c = rig.controller257        let view = c.terminalView258        var opened: [URL] = []259        c.onOpenLink = { opened.append($0) }260        c.requestOpenLink(source: view, link: "https://example.com/a?b=1", params: [:])261        c.requestOpenLink(source: view, link: "javascript:alert(1)", params: [:])262        c.requestOpenLink(source: view, link: "file:///etc/passwd", params: [:])263        c.requestOpenLink(source: view, link: "clauderemote://terminal?s=1", params: [:])264        c.requestOpenLink(source: view, link: "http://localhost:3000", params: [:])265        #expect(opened.map(\.absoluteString) == ["https://example.com/a?b=1", "http://localhost:3000"])266        // OSC 52: writes are refused unless the app opts in; reads are always refused.267        c.clipboardCopy(source: view, content: Data("secret".utf8))268        #expect(c.clipboardRead(source: view) == nil)269        var written: [String] = []270        c.onClipboardWrite = { written.append($0) }271        c.clipboardCopy(source: view, content: Data("allowed".utf8))272        #expect(written == ["allowed"])273        c.setTerminalTitle(source: view, title: "ok\u{1B}[31m\u{07}\u{9B}" + String(repeating: "x", count: 500))274        #expect(c.title.count == 200 && c.title.hasPrefix("ok[31m") && !c.title.unicodeScalars.contains { $0.value < 0x20 })275    }276277    @Test func appearanceSearchAndSelection() async throws {278        let rig = try await ControllerRig()279        let ws = try await rig.open()280        let c = rig.controller281        var appearance = TerminalAppearance(fontName: "No Such Font 123", fontSize: 15, lineSpacing: 1.0, theme: .claudeRemoteLight,282                                            cursorShape: .block, cursorBlink: false, scrollback: 800, optionAsMeta: false)283        c.apply(appearance)284        #expect(c.appearance == appearance)285        #expect(c.terminalView.font.pointSize == 15)286        #expect(c.terminalView.optionAsMetaKey == false)287        #expect(TerminalSessionController.font(for: appearance).pointSize == 15, "falls back to an installed monospaced font")288        appearance.theme = .dracula289        c.apply(appearance)290        ws.serverSend(bytes: "alpha\r\nbeta needle gamma\r\ndelta")291        #expect(await rig.waitFor { c.visibleText().contains("delta") })292        #expect(c.search("needle"))293        #expect(c.selectedText == "needle")294        #expect(!c.search("absent-term"))295        #expect(!c.search(""))296        c.clearSearch()297        c.selectAll()298        #expect(c.selectedText?.contains("alpha") == true)299        c.clearSelection()300        #expect(c.selectedText == nil)301        #expect(!c.isScrolledUp && !c.hasUnreadOutput)302        c.scrollToBottom()303        c.disconnect()304    }305306    @Test func surfaceReparentsTheSameView() async throws {307        let rig = try await ControllerRig()308        let view = rig.controller.terminalView309        #if os(macOS)310        let a = NSHostingView(rootView: TerminalSurface(controller: rig.controller, focusOnAppear: false).frame(width: 640, height: 400))311        a.frame = CGRect(x: 0, y: 0, width: 640, height: 400)312        a.layoutSubtreeIfNeeded()313        #expect(view.superview is TerminalHostView)314        let firstHost = view.superview315        let b = NSHostingView(rootView: TerminalSurface(controller: rig.controller, focusOnAppear: false).frame(width: 320, height: 200))316        b.frame = CGRect(x: 0, y: 0, width: 320, height: 200)317        b.layoutSubtreeIfNeeded()318        #expect(view.superview is TerminalHostView && view.superview !== firstHost, "moved, not duplicated")319        #expect(view === rig.controller.terminalView)320        #endif321        #expect(HexColor(0x102030).swiftTermColor.red == 0x1010)322        #expect(HexColor(0xFF0000, alpha: 0.5).platformColor.cgColor.alpha == 0.5)323        _ = view324    }325}326
Files main
Menu

Theme