import CoreGraphics import Foundation import HelderCore import HelderServices import Observation import SwiftTerm /// A live terminal pane, as the store talks to it. The Terminal views implement this over SwiftTerm. @MainActor public protocol TerminalSessionHandle: AnyObject { /// Writes raw bytes to the child process, as if typed. func send(_ text: String) func terminate() /// Spawns the child process in a pseudo-terminal. func start(_ launch: TerminalLaunch, argv0: String) /// The child's pid once spawned; the store reaps it after `terminate()`, which only signals it. var processID: pid_t? { get } /// The selected text, if any. var selectedText: String? { get } /// Pastes as the terminal would from the clipboard, then takes the keyboard. func paste(_ text: String) } /// Handles that never spawn a process, such as test doubles, need not implement `start` or `processID`. extension TerminalSessionHandle { public func start(_ launch: TerminalLaunch, argv0: String) {} public var processID: pid_t? { nil } public var selectedText: String? { nil } public func paste(_ text: String) { send(BracketedPaste.wrap(text, composerHasText: false)) } } extension HelderTerminalView { var processID: pid_t? { let pid = process?.shellPid ?? 0 return pid > 0 ? pid : nil } } @Observable @MainActor public final class TerminalStore { /// Set by the workspace once the project config is resolved; panes wait for it before spawning. public var config = HelderConfig.defaults { didSet { isConfigured = true } } public private(set) var isConfigured = false public private(set) var agentExited = false public private(set) var shellExited = false /// True while the agent's composer holds typed or pasted text, so the next paste starts on a new line. public private(set) var agentComposerHasText = false @ObservationIgnored public let projectRoot: String? @ObservationIgnored public private(set) var agent: TerminalSessionHandle? @ObservationIgnored public private(set) var shell: TerminalSessionHandle? @ObservationIgnored private let environment: [String: String] /// A right-click in a pane: its kind, whether it holds a selection, the click in window coordinates. @ObservationIgnored public var contextMenuRequested: ((TerminalKind, Bool, CGPoint) -> Void)? public init(projectRoot: String? = nil, environment: [String: String] = ProcessInfo.processInfo.environment) { self.projectRoot = projectRoot self.environment = environment } /// Executable, arguments, environment and cwd for a pane. public func launch(for kind: TerminalKind) -> TerminalLaunch { TerminalLaunch.make(kind: kind, config: config, projectRoot: projectRoot, environment: environment) } /// argv[0] with a leading dash, which makes the shell a login shell: a Finder-launched app /// inherits launchd's bare PATH, and only the login profile (Homebrew, nvm) repairs it. public static func loginArgv0(for executable: String) -> String { "-" + ((executable as NSString).lastPathComponent) } public func session(_ kind: TerminalKind) -> TerminalSessionHandle? { switch kind { case .agent: agent case .shell: shell } } /// Writes observed flags only when they change: panes attach during a SwiftUI update pass. public func attach(_ handle: TerminalSessionHandle, as kind: TerminalKind) { switch kind { case .agent: agent = handle if agentExited { agentExited = false } if agentComposerHasText { agentComposerHasText = false } case .shell: shell = handle if shellExited { shellExited = false } } } /// Attaches a pane and spawns its process. public func start(_ kind: TerminalKind, on handle: TerminalSessionHandle) { attach(handle, as: kind) let launch = launch(for: kind) Log.info("pty", "spawn \(kind.rawValue): \(launch.executable) \(launch.arguments.joined(separator: " ")) in \(launch.workingDirectory)") handle.start(launch, argv0: Self.loginArgv0(for: launch.executable)) } /// Kills whatever runs in the pane and spawns it again with the current config. public func restart(_ kind: TerminalKind) { guard let handle = session(kind) else { return } Self.terminate(handle) start(kind, on: handle) } /// The process ended on its own; an exit we asked for never reports here. public func processExited(_ kind: TerminalKind, exitCode: Int32? = nil) { switch kind { case .agent: agentExited = true case .shell: shellExited = true } if let exitCode, exitCode != 0 { Log.warn("pty", "\(kind.rawValue) exited unexpectedly with code \(exitCode)") } else { Log.info("pty", "\(kind.rawValue) exited") } } public func hasExited(_ kind: TerminalKind) -> Bool { kind == .agent ? agentExited : shellExited } /// Feed every keystroke the user sends to the agent: Enter empties the composer, printable text fills it. public func agentReceivedInput(_ data: String) { if data.contains("\r") { agentComposerHasText = false } else if let scalar = data.unicodeScalars.first, scalar.value >= 0x20 { agentComposerHasText = true } } /// Pastes into the agent's composer as a bracketed paste, so the CLI does not submit it. public func insertIntoAgent(text: String) { guard let agent else { return } agent.send(BracketedPaste.wrap(text, composerHasText: agentComposerHasText)) agentComposerHasText = true } public func selection(_ kind: TerminalKind) -> String? { guard let text = session(kind)?.selectedText, !text.isEmpty else { return nil } return text } public func paste(_ text: String, into kind: TerminalKind) { guard !text.isEmpty, let handle = session(kind) else { return } handle.paste(text) if kind == .agent { agentComposerHasText = true } } /// A pane's window closed: ends its process once, unless `terminateAll` already did. public func release(_ handle: TerminalSessionHandle) { if agent === handle { agent = nil } else if shell === handle { shell = nil } else { return } Self.terminate(handle) } /// Kills both processes; call it before the window closes or the store is replaced. public func terminateAll() { agent.map(Self.terminate) shell.map(Self.terminate) agent = nil shell = nil } private static func terminate(_ handle: TerminalSessionHandle) { let pid = handle.processID handle.terminate() if let pid { Task.detached(priority: .utility) { await ChildReaper.reap(pid) } } } }