SPB Git

Repository Public

TerminalConnection.swift 24.5 KB 674 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/Sources/ClaudeRemoteTerminal/TerminalConnection.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 Foundation9192/// Where the PTY output goes. Called from the connection's receive task, never from the main93/// thread, strictly in stream order. `reset()` is always called before the first byte of a new94/// attach: the server replays the history and repaints the live screen into the normal buffer.95public protocol TerminalOutputSink: Sendable {96    /// Full emulator reset (RIS) and scrollback clear.97    func reset()98    func feed(_ bytes: ArraySlice<UInt8>)99}100101/// State of the stream of one terminal session.102public enum TerminalConnectionState: Sendable, Hashable {103    /// Not started (or stopped by the client).104    case idle105    /// First attach in progress.106    case connecting107    case open108    /// The stream dropped; `attempt` retries were scheduled so far, the next one at `retryAt`109    /// (nil = in progress).110    case reconnecting(attempt: Int, retryAt: Date?)111    /// The device has no network; a retry happens on `wake()` or when the timer fires.112    case offline113    /// The session process ended (close 4410, or the session is STOPPED / FAILED).114    case ended(exitCode: Int?)115    /// The auth session is gone (close 4401): return to sign-in.116    case unauthorized117    case forbidden118    /// The session does not exist (anymore).119    case notFound120    /// The host rebooted: the session can be restarted through the API, then `reconnectNow()`.121    case recoverable122123    public var isOpen: Bool { self == .open }124    /// No retry will happen without a user action.125    public var isFinal: Bool {126        switch self {127        case .ended, .unauthorized, .forbidden, .notFound, .recoverable: true128        default: false129        }130    }131    public var isReconnecting: Bool {132        switch self {133        case .reconnecting, .offline: true134        default: false135        }136    }137}138139public enum TerminalConnectionEvent: Sendable, Hashable {140    case state(TerminalConnectionState)141    /// Round trip of the last ping in milliseconds; nil when not connected.142    case latency(Int?)143    /// The server reported the exit of the session process.144    case exit(code: Int?)145    /// Human-readable detail of the last problem (server `error` message, "Runtime unavailable"…).146    case detail(String?)147    /// Number of successful re-attaches since the first one.148    case reconnected(count: Int)149    /// The server acknowledged the attach with this size.150    case ready(cols: Int, rows: Int)151    /// Output was fed to the sink (throttled: at most a few per second).152    case activity153}154155/// One WebSocket attach to `/sessions/:id/stream`, kept alive across drops.156///157/// Mirrors the web terminal controller: binary frames are raw PTY bytes in both directions, text158/// frames are JSON control messages; reconnects use exponential backoff with jitter; every new159/// attach resets the sink before feeding; a reconnect only re-attaches — it never creates,160/// restarts or stops a session.161public actor TerminalConnection {162    public nonisolated let sessionId: String163    /// Single-consumer stream of everything that changes.164    public nonisolated let events: AsyncStream<TerminalConnectionEvent>165166    public private(set) var state: TerminalConnectionState = .idle167    public private(set) var latencyMs: Int?168    public private(set) var exitCode: Int?169    public private(set) var detail: String?170    public private(set) var reconnectCount = 0171    public private(set) var cols = 120172    public private(set) var rows = 32173174    /// Ping period, pong timeout, liveness check after `wake()`, resize debounce (seconds).175    public static let pingInterval: TimeInterval = 5176    public static let pongTimeout: TimeInterval = 16177    public static let wakeProbeTimeout: TimeInterval = 2.5178    public static let resizeDebounce: TimeInterval = 0.08179    /// Largest slice handed to the sink at once.180    public static let feedChunkBytes = 32 * 1024181182    private let client: APIClient183    private let sink: any TerminalOutputSink184    private let policy: ReconnectPolicy185    private let sleeper: any Sleeper186    private nonisolated let continuation: AsyncStream<TerminalConnectionEvent>.Continuation187    private nonisolated let outbox = Outbox()188    private nonisolated let pendingSize = PendingSize()189190    private var socket: (any WebSocketConnection)?191    private var generation = 0192    private var opened = false193    private var everOpened = false194    private var stopped = false195    private var networkAvailable = true196    private var attempt = 0197    private var pingSeq = 0198    private var pings: [Int: TimeInterval] = [:]199    private var lastPongAt: TimeInterval = 0200    private var pongCount = 0201    private var probeTask: Task<Void, Never>?202    private var lastActivityAt: TimeInterval = -1203    private var connectTask: Task<Void, Never>?204    private var receiveTask: Task<Void, Never>?205    private var writerTask: Task<Void, Never>?206    private var pingTask: Task<Void, Never>?207    private var retryTask: Task<Void, Never>?208    private var resizeTask: Task<Void, Never>?209    private var liveTask: Task<Void, Never>?210211    public init(client: APIClient, sessionId: String, sink: any TerminalOutputSink, policy: ReconnectPolicy = .standard,212                sleeper: any Sleeper = SystemSleeper()) {213        self.client = client214        self.sessionId = sessionId215        self.sink = sink216        self.policy = policy217        self.sleeper = sleeper218        (events, continuation) = AsyncStream.makeStream(of: TerminalConnectionEvent.self, bufferingPolicy: .bufferingNewest(256))219    }220221    deinit {222        connectTask?.cancel(); receiveTask?.cancel(); writerTask?.cancel(); pingTask?.cancel()223        retryTask?.cancel(); resizeTask?.cancel(); liveTask?.cancel(); probeTask?.cancel()224        socket?.close(code: 1000, reason: "client closed")225        continuation.finish()226    }227228    // MARK: Public API229230    /// Attaches with the given size (clamped to the server limits). No-op when already started.231    public func start(cols: Int, rows: Int) {232        let size = TerminalLimits.clamp(cols: cols, rows: rows)233        self.cols = size.cols234        self.rows = size.rows235        pendingSize.set(size.cols, size.rows)236        stopped = false237        if state == .idle { connect() }238    }239240    /// Sends keyboard / paste bytes to the PTY (binary, chunked at 64 KiB). Dropped — never241    /// queued — while the stream is not open. Order is preserved across calls, from any thread.242    public nonisolated func send(_ data: Data) {243        guard !data.isEmpty else { return }244        var offset = data.startIndex245        var chunks: [WebSocketMessage] = []246        while offset < data.endIndex {247            let end = data.index(offset, offsetBy: TerminalLimits.inputChunkBytes, limitedBy: data.endIndex) ?? data.endIndex248            chunks.append(.data(Data(data[offset..<end])))249            offset = end250        }251        outbox.yield(chunks)252    }253254    /// Sends text as UTF-8.255    public nonisolated func send(text: String) {256        send(Data(text.utf8))257    }258259    /// Tells the server the terminal size. Debounced (80 ms) and clamped; the last value wins.260    public nonisolated func resize(cols: Int, rows: Int) {261        let size = TerminalLimits.clamp(cols: cols, rows: rows)262        pendingSize.set(size.cols, size.rows)263        Task { await self.scheduleResize() }264    }265266    /// The app became active or the network came back: retry now, or check that an open socket267    /// is still alive (ping; reconnect when no pong arrives within 2.5 s).268    public func wake() {269        guard !stopped else { return }270        networkAvailable = true271        if state.isReconnecting {272            attempt = 0273            retryTask?.cancel()274            retryTask = nil275            if socket == nil, connectTask == nil { connect() }276            return277        }278        if state == .open, socket != nil {279            let before = pongCount280            ping()281            liveTask?.cancel()282            liveTask = Task { [sleeper] in283                guard (try? await sleeper.sleep(seconds: Self.wakeProbeTimeout)) != nil else { return }284                self.checkAlive(since: before)285            }286        }287    }288289    /// The network path became unsatisfied: a pending reconnection is shown as offline.290    public func networkBecameUnavailable() {291        networkAvailable = false292        if case .reconnecting = state { setState(.offline) }293    }294295    /// Re-attaches immediately (after the user restarted or re-synced the session via the API).296    public func reconnectNow() {297        stopped = false298        attempt = 0299        retryTask?.cancel()300        retryTask = nil301        if socket != nil || connectTask != nil {302            dropAndReconnect()303        } else {304            exitCode = nil305            state = .idle306            connect()307        }308    }309310    /// Closes the stream (code 1000) and stops retrying. The session keeps running on the server.311    public func stop() {312        stopped = true313        generation += 1314        cancelTimers()315        retryTask?.cancel(); retryTask = nil316        connectTask?.cancel(); connectTask = nil317        probeTask?.cancel(); probeTask = nil318        resizeTask?.cancel(); resizeTask = nil319        closeSocket()320        attempt = 0321        setLatency(nil)322        setState(.idle)323    }324325    // MARK: Connecting326327    private func connect() {328        guard !stopped, socket == nil, connectTask == nil else { return }329        retryTask?.cancel()330        retryTask = nil331        if attempt == 0, state == .idle { setState(.connecting) } else if networkAvailable || state != .offline {332            setState(.reconnecting(attempt: attempt, retryAt: nil))333        }334        generation += 1335        let gen = generation336        let size = pendingSize.get() ?? (cols, rows)337        (cols, rows) = size338        let previous = receiveTask339        connectTask = Task { [client, sessionId] in340            // The previous receive loop must be completely finished before the sink is reset.341            await previous?.value342            do {343                let ws = try await client.openTerminalStream(sessionId: sessionId, cols: size.0, rows: size.1)344                self.didOpen(ws, generation: gen)345            } catch {346                self.didFailToOpen(APIError.wrap(error), generation: gen)347            }348        }349    }350351    private func didOpen(_ ws: any WebSocketConnection, generation gen: Int) {352        guard gen == generation, !stopped else {353            ws.close(code: 1000, reason: "client closed")354            return355        }356        connectTask = nil357        socket = ws358        opened = true359        attempt = 0360        lastPongAt = sleeper.now()361        sink.reset()362        exitCode = nil363        setDetail(nil)364        setState(.open)365        if everOpened {366            reconnectCount += 1367            continuation.yield(.reconnected(count: reconnectCount))368        }369        everOpened = true370371        // Serial writer: preserves the order of input chunks and control frames.372        let (stream, writer) = AsyncStream.makeStream(of: WebSocketMessage.self, bufferingPolicy: .unbounded)373        outbox.open(writer)374        writerTask = Task {375            for await message in stream {376                do { try await ws.send(message) } catch { break }377            }378        }379        let size = pendingSize.get() ?? (cols, rows)380        (cols, rows) = size381        control(.resize(cols: size.0, rows: size.1))382        startPing()383384        let sink = sink385        receiveTask = Task.detached { [weak self] in386            var code = 1006387            do {388                while !Task.isCancelled {389                    switch try await ws.receive() {390                    case .data(let data):391                        // Parsed here, off the main thread, in stream order; the next frame is392                        // only read once this one is fed (natural backpressure).393                        data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) in394                            var offset = 0395                            while offset < raw.count {396                                let end = min(offset + Self.feedChunkBytes, raw.count)397                                sink.feed(Array(raw[offset..<end])[...])398                                offset = end399                            }400                        }401                        await self?.didReceiveOutput(generation: gen)402                    case .text(let text):403                        await self?.didReceiveControl(text, generation: gen)404                    }405                }406            } catch let closed as WebSocketClosed {407                code = closed.code408            } catch {409                code = Task.isCancelled ? 1000 : 1006410            }411            await self?.didClose(code: code, generation: gen)412        }413    }414415    private func didFailToOpen(_ error: APIError, generation gen: Int) {416        guard gen == generation, !stopped else { return }417        connectTask = nil418        opened = false419        setLatency(nil)420        switch (error.kind, error.status) {421        case (.cancelled, _): return422        case (_, 401): setState(.unauthorized)423        case (_, 403): setState(.forbidden)424        case (_, 404): setState(.notFound)425        case (_, 410): setState(.ended(exitCode: exitCode))426        default:427            if error.status == 503 { setDetail("Runtime unavailable") }428            setState(networkAvailable ? .reconnecting(attempt: attempt, retryAt: nil) : .offline)429            startProbe(generation: gen)430        }431    }432433    private func startProbe(generation gen: Int) {434        probeTask?.cancel()435        probeTask = Task { await self.probeThenRetry(generation: gen) }436    }437438    // MARK: Receiving439440    private func didReceiveOutput(generation gen: Int) {441        guard gen == generation else { return }442        let now = sleeper.now()443        if now - lastActivityAt >= 0.2 || lastActivityAt < 0 {444            lastActivityAt = now445            continuation.yield(.activity)446        }447    }448449    private func didReceiveControl(_ text: String, generation gen: Int) {450        guard gen == generation, let message = TermServerMessage(text: text) else { return }451        switch message {452        case .pong(let n):453            let sent = pings.removeValue(forKey: n)454            lastPongAt = sleeper.now()455            pongCount += 1456            if let sent { setLatency(max(0, Int(((lastPongAt - sent) * 1000).rounded()))) }457        case .exit(let code):458            exitCode = code459            continuation.yield(.exit(code: code))460        case .error(_, let message):461            setDetail(message)462        case .ready(_, let cols, let rows):463            continuation.yield(.ready(cols: cols, rows: rows))464        case .unknown:465            break466        }467    }468469    private func didClose(code: Int, generation gen: Int) {470        guard gen == generation, !stopped else { return }471        cancelTimers()472        let wasOpen = opened473        opened = false474        closeSocket()475        setLatency(nil)476        switch WSCloseCode(rawValue: code) {477        case .unauthorized: return setState(.unauthorized)478        case .sessionEnded: return setState(.ended(exitCode: exitCode))479        case .notFound: return setState(.notFound)480        case .forbidden: return setState(.forbidden)481        case .runtimeUnavailable: setDetail("Runtime unavailable")482        case .backpressure: setDetail("Connection too slow for the output rate")483        case nil: setDetail(nil)484        }485        setState(networkAvailable ? .reconnecting(attempt: attempt, retryAt: nil) : .offline)486        if !wasOpen || code == WSCloseCode.runtimeUnavailable.rawValue {487            // Not in the receive task: it is being torn down (cancelled) with its socket.488            startProbe(generation: gen)489        } else {490            scheduleRetry()491        }492    }493494    /// Asks the API what happened to the session before retrying blindly.495    private func probeThenRetry(generation gen: Int) async {496        do {497            let session = try await client.session(id: sessionId)498            guard gen == generation, !stopped, socket == nil else { return }499            if session.state == .stopped || session.state == .failed {500                exitCode = session.exitCode501                return setState(.ended(exitCode: session.exitCode))502            }503            if session.state == .recoverable { return setState(.recoverable) }504        } catch {505            guard gen == generation, !stopped, socket == nil else { return }506            let e = APIError.wrap(error)507            if e.status == 404 { return setState(.notFound) }508            if e.status == 401 { return setState(.unauthorized) }509        }510        scheduleRetry()511    }512513    private func scheduleRetry() {514        guard !stopped, retryTask == nil, socket == nil, connectTask == nil else { return }515        let delay = policy.delay(attempt: attempt)516        attempt += 1517        setState(networkAvailable ? .reconnecting(attempt: attempt, retryAt: Date().addingTimeInterval(delay)) : .offline)518        retryTask = Task { [sleeper] in519            guard (try? await sleeper.sleep(seconds: delay)) != nil else { return }520            self.retryFired()521        }522    }523524    private func retryFired() {525        retryTask = nil526        connect()527    }528529    private func dropAndReconnect() {530        generation += 1531        cancelTimers()532        connectTask?.cancel()533        connectTask = nil534        probeTask?.cancel()535        probeTask = nil536        closeSocket()537        opened = false538        attempt = 0539        setLatency(nil)540        setState(.reconnecting(attempt: 0, retryAt: nil))541        connect()542    }543544    private func closeSocket() {545        outbox.close()546        writerTask?.cancel()547        writerTask = nil548        socket?.close(code: 1000, reason: "client closed")549        socket = nil550        receiveTask?.cancel()551    }552553    // MARK: Ping554555    private func startPing() {556        cancelTimers()557        ping()558        pingTask = Task { [sleeper] in559            while !Task.isCancelled {560                guard (try? await sleeper.sleep(seconds: Self.pingInterval)) != nil else { return }561                guard self.pingTick() else { return }562            }563        }564    }565566    private func pingTick() -> Bool {567        guard state == .open, socket != nil else { return false }568        if sleeper.now() - lastPongAt > Self.pongTimeout {569            pingTask = nil // this very task: do not cancel it from inside570            dropAndReconnect()571            return false572        }573        ping()574        return true575    }576577    private func ping() {578        pingSeq += 1579        pings[pingSeq] = sleeper.now()580        control(.ping(n: pingSeq))581    }582583    private func checkAlive(since before: Int) {584        liveTask = nil585        if pongCount == before, state == .open { dropAndReconnect() }586    }587588    private func cancelTimers() {589        pingTask?.cancel()590        pingTask = nil591        liveTask?.cancel()592        liveTask = nil593        pings.removeAll()594    }595596    // MARK: Resize597598    private func scheduleResize() {599        guard !stopped else { return }600        resizeTask?.cancel()601        resizeTask = Task { [sleeper] in602            guard (try? await sleeper.sleep(seconds: Self.resizeDebounce)) != nil else { return }603            self.resizeFired()604        }605    }606607    private func resizeFired() {608        resizeTask = nil609        guard let size = pendingSize.get() else { return }610        let changed = size != (cols, rows)611        (cols, rows) = size612        if changed, state == .open { control(.resize(cols: size.0, rows: size.1)) }613    }614615    // MARK: Helpers616617    private func control(_ message: TermClientMessage) {618        outbox.yield([.text(message.text)])619    }620621    private func setState(_ new: TerminalConnectionState) {622        guard new != state else { return }623        state = new624        continuation.yield(.state(new))625    }626627    private func setLatency(_ value: Int?) {628        guard value != latencyMs else { return }629        latencyMs = value630        continuation.yield(.latency(value))631    }632633    private func setDetail(_ value: String?) {634        guard value != detail else { return }635        detail = value636        continuation.yield(.detail(value))637    }638}639640/// Gate between any thread and the serial writer of the current socket.641private final class Outbox: @unchecked Sendable {642    private let lock = NSLock()643    private var writer: AsyncStream<WebSocketMessage>.Continuation?644645    func open(_ writer: AsyncStream<WebSocketMessage>.Continuation) {646        lock.withLock { self.writer = writer }647    }648649    func close() {650        let w = lock.withLock { () -> AsyncStream<WebSocketMessage>.Continuation? in651            let w = writer652            writer = nil653            return w654        }655        w?.finish()656    }657658    /// Dropped when no socket is open.659    func yield(_ messages: [WebSocketMessage]) {660        lock.withLock {661            guard let writer else { return }662            for m in messages { writer.yield(m) }663        }664    }665}666667/// Latest size requested by the view (the last value always wins, whatever the task order).668private final class PendingSize: @unchecked Sendable {669    private let lock = NSLock()670    private var value: (Int, Int)?671    func set(_ cols: Int, _ rows: Int) { lock.withLock { value = (cols, rows) } }672    func get() -> (Int, Int)? { lock.withLock { value } }673}674
Files main
Menu

Theme