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/Sources/ClaudeRemoteTerminal/TerminalSessionController.swift10// Module : ClaudeRemoteTerminal11// 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 Foundation91import Observation92import SwiftTerm9394#if os(macOS)95import AppKit96public typealias PlatformFont = NSFont97public typealias PlatformColor = NSColor98#else99import UIKit100public typealias PlatformFont = UIFont101public typealias PlatformColor = UIColor102#endif103104/// The byte sequence fed to the emulator before every (re)attach: leave the alternate screen,105/// RIS (full reset: modes, attributes, buffer and scrollback), erase scrollback, cursor home.106/// Same effect as xterm.js `term.reset()` in the web client.107///108/// `ESC c` alone is not enough with SwiftTerm 1.99.2: issued while the alternate screen is109/// active it switches back to a cleared normal buffer but keeps the alternate cursor column,110/// so the replay would start mid-line (pinned by `EngineTests`).111public enum TerminalReset {112 public static let sequence = "\u{1B}[?1049l\u{1B}c\u{1B}[3J\u{1B}[H"113}114115/// Feeds a SwiftTerm view through its thread-safe `feedSender` (parsing happens on the caller's116/// thread — the connection's receive task — never on the main thread).117public struct SwiftTermOutputSink: TerminalOutputSink {118 private let sender: TerminalFeedSender119 public init(sender: TerminalFeedSender) { self.sender = sender }120 public func reset() { sender.feed(text: TerminalReset.sequence) }121 public func feed(_ bytes: ArraySlice<UInt8>) { sender.feed(byteArray: bytes) }122}123124public enum TerminalSearchDirection: Sendable, Hashable { case next, previous }125126public struct TerminalSearchOptions: Sendable, Hashable {127 public var caseSensitive: Bool128 public var regex: Bool129 public var wholeWord: Bool130 public init(caseSensitive: Bool = false, regex: Bool = false, wholeWord: Bool = false) {131 self.caseSensitive = caseSensitive132 self.regex = regex133 self.wholeWord = wholeWord134 }135}136137/// One terminal session on screen: a SwiftTerm view and the stream that feeds it.138///139/// The controller is independent of any window: moving it between tabs, splits or scenes only140/// re-parents `terminalView` (through `TerminalSurface`); the stream, scrollback and emulator141/// state are untouched. Keep one controller per session id for as long as the session is open in142/// the UI, and call `disconnect()` when it is closed.143///144/// - Important: never animate the frame of a container holding the terminal view. Every145/// intermediate size is a terminal resize (reflow + a `resize` message to the server). Change146/// layouts without animation (`.transaction { $0.animation = nil }`) or cross-fade a snapshot.147@MainActor148@Observable149public final class TerminalSessionController: Identifiable, TerminalViewDelegate {150 public nonisolated let sessionId: String151 public nonisolated var id: String { sessionId }152153 /// Stream state (drives overlays: reconnecting, ended, sign-in again…).154 public private(set) var state: TerminalConnectionState = .idle155 /// Round trip of the last ping.156 public private(set) var latencyMs: Int?157 /// Title set by the running program (OSC 0 / 2), sanitised.158 public private(set) var title: String = ""159 public private(set) var bellCount = 0160 /// Exit code reported by the server when the session process ended.161 public private(set) var exitCode: Int?162 /// Human-readable detail of the last problem.163 public private(set) var detail: String?164 public private(set) var reconnectCount = 0165 public private(set) var cols: Int166 public private(set) var rows: Int167 /// The viewport left the bottom of the buffer.168 public private(set) var isScrolledUp = false169 /// Output arrived while scrolled up.170 public private(set) var hasUnreadOutput = false171 public private(set) var appearance: TerminalAppearance172 /// Sticky modifiers of the accessory key row. Applied to the next key of the row and to the173 /// next single character typed on the (soft or hardware) keyboard.174 public var modifiers = StickyModifiers()175176 /// The SwiftTerm view. Embed it with `TerminalSurface(controller:)`; do not add it to a view177 /// hierarchy yourself.178 @ObservationIgnored public let terminalView: TerminalView179 @ObservationIgnored public let connection: TerminalConnection180 @ObservationIgnored public var onBell: (() -> Void)?181 /// A program asked to open a link (OSC 8 or a detected URL). Only http(s) URLs get here.182 @ObservationIgnored public var onOpenLink: ((URL) -> Void)?183 /// A program wants to write the clipboard (OSC 52). Nil (default) = refused. Reads are always refused.184 @ObservationIgnored public var onClipboardWrite: ((String) -> Void)?185 /// Bytes typed by the user (after sticky modifiers), e.g. to mark the session as active.186 @ObservationIgnored public var onUserInput: ((Int) -> Void)?187188 @ObservationIgnored private let tasks = TaskBag()189 @ObservationIgnored private var isPasting = false190 @ObservationIgnored private var scrollRefreshScheduled = false191 @ObservationIgnored private var started = false192193 public init(sessionId: String, client: APIClient, appearance: TerminalAppearance = TerminalAppearance(),194 policy: ReconnectPolicy = .standard, sleeper: any Sleeper = SystemSleeper()) {195 self.sessionId = sessionId196 self.appearance = appearance197 var options = TerminalOptions.default198 options.scrollback = appearance.scrollback199 let view = TerminalView(frame: CGRect(x: 0, y: 0, width: 800, height: 480), font: Self.font(for: appearance), options: options)200 terminalView = view201 let dims = view.terminalDimensions202 cols = dims.cols203 rows = dims.rows204 connection = TerminalConnection(client: client, sessionId: sessionId, sink: SwiftTermOutputSink(sender: view.feedSender),205 policy: policy, sleeper: sleeper)206 view.terminalDelegate = self207 #if os(iOS)208 // The app supplies its own configurable key row (see `TerminalKey`, `send(key:)`).209 view.inputAccessoryView = nil210 view.autocorrectionType = .no211 view.autocapitalizationType = .none212 #endif213 applyToView(appearance)214 let events = connection.events215 tasks.add(Task { [weak self] in216 for await event in events {217 guard let self else { return }218 self.handle(event)219 }220 })221 }222223 deinit {224 tasks.cancelAll()225 let connection = connection226 Task { await connection.stop() }227 }228229 // MARK: Connection230231 /// Attaches to the session stream with the current size. Idempotent.232 public func connect() {233 started = true234 let dims = terminalView.terminalDimensions235 (cols, rows) = (dims.cols, dims.rows)236 let (c, r) = (cols, rows)237 Task { [connection] in await connection.start(cols: c, rows: r) }238 }239240 /// Detaches (the session keeps running on the server).241 public func disconnect() {242 started = false243 Task { [connection] in await connection.stop() }244 }245246 /// Call when the app becomes active or the network path becomes satisfied.247 public func wake() {248 Task { [connection] in await connection.wake() }249 }250251 /// Call when the network path becomes unsatisfied.252 public func networkBecameUnavailable() {253 Task { [connection] in await connection.networkBecameUnavailable() }254 }255256 /// Re-attaches now — e.g. after `APIClient.reconnectSession(id:restart:)` restarted a257 /// recoverable session. Never creates a process by itself.258 public func reconnectNow() {259 started = true260 Task { [connection] in await connection.reconnectNow() }261 }262263 private func handle(_ event: TerminalConnectionEvent) {264 switch event {265 case .state(let s):266 state = s267 if s == .open {268 exitCode = nil269 isScrolledUp = false270 hasUnreadOutput = false271 terminalView.setCursorStyle(Self.cursorStyle(appearance)) // RIS resets it272 }273 if case .ended(let code) = s, let code { exitCode = code }274 case .latency(let ms): latencyMs = ms275 case .exit(let code): exitCode = code276 case .detail(let d): detail = d277 case .reconnected(let count): reconnectCount = count278 case .ready: break279 case .activity:280 if isScrolledUp, !hasUnreadOutput { hasUnreadOutput = true }281 }282 }283284 // MARK: Input285286 /// Sends text to the PTY exactly as given (no sticky modifiers, no bracketed paste).287 public func send(text: String) {288 connection.send(text: text)289 }290291 /// Sends raw bytes to the PTY.292 public func send(data: Data) {293 connection.send(data)294 }295296 /// A key of the accessory row: toggles a sticky modifier, or sends the key honouring the297 /// sticky modifiers and the application cursor mode of the running program.298 /// - Parameter doubleTap: for modifier keys, a double tap locks the modifier.299 public func send(key: TerminalKey, doubleTap: Bool = false) {300 if let modifier = key.modifier {301 modifiers.tap(modifier, doubleTap: doubleTap)302 return303 }304 let appCursor = terminalView.terminalInputStateSnapshot()?.applicationCursor ?? false305 connection.send(text: KeyEncoder.sequence(for: key, modifiers: modifiers, applicationCursor: appCursor))306 if modifiers.hasAny { modifiers.consume() }307 }308309 /// Several keys in order (one-shot modifiers apply to the first non-modifier key).310 public func send(keys: [TerminalKey]) {311 for key in keys { send(key: key) }312 }313314 /// Pastes text through the emulator: bracketed when the program enabled bracketed paste315 /// (DECSET 2004), control bytes sanitised.316 public func paste(_ text: String) {317 guard !text.isEmpty else { return }318 isPasting = true319 defer { isPasting = false }320 terminalView.pasteText(text)321 }322323 /// Pastes the general pasteboard's text. Returns false when it holds no text.324 @discardableResult325 public func pasteFromClipboard() -> Bool {326 #if os(macOS)327 let text = NSPasteboard.general.string(forType: .string)328 #else329 let text = UIPasteboard.general.string330 #endif331 guard let text, !text.isEmpty else { return false }332 paste(text)333 return true334 }335336 // MARK: Selection, search, content337338 public var selectedText: String? {339 guard terminalView.selectionActive, let text = terminalView.getSelection(), !text.isEmpty else { return nil }340 return text341 }342343 /// Copies the selection to the general pasteboard. Returns false when nothing is selected.344 @discardableResult345 public func copySelection() -> Bool {346 guard let text = selectedText else { return false }347 Self.writePasteboard(text)348 return true349 }350351 public func selectAll() { terminalView.selectAll() }352 public func clearSelection() { terminalView.selectNone() }353354 /// Finds the next / previous match in the scrollback, selects it and scrolls it into view.355 @discardableResult356 public func search(_ term: String, direction: TerminalSearchDirection = .next, options: TerminalSearchOptions = TerminalSearchOptions()) -> Bool {357 guard !term.isEmpty else {358 clearSearch()359 return false360 }361 let o = SearchOptions(caseSensitive: options.caseSensitive, regex: options.regex, wholeWord: options.wholeWord)362 return direction == .next ? terminalView.findNext(term, options: o) : terminalView.findPrevious(term, options: o)363 }364365 public func clearSearch() { terminalView.clearSearch() }366367 /// Text of the rows currently on screen ("copy visible").368 public func visibleText() -> String {369 Self.text(of: terminalView.terminalContentSnapshot(region: .viewport))370 }371372 /// The live screen plus at most `scrollbackRows` (capped at 2 000) preceding rows. Bounded on373 /// purpose: copying a whole scrollback in one transaction blocks the parser.374 public func recentText(scrollbackRows: Int = 500) -> String {375 Self.text(of: terminalView.terminalContentSnapshot(region: .history(maximumScrollbackRows: min(max(scrollbackRows, 0), 2000))))376 }377378 private static func text(of snapshot: TerminalContentSnapshot?) -> String {379 guard let snapshot else { return "" }380 var lines = snapshot.rows.map(\.text)381 while let last = lines.last, last.isEmpty { lines.removeLast() }382 return lines.joined(separator: "\n")383 }384385 public func scrollToBottom() {386 terminalView.scroll(toPosition: 1)387 refreshScrollState()388 }389390 /// Makes the terminal the first responder (shows the keyboard on iOS).391 public func focus() {392 #if os(macOS)393 terminalView.window?.makeFirstResponder(terminalView)394 #else395 _ = terminalView.becomeFirstResponder()396 #endif397 }398399 /// Dismisses the keyboard (iOS) / gives up first responder.400 public func unfocus() {401 #if os(macOS)402 if terminalView.window?.firstResponder === terminalView { terminalView.window?.makeFirstResponder(nil) }403 #else404 _ = terminalView.resignFirstResponder()405 #endif406 }407408 // MARK: Appearance409410 /// Applies font, line spacing, colours, cursor and scrollback. Cheap when nothing changed.411 public func apply(_ appearance: TerminalAppearance) {412 guard appearance != self.appearance else { return }413 self.appearance = appearance414 applyToView(appearance)415 }416417 private func applyToView(_ a: TerminalAppearance) {418 let view = terminalView419 let font = Self.font(for: a)420 if view.font != font { view.font = font }421 if view.lineSpacing != CGFloat(a.lineSpacing) { view.lineSpacing = CGFloat(a.lineSpacing) }422 view.installColors(a.theme.ansi.map(\.swiftTermColor))423 view.nativeBackgroundColor = a.theme.background.platformColor424 view.nativeForegroundColor = a.theme.foreground.platformColor425 view.caretColor = a.theme.cursor.platformColor426 view.selectedTextBackgroundColor = a.theme.selection.platformColor427 view.minimumContrastRatio = CGFloat(a.theme.minimumContrastRatio)428 view.setCursorStyle(Self.cursorStyle(a))429 view.optionAsMetaKey = a.optionAsMeta430 view.changeScrollback(a.scrollback)431 #if os(iOS)432 view.keyboardAppearance = a.theme.isDark ? .dark : .light433 #endif434 }435436 static func cursorStyle(_ a: TerminalAppearance) -> CursorStyle {437 switch (a.cursorShape, a.cursorBlink) {438 case (.block, true): .blinkBlock439 case (.block, false): .steadyBlock440 case (.underline, true): .blinkUnderline441 case (.underline, false): .steadyUnderline442 case (.bar, true): .blinkBar443 case (.bar, false): .steadyBar444 }445 }446447 /// Resolves the preferred family to an installed fixed-pitch font, else the system monospaced font.448 public static func font(for appearance: TerminalAppearance) -> PlatformFont {449 let size = CGFloat(appearance.fontSize)450 for name in TerminalAppearance.fontCandidates(preferred: appearance.fontName) {451 if name == "SF Mono" { break }452 #if os(macOS)453 if let font = NSFont(name: name, size: size) ?? NSFontManager.shared.font(withFamily: name, traits: [], weight: 5, size: size) { return font }454 #else455 if let font = UIFont(name: name, size: size) { return font }456 if let first = UIFont.fontNames(forFamilyName: name).first(where: { $0.lowercased().hasSuffix("regular") }) ?? UIFont.fontNames(forFamilyName: name).first,457 let font = UIFont(name: first, size: size) { return font }458 #endif459 }460 return PlatformFont.monospacedSystemFont(ofSize: size, weight: .regular)461 }462463 private static func writePasteboard(_ text: String) {464 #if os(macOS)465 NSPasteboard.general.clearContents()466 NSPasteboard.general.setString(text, forType: .string)467 #else468 UIPasteboard.general.string = text469 #endif470 }471472 private func refreshScrollState() {473 scrollRefreshScheduled = false474 let up = terminalView.canScroll && terminalView.scrollPosition < 1475 if up != isScrolledUp { isScrolledUp = up }476 if !up, hasUnreadOutput { hasUnreadOutput = false }477 }478479 // MARK: TerminalViewDelegate480481 public func sizeChanged(source: TerminalView, newCols: Int, newRows: Int) {482 guard newCols != cols || newRows != rows else { return }483 cols = newCols484 rows = newRows485 connection.resize(cols: newCols, rows: newRows)486 }487488 public func setTerminalTitle(source: TerminalView, title: String) {489 // Titles come from untrusted program output: keep them short and printable.490 let cleaned = Self.sanitize(title: title)491 if cleaned != self.title { self.title = cleaned }492 }493494 static func sanitize(title: String) -> String {495 String(String.UnicodeScalarView(title.unicodeScalars.filter { $0.value >= 0x20 && $0.value != 0x7F && !(0x80...0x9F).contains($0.value) }.prefix(200)))496 }497498 public func hostCurrentDirectoryUpdate(source: TerminalView, directory: String?) {}499500 /// Keyboard input (and the emulator's own replies) on their way to the PTY.501 public func send(source: TerminalView, data: ArraySlice<UInt8>) {502 if modifiers.hasAny, !isPasting, data.count <= 4, let text = String(bytes: data, encoding: .utf8), text.unicodeScalars.count == 1 {503 let out = KeyEncoder.applyModifiers(toInput: text, modifiers: modifiers)504 modifiers.consume()505 connection.send(text: out)506 onUserInput?(out.utf8.count)507 return508 }509 connection.send(Data(data))510 onUserInput?(data.count)511 }512513 public func scrolled(source: TerminalView, position: Double) {514 // Do not query the view from inside its callback (terminal lock): refresh on the next turn.515 guard !scrollRefreshScheduled else { return }516 scrollRefreshScheduled = true517 Task { @MainActor [weak self] in self?.refreshScrollState() }518 }519520 public func requestOpenLink(source: TerminalView, link: String, params: [String: String]) {521 guard let url = URL(string: link), let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", url.host() != nil else { return }522 onOpenLink?(url)523 }524525 public func bell(source: TerminalView) {526 bellCount += 1527 onBell?()528 }529530 public func clipboardCopy(source: TerminalView, content: Data) {531 guard let onClipboardWrite, let text = String(data: content, encoding: .utf8), !text.isEmpty else { return }532 onClipboardWrite(text)533 }534535 public func clipboardRead(source: TerminalView) -> Data? { nil }536 public func iTermContent(source: TerminalView, content: ArraySlice<UInt8>) {}537 public func rangeChanged(source: TerminalView, startY: Int, endY: Int) {}538}539540/// Tasks cancelled when their owner goes away (usable from a nonisolated deinit).541final class TaskBag: @unchecked Sendable {542 private let lock = NSLock()543 private var tasks: [Task<Void, Never>] = []544 func add(_ task: Task<Void, Never>) { lock.withLock { tasks.append(task) } }545 func cancelAll() {546 let all = lock.withLock { () -> [Task<Void, Never>] in547 let t = tasks548 tasks = []549 return t550 }551 all.forEach { $0.cancel() }552 }553}554555extension HexColor {556 /// SwiftTerm colour (16-bit components).557 public var swiftTermColor: SwiftTerm.Color {558 SwiftTerm.Color(red: UInt16((rgb >> 16) & 0xFF) * 257, green: UInt16((rgb >> 8) & 0xFF) * 257, blue: UInt16(rgb & 0xFF) * 257)559 }560561 public var platformColor: PlatformColor {562 #if os(macOS)563 NSColor(srgbRed: red, green: green, blue: blue, alpha: alpha)564 #else565 UIColor(red: red, green: green, blue: blue, alpha: alpha)566 #endif567 }568}569