Repository Public
1import AppKit2import Foundation3import PTYProcess4import SettingsModel5import DesignSystem6import Testing7@testable import TerminalCore89@Suite("Shells and launch planning")10struct LaunchTests {11 @Test func shellsFileParsing() {12 let text = "# List of acceptable shells\n\n/bin/bash\n/bin/zsh # default\nnot-a-path\n /opt/homebrew/bin/fish \n"13 #expect(ShellCatalog.parseShellsFile(text) == ["/bin/bash", "/bin/zsh", "/opt/homebrew/bin/fish"])14 }1516 @Test func installedShellsExistAndIncludeTheDefault() {17 let shells = ShellCatalog.installedShells()18 #expect(!shells.isEmpty)19 #expect(shells.allSatisfy { FileManager.default.isExecutableFile(atPath: $0.path) })20 #expect(shells.first?.path == ShellCatalog.defaultShell())21 #expect(shells.contains { $0.name == "zsh" })22 #expect(shells.contains { $0.name == "bash" })23 // Only shells that really exist are offered.24 let none = ShellCatalog.installedShells(isExecutable: { _ in false })25 #expect(none.isEmpty)26 }2728 @Test func loginShellUsesDashArgv0() {29 let plan = LaunchPlanner.plan(.shell(path: "/bin/zsh", login: true), workingDirectory: "/tmp", columns: 100, rows: 30, appVersion: "9.9")30 #expect(plan.executable == "/bin/zsh")31 #expect(plan.arguments == ["-zsh"])32 #expect(plan.workingDirectory == "/tmp")33 #expect(plan.columns == 100 && plan.rows == 30)34 #expect(LaunchPlanner.plan(.shell(path: "/bin/bash", login: false), workingDirectory: nil, columns: 80, rows: 24, appVersion: "1").arguments == ["bash"])35 }3637 @Test func environmentIsCleanAndComplete() {38 let base = ["HOME": "/Users/x", "PATH": "/usr/bin", "TERM": "dumb", "DYLD_INSERT_LIBRARIES": "/evil.dylib", "XPC_SERVICE_NAME": "app",39 "OS_ACTIVITY_DT_MODE": "YES", "COLUMNS": "10", "SSH_AUTH_SOCK": "/tmp/agent", "TERM_PROGRAM": "Apple_Terminal", "EDITOR": "vim"]40 let env = LaunchPlanner.environment(base: base, shell: "/bin/zsh", appVersion: "1.2.3", extra: ["SPTERM_PANE": "p1"])41 #expect(env["TERM"] == "xterm-256color")42 #expect(env["COLORTERM"] == "truecolor")43 #expect(env["TERM_PROGRAM"] == "SPTerm")44 #expect(env["TERM_PROGRAM_VERSION"] == "1.2.3")45 #expect(env["SHELL"] == "/bin/zsh")46 #expect(env["SSH_AUTH_SOCK"] == "/tmp/agent")47 #expect(env["EDITOR"] == "vim")48 #expect(env["DYLD_INSERT_LIBRARIES"] == nil)49 #expect(env["XPC_SERVICE_NAME"] == nil)50 #expect(env["OS_ACTIVITY_DT_MODE"] == nil)51 #expect(env["COLUMNS"] == nil)52 #expect(env["LANG"]?.hasSuffix(".UTF-8") == true)53 #expect(env["SPTERM_PANE"] == "p1")54 // An existing locale choice is respected.55 #expect(LaunchPlanner.environment(base: ["LC_ALL": "C"], shell: "/bin/sh", appVersion: "1")["LANG"] == nil)56 }5758 @Test func missingDirectoryFallsBackToHome() {59 let plan = LaunchPlanner.plan(.shell(path: nil, login: true), workingDirectory: "/definitely/not/here", columns: 80, rows: 24,60 appVersion: "1", baseEnvironment: ["HOME": "/Users/someone"])61 #expect(plan.workingDirectory == "/Users/someone")62 }6364 @Test func commandLineAndProgramRequests() {65 let command = LaunchPlanner.plan(.commandLine("claude --resume", shell: "/bin/zsh"), workingDirectory: nil, columns: 80, rows: 24, appVersion: "1")66 #expect(command.arguments == ["zsh", "-l", "-i", "-c", "claude --resume"])67 let program = LaunchPlanner.plan(.program(executable: "/usr/bin/ssh", arguments: ["--", "host"]), workingDirectory: nil, columns: 80, rows: 24, appVersion: "1")68 #expect(program.executable == "/usr/bin/ssh")69 #expect(program.arguments == ["ssh", "--", "host"])70 }7172 @Test func droppedPathsAreEscapedForTheShell() {73 #expect(ShellEscaping.escapePath("/tmp/plain.txt") == "/tmp/plain.txt")74 #expect(ShellEscaping.escapePath("/tmp/my file (1).txt") == #"/tmp/my\ file\ \(1\).txt"#)75 #expect(ShellEscaping.escapePath("/tmp/it's $HOME & `x`") == #"/tmp/it\'s\ \$HOME\ \&\ \`x\`"#)76 #expect(ShellEscaping.escapePath("/tmp/a\nb") == #"$'/tmp/a\nb'"#)77 #expect(ShellEscaping.escapePath("") == "''")78 #expect(ShellEscaping.escapePaths(["/a b", "/c"]) == #"/a\ b /c "#)79 }8081 @Test func escapedPathsSurviveARealShell() throws {82 let names = ["plain", "with space", "quote'single", "dq\"double", "dollar$HOME", "semi;colon", "amp&ersand", "star*glob?",83 "paren(1)", "back\\slash", "tick`cmd`", "pipe|bang!", "tilde~hash#", "new\nline", "tab\there", "émoji 👩💻", "-dash"]84 for name in names {85 let path = "/tmp/spterm test/" + name86 let process = Process()87 process.executableURL = URL(fileURLWithPath: "/bin/zsh")88 process.arguments = ["-f", "-c", "printf '%s' " + ShellEscaping.escapePath(path)]89 let pipe = Pipe()90 process.standardOutput = pipe91 try process.run()92 process.waitUntilExit()93 let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)94 #expect(output == path, "round trip failed for \(name.debugDescription)")95 }96 }9798 @Test func workingDirectoryReports() {99 #expect(WorkingDirectoryReport.path(from: "file://mac.local/Users/me/My%20Project") == "/Users/me/My Project")100 #expect(WorkingDirectoryReport.path(from: "/plain/path") == "/plain/path")101 #expect(WorkingDirectoryReport.path(from: "https://example.com/x") == nil)102 #expect(WorkingDirectoryReport.remoteHost(from: "file://server1/home/me", localHostNames: ["mac"]) == "server1")103 #expect(WorkingDirectoryReport.remoteHost(from: "file://mac/Users/me", localHostNames: ["mac"]) == nil)104 #expect(WorkingDirectoryReport.remoteHost(from: "file:///Users/me", localHostNames: ["mac"]) == nil)105 }106}107108@Suite("Paste and broadcast guards")109struct PasteGuardTests {110 @Test func assessment() {111 let single = PasteGuard.assess("ls -la")112 #expect(!single.isMultiline && !single.isSuspicious && single.lineCount == 1)113 let multi = PasteGuard.assess("cd /tmp\r\nsudo rm -rf x\n")114 #expect(multi.isMultiline && multi.lineCount == 2 && multi.endsWithNewline && multi.mentionsSudo)115 let escape = PasteGuard.assess("echo hi\u{1b}[201~\nrm -rf ~\n")116 #expect(escape.containsBracketEscape && escape.containsControlCharacters && escape.isSuspicious)117 #expect(PasteGuard.assess("tab\tseparated").containsControlCharacters == false)118 #expect(PasteGuard.assess("pseudosudoku").mentionsSudo == false)119 }120121 @Test func decisions() {122 let multi = PasteGuard.assess("a\nb")123 let single = PasteGuard.assess("a")124 let withNewline = PasteGuard.assess("a\n")125 let hostile = PasteGuard.assess("a\u{1b}[201~b")126 #expect(PasteGuard.decide(multi, policy: .multiline) == .confirm)127 #expect(PasteGuard.decide(single, policy: .multiline) == .allow)128 #expect(PasteGuard.decide(withNewline, policy: .multiline) == .confirm)129 #expect(PasteGuard.decide(multi, policy: .never) == .allow)130 #expect(PasteGuard.decide(single, policy: .always) == .confirm)131 // Escape injection always asks, even when confirmations are turned off.132 #expect(PasteGuard.decide(hostile, policy: .never) == .confirm)133 }134135 @Test func sanitizeRemovesControlSequences() {136 let cleaned = PasteGuard.sanitize("echo hi\u{1b}[201~\r\nrm -rf ~\u{07}\u{9b}\n\n")137 #expect(cleaned == "echo hi\nrm -rf ~")138 #expect(!PasteGuard.assess(cleaned).isSuspicious)139 #expect(PasteGuard.sanitize("keep\ttabs\n", stripTrailingNewline: false) == "keep\ttabs\n")140 }141142 @Test func broadcastLineTrackerSeesTheLineBeforeReturn() {143 var tracker = BroadcastGuard.LineTracker()144 #expect(tracker.consume(Array("rm -rf /tmx".utf8)) == .passthrough)145 #expect(tracker.consume([0x7f]) == .passthrough) // backspace146 #expect(tracker.consume(Array("p".utf8)) == .passthrough)147 #expect(tracker.pending == "rm -rf /tmp")148 #expect(tracker.consume([0x0d]) == .line("rm -rf /tmp"))149 #expect(tracker.pending == "")150 _ = tracker.consume(Array("abc def".utf8))151 _ = tracker.consume([0x17]) // Ctrl+W152 #expect(tracker.pending == "abc ")153 _ = tracker.consume([0x15]) // Ctrl+U154 #expect(tracker.pending == "")155 #expect(tracker.consume(Array("ls\r".utf8)) == .line("ls"))156 }157}158159/// Real sessions: PTY + emulation engine + view, without a window.160@Suite("Terminal session integration", .serialized)161@MainActor162struct SessionIntegrationTests {163 func wait(_ timeout: TimeInterval = 8, _ condition: @MainActor () -> Bool) async -> Bool {164 let deadline = Date().addingTimeInterval(timeout)165 while Date() < deadline {166 if condition() { return true }167 try? await Task.sleep(for: .milliseconds(25))168 }169 return condition()170 }171172 @Test func shellSessionRunsCommandsAndTracksState() async throws {173 let dir = String(cString: realpath(NSTemporaryDirectory(), nil))174 let session = TerminalSession(request: .shell(path: "/bin/zsh", login: false), workingDirectory: dir,175 extraEnvironment: ["ZDOTDIR": "/var/empty"])176 #expect(session.status == .notStarted)177 session.start()178 #expect(session.status.isRunning)179 // /etc/zshrc sets the prompt ("user@host dir % "); wait for it rather than for a custom one.180 #expect(await wait { session.bufferText().contains("% ") })181 session.send(text: "echo $TERM $COLORTERM $TERM_PROGRAM; printf '\\033]0;custom-title\\007'\r")182 #expect(await wait { session.bufferText().contains("xterm-256color truecolor SPTerm") })183 #expect(await wait { session.reportedTitle == "custom-title" })184 session.refreshProcessState()185 #expect(session.workingDirectory == dir)186 #expect(!session.isBusy)187 #expect(session.foregroundProcessName == "zsh")188 // A running command makes the session busy; Ctrl+C returns it to the prompt.189 session.send(text: "sleep 30\r")190 #expect(await wait { session.refreshProcessState(); return session.hasForegroundJob })191 #expect(session.isBusy)192 #expect(session.foregroundProcessName == "sleep")193 session.send(bytes: [0x03])194 #expect(await wait { session.refreshProcessState(); return !session.hasForegroundJob })195 // cd is followed by probing when the shell does not report OSC 7.196 session.send(text: "cd /usr/lib\r")197 #expect(await wait { session.refreshProcessState(); return session.workingDirectory == "/usr/lib" })198 session.send(text: "exit 4\r")199 #expect(await wait { session.status == .exited(.exited(code: 4)) })200 #expect(await wait { session.bufferText().contains("[process exited with code 4]") })201 #expect(session.endedAt != nil)202 }203204 @Test func resizeReachesTheProgram() async throws {205 let session = TerminalSession(request: .shell(path: "/bin/sh", login: false), extraEnvironment: ["PS1": "ready> "])206 session.start()207 #expect(await wait { session.bufferText().contains("ready> ") })208 session.view.setFrameSize(NSSize(width: 1300, height: 700))209 #expect(await wait { session.columns > 100 })210 let expected = "\(session.rows) \(session.columns)"211 session.send(text: "stty size\r")212 #expect(await wait { session.bufferText().contains(expected) }, "expected stty to print \(expected)")213 session.terminate()214 #expect(await wait { !session.status.isRunning })215 }216217 @Test func osc7ReportUpdatesDirectoryAndRestartKeepsScrollback() async throws {218 let session = TerminalSession(request: .shell(path: "/bin/sh", login: false), extraEnvironment: ["PS1": "ready> "])219 session.start()220 #expect(await wait { session.bufferText().contains("ready> ") })221 session.send(text: "printf '\\033]7;file://localhost/usr/share\\007'; echo first-run\r")222 #expect(await wait { session.workingDirectory == "/usr/share" })223 let firstPID = session.pid224 session.restart()225 #expect(session.status.isRunning)226 #expect(session.pid != firstPID)227 #expect(await wait { session.bufferText().contains("new process started") })228 #expect(session.bufferText().contains("first-run"))229 session.send(text: "pwd\r")230 #expect(await wait { session.bufferText().contains("\n/usr/share") })231 session.terminate()232 #expect(await wait { !session.status.isRunning })233 }234235 @Test func launchFailureIsReportedNotFatal() async {236 let session = TerminalSession(request: .program(executable: "/nonexistent/program", arguments: []))237 session.start()238 if case .failed = session.status {} else { Issue.record("expected failed status, got \(session.status)") }239 #expect(await wait { session.bufferText().contains("could not start the session") })240 }241242 @Test func userInputTapOnlySeesUserInput() async throws {243 let session = TerminalSession(request: .program(executable: "/bin/cat", arguments: []))244 var tapped: [UInt8] = []245 session.userInputTap = { tapped.append(contentsOf: $0) }246 session.start()247 // A reply generated by the emulator (cursor position report) is not user input…248 session.view.feed(text: "\u{1b}[6n")249 try await Task.sleep(for: .milliseconds(300))250 #expect(tapped.isEmpty)251 // …typed text is.252 session.view.typeText("typed")253 #expect(String(decoding: tapped, as: UTF8.self) == "typed")254 session.terminate()255 #expect(await wait { !session.status.isRunning })256 }257258 @Test func themeAndSettingsApply() {259 let session = TerminalSession(request: .shell(path: "/bin/sh", login: false))260 var settings = AppSettings()261 settings.fontSize = 18262 settings.fontName = "Menlo"263 session.apply(settings: settings, theme: ThemeCatalog.daylight)264 #expect(session.view.font.pointSize == 18)265 #expect(session.view.font.familyName == "Menlo")266 #expect(session.view.nativeBackgroundColor.usingColorSpace(.sRGB)?.redComponent ?? 0 > 0.9)267 settings.fontName = "No Such Font 123"268 settings.fontSize = 6269 session.apply(settings: settings, theme: ThemeCatalog.graphite)270 #expect(session.view.font.isFixedPitch)271 #expect(session.view.font.pointSize == 6)272 #expect(TerminalSession.monospacedFontFamilies().first == "SF Mono")273 #expect(TerminalSession.monospacedFontFamilies().contains("Menlo"))274 }275}276