Repository Public
1import AppKit2import Foundation3import Observation4import SwiftTerm5import WorkspaceCore6import os78/// Lifecycle state of the process behind a session.9public enum SessionStatus: Sendable, Hashable {10 case starting11 case running(pid: pid_t)12 case exited(code: Int32?)13 case failed(String)1415 public var isAlive: Bool {16 if case .running = self { return true }17 if case .starting = self { return true }18 return false19 }2021 public var label: String {22 switch self {23 case .starting: return "Starting"24 case .running: return "Running"25 case .exited(let code): return code.map { "Exited (\($0))" } ?? "Exited (signal)"26 case .failed(let reason): return "Failed: \(reason)"27 }28 }29}3031/// A terminal session: owns a PTY-backed process and the view that renders it.32/// Sessions outlive any SwiftUI view and are held by `SessionRegistry`; moving a pane33/// between tabs or windows only reparents `view`.34@MainActor35@Observable36public final class TerminalSession: Identifiable {37 public let id: SessionID38 public private(set) var profile: SessionProfile39 public private(set) var status: SessionStatus = .starting40 public private(set) var title: String = ""41 public private(set) var currentDirectory: String?42 public private(set) var lastOutputAt: Date?43 public private(set) var outputBatches: Int = 044 public private(set) var hasFocus = false45 /// Current PTY grid as reported by SwiftTerm's resize callback.46 public private(set) var gridColumns = 8047 public private(set) var gridRows = 2448 public private(set) var startedAt: Date?49 public private(set) var exitedAt: Date?50 public private(set) var launchSpec: LaunchSpec?51 public private(set) var launchError: String?52 public let createdAt = Date()53 /// Set by the app when the pane is placed, so deep links can find it.54 public var paneID: PaneID?5556 public let view: NEXTerminalView57 private let adapter = SessionViewAdapter()58 private let outputGate = OSAllocatedUnfairLock(initialState: false)59 private var probeTask: Task<Void, Never>?60 /// Name of the program currently in the PTY foreground (verified via tcgetpgrp + libproc), nil when it is the shell.61 public private(set) var foregroundProgram: String?6263 public var label: String? { profile.label }6465 /// Title for tabs/sidebar: explicit label › OSC title › "program · ~/dir" › "Terminal".66 public var displayTitle: String {67 if let label = profile.label, !label.isEmpty { return label }68 if !title.isEmpty { return title }69 let dir = (currentDirectory ?? profile.workingDirectory).map(Self.abbreviate)70 let program: String? = foregroundProgram ?? {71 if case .shell(let path) = profile.kind { return ((path ?? ShellDiscovery.loginShell()) as NSString).lastPathComponent }72 if case .claude = profile.kind { return "claude" }73 if case .ssh = profile.kind { return "ssh" }74 if case .tmux(let name) = profile.kind { return "tmux:\(name)" }75 if case .command(let exe, _) = profile.kind { return (exe as NSString).lastPathComponent }76 return nil77 }()78 switch (program, dir) {79 case (let p?, let d?): return "\(p) · \(d)"80 case (let p?, nil): return p81 case (nil, let d?): return d82 default: return "Terminal"83 }84 }8586 /// "~/x" style path abbreviation.87 public static func abbreviate(_ path: String) -> String {88 let home = ShellDiscovery.homeDirectory()89 if path == home { return "~" }90 if path.hasPrefix(home + "/") { return "~" + path.dropFirst(home.count) }91 return path92 }9394 public var processID: pid_t? {95 if case .running(let pid) = status { return pid }96 return nil97 }9899 /// True when a program other than the shell itself owns the PTY foreground (vim, ssh, claude…).100 /// Uses `tcgetpgrp` on the PTY master; false when the session is dead or the query fails.101 public var hasForegroundProcess: Bool {102 guard let pid = processID, let process = view.process, process.running else { return false }103 let fd = process.childfd104 guard fd >= 0 else { return false }105 let pgrp = tcgetpgrp(fd)106 guard pgrp > 0 else { return false }107 return pgrp != pid108 }109110 /// The slave device path (e.g. /dev/ttys012) for the inspector, if the process is running.111 public var ttyPath: String? {112 guard let pid = processID else { return nil }113 // libproc is the only non-root way to read a child's controlling tty by pid.114 var info = proc_bsdinfo()115 let size = Int32(MemoryLayout<proc_bsdinfo>.size)116 guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, size) == size else { return nil }117 guard info.e_tdev != UInt32.max, info.e_tdev != 0 else { return nil }118 if let name = devname(dev_t(info.e_tdev), S_IFCHR) { return "/dev/" + String(cString: name) }119 return nil120 }121122 public init(id: SessionID = SessionID(), profile: SessionProfile, appearance: TerminalAppearance) {123 self.id = id124 self.profile = profile125 var options = TerminalOptions.default126 options.scrollback = appearance.scrollbackLines127 options.termName = "xterm-256color"128 self.view = NEXTerminalView(frame: CGRect(x: 0, y: 0, width: 800, height: 400), font: appearance.makeFont(), options: options)129 self.view.apply(appearance: appearance)130 self.currentDirectory = profile.workingDirectory131 adapter.session = self132 view.processDelegate = adapter133 view.setProcessOutputHandler { [weak self] in134 guard let self else { return }135 // Coalesce: only one hop to the main actor is pending at any time.136 let shouldHop = self.outputGate.withLock { pending -> Bool in137 if pending { return false }138 pending = true139 return true140 }141 guard shouldHop else { return }142 Task { @MainActor in143 self.outputGate.withLock { $0 = false }144 self.lastOutputAt = Date()145 self.outputBatches += 1146 }147 }148 }149150 // MARK: Process control151152 public func start(with spec: LaunchSpec) {153 launchSpec = spec154 launchError = nil155 status = .starting156 startedAt = Date()157 exitedAt = nil158 view.startProcess(executable: spec.executable, args: spec.arguments, environment: spec.environmentArray, execName: spec.execName, currentDirectory: spec.workingDirectory)159 let pid = view.process.shellPid160 if pid > 0 { status = .running(pid: pid) }161 let grid = view.gridSize162 handleResize(cols: grid.cols, rows: grid.rows)163 startProbing()164 }165166 /// Polls kernel facts (cwd of the shell / foreground program) every 2 s while the process lives.167 /// OSC 7 updates arrive instantly; this is the fallback for shells without shell integration.168 private func startProbing() {169 probeTask?.cancel()170 probeTask = Task { [weak self] in171 while !Task.isCancelled {172 guard let self, self.status.isAlive else { return }173 self.probeOnce()174 try? await Task.sleep(for: .seconds(2))175 }176 }177 }178179 public func probeOnce() {180 guard let pid = processID else { return }181 var program: String?182 var cwdPID = pid183 if let fd = view.process?.childfd, let pgrp = ProcessInspector.foregroundProcessGroup(masterFD: fd), pgrp != pid {184 program = ProcessInspector.name(pid: pgrp)185 cwdPID = pgrp186 }187 if foregroundProgram != program { foregroundProgram = program }188 if let cwd = ProcessInspector.currentDirectory(pid: cwdPID) ?? ProcessInspector.currentDirectory(pid: pid), cwd != currentDirectory {189 currentDirectory = cwd190 profile.workingDirectory = cwd191 }192 }193194 public func restart() {195 guard let spec = launchSpec, !status.isAlive else { return }196 view.feed(text: "\r\n")197 start(with: spec)198 }199200 /// Terminates the child process (SIGHUP then escalation handled by SwiftTerm). Used when the user closes the pane.201 public func terminate() {202 guard status.isAlive else { return }203 view.terminate()204 }205206 public func send(text: String) {207 view.send(txt: text)208 }209210 /// Called by the hosting container when keyboard focus enters or leaves this session's view.211 public func setFocused(_ focused: Bool) {212 if hasFocus != focused { hasFocus = focused }213 }214215 public func updateLabel(_ label: String?) {216 profile.label = label?.isEmpty == true ? nil : label217 }218219 public func updateProfile(_ profile: SessionProfile) {220 self.profile = profile221 }222223 public func apply(appearance: TerminalAppearance) {224 view.apply(appearance: appearance)225 }226227 // MARK: Adapter callbacks228229 fileprivate func handleTitle(_ newTitle: String) { title = newTitle }230231 fileprivate func handleResize(cols: Int, rows: Int) {232 if gridColumns != cols { gridColumns = cols }233 if gridRows != rows { gridRows = rows }234 }235236 fileprivate func handleDirectory(_ directory: String?) {237 guard let directory else { return }238 // OSC 7 delivers a file:// URL; SwiftTerm passes the path component.239 if directory.hasPrefix("file://"), let url = URL(string: directory) {240 currentDirectory = url.path241 } else {242 currentDirectory = directory243 }244 profile.workingDirectory = currentDirectory245 }246247 fileprivate func handleTerminated(exitCode: Int32?) {248 status = .exited(code: exitCode)249 exitedAt = Date()250 foregroundProgram = nil251 probeTask?.cancel()252 }253254 fileprivate func handleFailedToStart(_ error: LocalProcessError) {255 markFailed("\(error)")256 }257258 func markFailed(_ message: String) {259 status = .failed(message)260 launchError = message261 exitedAt = Date()262 }263}264265/// Bridges SwiftTerm delegate callbacks to the session. Kept separate so `TerminalSession`266/// does not have to be an `NSObject` or expose the delegate surface.267@MainActor268private final class SessionViewAdapter: LocalProcessTerminalViewDelegate {269 weak var session: TerminalSession?270271 func sizeChanged(source: LocalProcessTerminalView, newCols: Int, newRows: Int) {272 session?.handleResize(cols: newCols, rows: newRows)273 }274275 func setTerminalTitle(source: LocalProcessTerminalView, title: String) {276 session?.handleTitle(title)277 }278279 func hostCurrentDirectoryUpdate(source: TerminalView, directory: String?) {280 session?.handleDirectory(directory)281 }282283 func processTerminated(source: TerminalView, exitCode: Int32?) {284 session?.handleTerminated(exitCode: exitCode)285 }286287 func processFailedToStart(source: TerminalView, error: LocalProcessError) {288 session?.handleFailedToStart(error)289 }290291 func programStatusChanged(source: TerminalView, records: [TerminalProgramStatus]) {}292}293