SPB Git

Repository Public

AppModel.swift 48.7 KB 1,003 lines swift

1import AIAssistant2import AppKit3import DesignSystem4import Observation5import PTYProcess6import SessionStore7import SettingsModel8import SSHKit9import TerminalCore10import WindowManager11import WorkspaceKit1213/// A command waiting for the user's explicit confirmation (assistant suggestion, snippet,14/// broadcast line). Execution is only possible through `ConsentGate.approve`.15struct CommandConfirmation: Identifiable {16    let id = UUID()17    var title: String18    var proposal: ProposedCommand19    var targetDescription: String20    /// Receives the approved command; never called without approval.21    var onApproved: @MainActor (ApprovedCommand) -> Void22    var onCancelled: @MainActor () -> Void = {}23}2425/// Dependencies that differ between the real app and hosted tests.26struct AppEnvironment {27    var locations: StoreLocations28    var secrets: any SecretStore29    var screens: @MainActor () -> [ScreenDescriptor]30    /// Shows windows on screen. Hosted tests keep them ordered out.31    var showsWindows: Bool32    /// Asks a yes/no question; tests answer programmatically.33    var confirm: @MainActor (_ title: String, _ message: String, _ action: String) -> Bool34    var persists: Bool3536    @MainActor static func live(locations: StoreLocations) -> AppEnvironment {37        AppEnvironment(locations: locations, secrets: KeychainSecretStore(), screens: { ScreenReader.current() },38                       showsWindows: true, confirm: { title, message, action in39            let alert = NSAlert()40            alert.messageText = title41            alert.informativeText = message42            alert.alertStyle = .warning43            alert.addButton(withTitle: action)44            alert.addButton(withTitle: "Cancel")45            return alert.runModal() == .alertFirstButtonReturn46        }, persists: true)47    }48}4950enum ScreenReader {51    @MainActor static func current() -> [ScreenDescriptor] {52        let main = NSScreen.screens.first53        return NSScreen.screens.map { screen in54            let number = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.uint32Value ?? 055            return ScreenDescriptor(id: number, name: screen.localizedName, frame: screen.frame, visibleFrame: screen.visibleFrame,56                                    scale: screen.backingScaleFactor, isMain: screen == main)57        }58    }59}6061@MainActor62@Observable63final class AppModel {64    @ObservationIgnored let environment: AppEnvironment65    @ObservationIgnored let stores: SessionStores66    @ObservationIgnored let hostStore: VersionedStore<[SSHHostProfile]>67    @ObservationIgnored let providerStore: VersionedStore<[AIProviderConfig]>68    @ObservationIgnored let appVersion: String6970    var settings: AppSettings { didSet { if settings != oldValue { settingsDidChange(from: oldValue) } } }71    private(set) var windows: [WindowState] = []72    var snippets: [Snippet] = []73    var savedWorkspaces: [WorkspaceSnapshot] = []74    var manualHosts: [SSHHostProfile] = []75    private(set) var configHosts: [SSHConfigHost] = []76    var providers: [AIProviderConfig] = []77    var systemIsDark = true78    var increaseContrast = false79    /// "Reduce motion" of macOS (System Settings › Accessibility › Display).80    var reduceMotion = false81    /// Foreground commands that have just ended, shown briefly in the tab and the status bar.82    private(set) var completions: [PaneID: CommandCompletion] = [:]83    /// Explanations attached to panes (ssh failure diagnosis…), shown as an overlay with actions.84    var paneNotes: [PaneID: String] = [:]85    /// Bumped once per second so views showing sampled process state refresh.86    private(set) var tick = 087    private(set) var storageWarnings: [String] = []8889    @ObservationIgnored private(set) var sessions: [PaneID: TerminalSession] = [:]90    @ObservationIgnored private var paneByView: [ObjectIdentifier: PaneID] = [:]91    @ObservationIgnored private var lineTrackers: [TabID: BroadcastGuard.LineTracker] = [:]92    @ObservationIgnored private var autosaveScheduled = false93    @ObservationIgnored private var timer: Timer?94    @ObservationIgnored private(set) var lastKnownScreens: [ScreenDescriptor] = []95    @ObservationIgnored var quickTerminal: QuickTerminalController?96    @ObservationIgnored let analyzer = CommandRiskAnalyzer()97    @ObservationIgnored let gate = ConsentGate()98    @ObservationIgnored private var cascade = 099    @ObservationIgnored let git = GitContext()100    @ObservationIgnored var assistants: [WindowID: AssistantModel] = [:]101    @ObservationIgnored var isTerminating = false102103    init(environment: AppEnvironment) {104        self.environment = environment105        stores = SessionStores(locations: environment.locations)106        hostStore = VersionedStore(url: environment.locations.hosts, currentVersion: 1)107        providerStore = VersionedStore(url: environment.locations.providers, currentVersion: 1)108        appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0"109        try? environment.locations.prepare()110        settings = AppSettings()111        settings = load(stores.settings, default: AppSettings(), name: "settings")112        snippets = load(stores.snippets, default: SessionStores.starterSnippets, name: "snippets")113        savedWorkspaces = load(stores.workspaces, default: [], name: "workspaces")114        manualHosts = load(hostStore, default: [], name: "hosts")115        providers = load(providerStore, default: [], name: "assistant providers")116        lastKnownScreens = environment.screens()117        reloadSSHConfig()118    }119120    private func load<T>(_ store: VersionedStore<T>, default fallback: T, name: String) -> T {121        switch store.load() {122        case .loaded(let value): return value123        case .missing: return fallback124        case .recovered(let backup, _):125            storageWarnings.append("The \(name) file could not be read and was set aside"126                                   + (backup.map { " as \($0.lastPathComponent)" } ?? "") + ". Defaults are in use.")127            return fallback128        }129    }130131    // MARK: Appearance132133    var theme: TerminalTheme { settings.resolvedTheme(systemIsDark: systemIsDark, increaseContrast: increaseContrast) }134    var accent: SPColor { settings.accentOverride ?? theme.accent }135136    func refreshSystemAppearance() {137        let dark = NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua138        let contrast = NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast139        if dark != systemIsDark { systemIsDark = dark }140        if contrast != increaseContrast { increaseContrast = contrast }141        let motion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion142        if motion != reduceMotion { reduceMotion = motion }143        applyAppearanceToAll()144    }145146    private func settingsDidChange(from old: AppSettings) {147        applyAppearanceToAll()148        save { try stores.settings.save(settings) }149        if old.quickTerminalEnabled != settings.quickTerminalEnabled || old.quickTerminalShortcut != settings.quickTerminalShortcut {150            quickTerminal?.updateHotKey()151        }152        if old.keyBindings != settings.keyBindings { (NSApp.delegate as? AppDelegate)?.rebuildMenu() }153        if !old.privateMode && settings.privateMode { stores.lastSession.delete() }154    }155156    func applyAppearanceToAll() {157        let theme = theme158        for session in sessions.values { session.apply(settings: settings, theme: theme) }159        for window in windows { window.controller?.applyAppearance() }160        quickTerminal?.applyAppearance()161    }162163    func save(_ write: () throws -> Void) {164        guard environment.persists else { return }165        do { try write() } catch { storageWarnings.append("Could not save: \(error.localizedDescription)") }166    }167168    // MARK: Sessions169170    func session(for pane: PaneID) -> TerminalSession? { sessions[pane] }171172    func window(containing pane: PaneID) -> WindowState? {173        windows.first { $0.tabIndex(containing: pane) != nil } ?? quickTerminal?.state.flatMap { $0.tabIndex(containing: pane) != nil ? $0 : nil }174    }175176    func descriptor(for pane: PaneID) -> PaneDescriptor? {177        guard let window = window(containing: pane), let index = window.tabIndex(containing: pane) else { return nil }178        return window.tabs[index].descriptor(for: pane)179    }180181    /// All SSH profiles: hosts found in `~/.ssh/config` merged with the ones saved in SP Term.182    var hosts: [SSHHostProfile] { SSHHostProfile.merge(configHosts: configHosts, saved: manualHosts) }183184    func reloadSSHConfig() {185        configHosts = SSHConfigParser().parseFile().hosts186    }187188    func launchRequest(for kind: SessionKind) -> (request: LaunchRequest, problem: String?) {189        switch kind {190        case .localShell(let path):191            return (.shell(path: path ?? settings.shellPath, login: settings.loginShell), nil)192        case .command(let line):193            return (.commandLine(line, shell: settings.shellPath), nil)194        case .ssh(let alias):195            let profile = hosts.first { $0.host == alias || $0.label == alias }196                ?? SSHHostProfile(label: alias, host: alias, source: .manual)197            do {198                // SSHKit validates every field and never weakens host key checking.199                let command = try SSHCommandBuilder.sshCommand(for: profile)200                return (.program(executable: command.executable, arguments: command.arguments), nil)201            } catch {202                return (.shell(path: settings.shellPath, login: settings.loginShell),203                        "The SSH profile “\(alias)” is not valid (\(error.localizedDescription)). A local shell was opened instead.")204            }205        }206    }207208    /// Returns the session of a pane, creating (but not starting) it when needed. The process209    /// starts when the terminal view is first laid out, so it gets the right size immediately.210    @discardableResult211    func ensureSession(for descriptor: PaneDescriptor) -> TerminalSession {212        if let existing = sessions[descriptor.id] { return existing }213        let (request, problem) = launchRequest(for: descriptor.kind)214        let directory = descriptor.workingDirectory ?? settings.startupDirectory215        let session = TerminalSession(request: request, workingDirectory: directory, scrollback: settings.scrollbackLines, appVersion: appVersion)216        let pane = descriptor.id217        session.apply(settings: settings, theme: theme)218        session.userInputTap = { [weak self] bytes in self?.handleUserInput(from: pane, bytes: bytes) }219        session.onExit = { [weak self] status in self?.sessionDidExit(pane, status: status) }220        session.onOpenLink = { [weak self] link in self?.openLink(link) }221        session.onClipboardWrite = { [weak self] text in self?.clipboardWriteRequested(text, pane: pane) }222        session.clipboardReadProvider = { [weak self] in223            self?.settings.clipboardRead == .allow ? NSPasteboard.general.string(forType: .string) : nil224        }225        session.onForegroundJobEnded = { [weak self] name, duration in self?.foregroundJobEnded(pane, name: name, duration: duration) }226        session.onBell = { [weak self] in self?.tick &+= 1 }227        session.view.pasteInterceptor = { [weak self] text in self?.shouldPasteImmediately(text, pane: pane, isDrop: false) ?? true }228        session.view.onTextDrop = { [weak self] text, point in229            guard let self else { return }230            // A pane dragged by its header lands here when dropped on another terminal.231            if let dragged = PaneDrag.pane(from: text) {232                self.movePane(dragged, to: PaneDrag.edge(for: point), of: pane)233                return234            }235            if self.shouldPasteImmediately(text, pane: pane, isDrop: true) { self.sendPasteText(text, to: pane) }236        }237        session.view.contextMenuProvider = { [weak self] in self?.contextMenu(for: pane) }238        sessions[pane] = session239        paneByView[ObjectIdentifier(session.view)] = pane240        if let problem { paneNotes[pane] = problem }241        return session242    }243244    /// Called by the terminal container once the view has a real size.245    func startIfNeeded(_ pane: PaneID) {246        guard let session = sessions[pane], session.status == .notStarted else { return }247        session.start()248        if case .localShell = descriptor(for: pane)?.kind, !settings.startupCommand.isEmpty, session.status.isRunning {249            session.send(text: settings.startupCommand + "\r")250        }251    }252253    private func discardSession(_ pane: PaneID) {254        if let view = sessions[pane]?.view { paneByView[ObjectIdentifier(view)] = nil }255        sessions[pane]?.terminate()256        sessions[pane] = nil257        paneNotes[pane] = nil258        completions[pane] = nil259    }260261    private func sessionDidExit(_ pane: PaneID, status: PTYExitStatus) {262        tick &+= 1263        guard !isTerminating, let descriptor = descriptor(for: pane), let session = sessions[pane] else { return }264        if case .ssh(let alias) = descriptor.kind {265            let tail = session.bufferText().split(separator: "\n").suffix(12).joined(separator: "\n")266            if let kind = SSHErrorClassifier.classify(stderr: tail, exitStatus: status.shellCode) {267                paneNotes[pane] = "\(alias): \(kind.explanation)"268            } else {269                paneNotes[pane] = "Connection to \(alias) ended."270            }271            Notifier.shared.post(title: "SSH session ended", body: paneNotes[pane] ?? alias, settings: settings, onlyWhenInactive: true)272        }273    }274275    private func foregroundJobEnded(_ pane: PaneID, name: String, duration: TimeInterval) {276        noteCompletion(pane, name: name, duration: duration)277        guard settings.notifyOnLongCommand, duration >= Double(settings.longCommandSeconds) else { return }278        Notifier.shared.post(title: "\(name) finished", body: "Ran for \(Formatters.duration(duration)).", settings: settings, onlyWhenInactive: true)279    }280281    /// Records that a foreground command ended so the chrome can acknowledge it for a few seconds.282    /// Only the name and the duration are known: without shell integration the exit status is not,283    /// so the feedback never claims success or failure.284    func noteCompletion(_ pane: PaneID, name: String, duration: TimeInterval) {285        guard settings.completionFeedback, duration >= CommandCompletion.minimumDuration, sessions[pane] != nil else { return }286        let completion = CommandCompletion(name: name, duration: duration)287        completions[pane] = completion288        DispatchQueue.main.asyncAfter(deadline: .now() + MotionSpec.completionHold) { [weak self] in289            if self?.completions[pane]?.id == completion.id { self?.completions[pane] = nil }290        }291    }292293    func startTimer() {294        timer?.invalidate()295        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in296            MainActor.assumeIsolated { self?.sampleSessions() }297        }298    }299300    func sampleSessions() {301        for session in sessions.values { session.refreshProcessState() }302        tick &+= 1303    }304305    // MARK: Windows306307    func screens() -> [ScreenDescriptor] { environment.screens() }308309    /// Display for a new window according to the user's preference.310    func preferredScreen() -> ScreenDescriptor? {311        let all = screens()312        switch settings.newWindowScreen {313        case .main: return PlacementEngine.fallbackScreen(in: all)314        case .pointer:315            let point = NSEvent.mouseLocation316            return all.first { $0.frame.contains(point) } ?? PlacementEngine.fallbackScreen(in: all)317        case .active:318            if let key = windows.first(where: { $0.controller?.window?.isKeyWindow == true })?.controller?.window {319                return PlacementEngine.screen(containing: key.frame, in: all) ?? PlacementEngine.fallbackScreen(in: all)320            }321            return PlacementEngine.fallbackScreen(in: all)322        }323    }324325    func newPaneDescriptor(kind: SessionKind = .localShell(path: nil), inheritingFrom pane: PaneID? = nil) -> PaneDescriptor {326        var directory = settings.startupDirectory327        if settings.newPaneInheritsDirectory, let pane, let session = sessions[pane], session.reportedRemoteHost == nil {328            session.refreshProcessState()329            directory = session.workingDirectory ?? directory330        }331        return PaneDescriptor(kind: kind, workingDirectory: directory)332    }333334    /// Opens a window. `screenID` selects the display; `frame` overrides the placement.335    @discardableResult336    func openWindow(tabs: [TabModel]? = nil, selectedTab: TabID? = nil, on screenID: UInt32? = nil, placement: Placement? = nil,337                    id: WindowID = WindowID(), fullScreen: Bool = false) -> WindowState {338        let content = tabs ?? [TabModel(single: newPaneDescriptor(inheritingFrom: keyWindowState?.focusedPane))]339        let state = WindowState(id: id, tabs: content, selectedTabID: selectedTab, sidebarVisible: settings.showSidebar)340        for tab in content { for pane in tab.panes { ensureSession(for: pane) } }341        let all = screens()342        var frame = placement?.frame343        if frame == nil {344            let target = screenID.flatMap { id in all.first { $0.id == id } } ?? preferredScreen()345            if let target { frame = PlacementEngine.frameForNewWindow(on: target, cascadeIndex: cascade) }346            cascade += 1347        }348        let controller = WorkspaceWindowController(state: state, model: self, frame: frame ?? CGRect(x: 100, y: 100, width: 1000, height: 640))349        state.controller = controller350        windows.append(state)351        if environment.showsWindows {352            controller.showWindow(nil)353            controller.window?.makeKeyAndOrderFront(nil)354            if fullScreen { controller.window?.toggleFullScreen(nil) }355        }356        focusCurrentPane(in: state)357        scheduleAutosave()358        return state359    }360361    var keyWindowState: WindowState? {362        windows.first { $0.controller?.window?.isKeyWindow == true } ?? windows.first { $0.controller?.window?.isMainWindow == true } ?? windows.last363    }364365    /// Closes a window. Sessions are terminated unless they were moved elsewhere beforehand.366    func closeWindow(_ window: WindowState, confirmed: Bool = false) {367        let busy = window.allPanes.compactMap { sessions[$0] }.filter(\.isBusy)368        if !confirmed, settings.confirmCloseRunning, !busy.isEmpty {369            let names = busy.compactMap(\.foregroundProcessName).joined(separator: ", ")370            guard environment.confirm("Close this window?", "\(busy.count) session(s) are still running (\(names)). Closing the window ends them.", "Close Window") else { return }371        }372        for pane in window.allPanes { discardSession(pane) }373        removeWindow(window)374    }375376    private func removeWindow(_ window: WindowState) {377        windows.removeAll { $0.id == window.id }378        assistants[window.id] = nil379        let controller = window.controller380        window.controller = nil381        controller?.closeWithoutPrompt()382        scheduleAutosave()383    }384385    func moveWindow(_ window: WindowState, toScreen screenID: UInt32) {386        guard let nsWindow = window.controller?.window, let target = screens().first(where: { $0.id == screenID }) else { return }387        let source = PlacementEngine.screen(containing: nsWindow.frame, in: screens())388        let frame = PlacementEngine.move(nsWindow.frame, from: source?.visibleFrame ?? nsWindow.frame, to: target)389        nsWindow.setFrame(frame, display: true, animate: environment.showsWindows)390        scheduleAutosave()391    }392393    func moveWindowToNextScreen(_ window: WindowState) {394        let all = screens()395        guard all.count > 1, let nsWindow = window.controller?.window,396              let current = PlacementEngine.screen(containing: nsWindow.frame, in: all),397              let index = all.firstIndex(of: current) else { return }398        moveWindow(window, toScreen: all[(index + 1) % all.count].id)399    }400401    // MARK: Tabs402403    @discardableResult404    func newTab(in window: WindowState, kind: SessionKind = .localShell(path: nil)) -> TabID {405        let descriptor = newPaneDescriptor(kind: kind, inheritingFrom: window.focusedPane)406        ensureSession(for: descriptor)407        let tab = TabModel(single: descriptor)408        let insertAt = (window.selectedIndex ?? window.tabs.count - 1) + 1409        window.tabs.insert(tab, at: min(insertAt, window.tabs.count))410        selectTab(tab.id, in: window)411        return tab.id412    }413414    func selectTab(_ id: TabID, in window: WindowState) {415        guard window.tabs.contains(where: { $0.id == id }) else { return }416        window.selectedTabID = id417        focusCurrentPane(in: window)418        scheduleAutosave()419    }420421    func selectTab(offset: Int, in window: WindowState) {422        guard let index = window.selectedIndex, !window.tabs.isEmpty else { return }423        let next = (index + offset + window.tabs.count) % window.tabs.count424        selectTab(window.tabs[next].id, in: window)425    }426427    func closeTab(_ id: TabID, in window: WindowState, confirmed: Bool = false) {428        guard let index = window.tabs.firstIndex(where: { $0.id == id }) else { return }429        let panes = window.tabs[index].layout.panes430        let busy = panes.compactMap { sessions[$0] }.filter(\.isBusy)431        if !confirmed, settings.confirmCloseRunning, !busy.isEmpty {432            guard environment.confirm("Close this tab?", "\(busy.count) session(s) are still running. Closing the tab ends them.", "Close Tab") else { return }433        }434        panes.forEach(discardSession)435        removeTab(at: index, in: window)436    }437438    private func removeTab(at index: Int, in window: WindowState) {439        let removed = window.tabs.remove(at: index)440        window.broadcastTabs.remove(removed.id)441        lineTrackers[removed.id] = nil442        if window.tabs.isEmpty {443            if window.isQuickTerminal { quickTerminal?.tabsDidEmpty() } else { removeWindow(window) }444            return445        }446        if window.selectedTabID == removed.id {447            window.selectedTabID = window.tabs[min(index, window.tabs.count - 1)].id448        }449        focusCurrentPane(in: window)450        scheduleAutosave()451    }452453    func moveTab(_ id: TabID, in window: WindowState, to newIndex: Int) {454        guard let index = window.tabs.firstIndex(where: { $0.id == id }) else { return }455        let tab = window.tabs.remove(at: index)456        window.tabs.insert(tab, at: min(max(newIndex, 0), window.tabs.count))457        scheduleAutosave()458    }459460    /// Moves a tab into its own new window; its sessions keep running.461    @discardableResult462    func detachTab(_ id: TabID, from window: WindowState, toScreen screenID: UInt32? = nil) -> WindowState? {463        guard window.tabs.count > 1 || !window.isQuickTerminal, let index = window.tabs.firstIndex(where: { $0.id == id }) else { return nil }464        guard window.tabs.count > 1 else { return window }465        let tab = window.tabs[index]466        removeTab(at: index, in: window)467        return openWindow(tabs: [tab], on: screenID)468    }469470    /// Moves every tab of `source` into `target` and closes `source`. Sessions keep running.471    func mergeWindow(_ source: WindowState, into target: WindowState) {472        guard source.id != target.id else { return }473        let moved = source.tabs474        source.tabs = []475        target.tabs.append(contentsOf: moved)476        for tab in moved where source.broadcastTabs.contains(tab.id) { lineTrackers[tab.id] = nil }477        removeWindow(source)478        if let last = moved.last { selectTab(last.id, in: target) }479        target.controller?.window?.makeKeyAndOrderFront(nil)480    }481482    func mergeAllWindows(into target: WindowState) {483        for window in windows where window.id != target.id { mergeWindow(window, into: target) }484    }485486    // MARK: Panes487488    @discardableResult489    func split(_ pane: PaneID? = nil, axis: SplitAxis, in window: WindowState, kind: SessionKind = .localShell(path: nil)) -> PaneID? {490        guard let target = pane ?? window.focusedPane, let index = window.tabIndex(containing: target) else { return nil }491        let descriptor = newPaneDescriptor(kind: kind, inheritingFrom: target)492        guard window.tabs[index].split(target, axis: axis, adding: descriptor) else { return nil }493        ensureSession(for: descriptor)494        focus(descriptor.id, in: window)495        scheduleAutosave()496        return descriptor.id497    }498499    func closePane(_ pane: PaneID, in window: WindowState, confirmed: Bool = false) {500        guard let index = window.tabIndex(containing: pane) else { return }501        if !confirmed, settings.confirmCloseRunning, let session = sessions[pane], session.isBusy {502            let name = session.foregroundProcessName ?? "a process"503            guard environment.confirm("Close this pane?", "“\(name)” is still running. Closing the pane ends it.", "Close Pane") else { return }504        }505        discardSession(pane)506        window.tabs[index].remove(pane)507        if window.tabs[index].isEmpty { removeTab(at: index, in: window) } else {508            focusCurrentPane(in: window)509            scheduleAutosave()510        }511    }512513    /// Moves a pane into its own new window; its process keeps running.514    @discardableResult515    func detachPane(_ pane: PaneID, from window: WindowState, toScreen screenID: UInt32? = nil) -> WindowState? {516        guard let index = window.tabIndex(containing: pane), let descriptor = window.tabs[index].remove(pane) else { return nil }517        if window.tabs[index].isEmpty { removeTab(at: index, in: window) } else { focusCurrentPane(in: window) }518        return openWindow(tabs: [TabModel(single: descriptor)], on: screenID)519    }520521    /// Moves a pane into a new tab of the same window.522    func movePaneToNewTab(_ pane: PaneID, in window: WindowState) {523        guard let index = window.tabIndex(containing: pane), window.tabs[index].panes.count > 1,524              let descriptor = window.tabs[index].remove(pane) else { return }525        let tab = TabModel(single: descriptor)526        window.tabs.insert(tab, at: index + 1)527        selectTab(tab.id, in: window)528    }529530    /// Re-arranges panes by drag & drop: `pane` lands on `edge` of `target` (same tab), or is531    /// moved across tabs/windows when it comes from elsewhere.532    func movePane(_ pane: PaneID, to edge: DropEdge, of target: PaneID) {533        guard pane != target, let destination = window(containing: target), let destinationIndex = destination.tabIndex(containing: target),534              let source = window(containing: pane), let sourceIndex = source.tabIndex(containing: pane) else { return }535        if source.id == destination.id, sourceIndex == destinationIndex {536            destination.tabs[destinationIndex].layout.move(pane, to: edge, of: target)537            destination.tabs[destinationIndex].zoomedPane = nil538        } else {539            guard let descriptor = source.tabs[sourceIndex].remove(pane) else { return }540            let axis: SplitAxis = (edge == .left || edge == .right) ? .horizontal : .vertical541            // Re-resolve the destination: removing the source tab may have shifted indices.542            if source.tabs[sourceIndex].isEmpty { removeTab(at: sourceIndex, in: source) }543            guard let index = destination.tabIndex(containing: target) else { return }544            destination.tabs[index].split(target, axis: axis, adding: descriptor, before: edge == .left || edge == .top)545        }546        focus(pane, in: destination)547        scheduleAutosave()548    }549550    func swapPanes(_ a: PaneID, _ b: PaneID, in window: WindowState) {551        window.mutateTab(containing: a) { $0.layout.swap(a, b) }552        scheduleAutosave()553    }554555    func toggleZoom(in window: WindowState) {556        window.mutateSelectedTab { tab in557            tab.zoomedPane = tab.zoomedPane == nil ? tab.focusedPane : nil558        }559        focusCurrentPane(in: window)560        scheduleAutosave()561    }562563    func resizeFocusedPane(_ direction: Direction, in window: WindowState) {564        guard let pane = window.focusedPane else { return }565        window.mutateSelectedTab { $0.layout.resize(pane: pane, toward: direction, by: 0.04) }566        scheduleAutosave()567    }568569    func equalizePanes(in window: WindowState) {570        window.mutateSelectedTab { $0.layout.equalize() }571        scheduleAutosave()572    }573574    func duplicatePane(_ pane: PaneID, in window: WindowState) {575        guard let descriptor = descriptor(for: pane) else { return }576        split(pane, axis: .horizontal, in: window, kind: descriptor.kind)577    }578579    func restartSession(_ pane: PaneID) {580        paneNotes[pane] = nil581        guard let session = sessions[pane] else { return }582        if session.status == .notStarted { session.start() } else { session.restart() }583    }584585    func rename(pane: PaneID, to title: String) {586        window(containing: pane)?.mutateTab(containing: pane) { tab in587            tab.update(pane) { $0.customTitle = title.trimmingCharacters(in: .whitespaces).isEmpty ? nil : title }588        }589        scheduleAutosave()590    }591592    func rename(tab: TabID, in window: WindowState, to title: String) {593        guard let index = window.tabs.firstIndex(where: { $0.id == tab }) else { return }594        window.tabs[index].customTitle = title.trimmingCharacters(in: .whitespaces).isEmpty ? nil : title595        scheduleAutosave()596    }597598    // MARK: Focus599600    func focus(_ pane: PaneID, in window: WindowState) {601        guard let index = window.tabIndex(containing: pane) else { return }602        if window.tabs[index].focusedPane != pane { window.tabs[index].focusedPane = pane }603        if window.tabs[index].zoomedPane != nil, window.tabs[index].zoomedPane != pane { window.tabs[index].zoomedPane = pane }604        if window.selectedTabID != window.tabs[index].id { window.selectedTabID = window.tabs[index].id }605        updateFocusFlags(in: window)606        if let view = sessions[pane]?.view, let nsWindow = view.window, nsWindow.firstResponder !== view {607            nsWindow.makeFirstResponder(view)608        }609    }610611    func focusCurrentPane(in window: WindowState) {612        guard let pane = window.focusedPane else { return }613        // The view may not be in the hierarchy yet (new tab): retry after the next layout pass.614        focus(pane, in: window)615        DispatchQueue.main.async { [weak self, weak window] in616            guard let self, let window, window.focusedPane == pane else { return }617            self.focus(pane, in: window)618        }619    }620621    /// Called when a terminal view has just entered a window: if its pane is the focused one,622    /// give it the keyboard (unless the user is typing in a text field such as the palette).623    func claimFocusIfNeeded(_ pane: PaneID) {624        guard let window = window(containing: pane), window.focusedPane == pane, !window.paletteVisible, window.sheet == nil,625              let view = sessions[pane]?.view, let nsWindow = view.window, nsWindow.firstResponder !== view else { return }626        if nsWindow.firstResponder is NSText { return }627        nsWindow.makeFirstResponder(view)628    }629630    func moveFocus(_ direction: Direction, in window: WindowState) {631        guard let tab = window.selectedTab, let current = tab.focusedPane, tab.zoomedPane == nil,632              let next = tab.layout.neighbor(of: current, toward: direction, in: window.controller?.canvasBounds ?? CGRect(x: 0, y: 0, width: 1000, height: 700))633        else { return }634        focus(next, in: window)635    }636637    func cycleFocus(_ offset: Int, in window: WindowState) {638        guard let tab = window.selectedTab, let current = tab.focusedPane, let index = tab.layout.panes.firstIndex(of: current) else { return }639        let panes = tab.layout.panes640        focus(panes[(index + offset + panes.count) % panes.count], in: window)641    }642643    /// The window noticed that a terminal view became first responder (click, tab key…).644    func viewDidBecomeFirstResponder(_ view: NSView, in window: WindowState) {645        guard let pane = paneByView[ObjectIdentifier(view)], let index = window.tabIndex(containing: pane) else {646            updateFocusFlags(in: window, responder: view)647            return648        }649        if window.tabs[index].focusedPane != pane { window.tabs[index].focusedPane = pane }650        updateFocusFlags(in: window)651    }652653    private func updateFocusFlags(in window: WindowState, responder: NSView? = nil) {654        let focused = window.focusedPane655        for pane in window.allPanes {656            let isFirstResponder = responder.map { sessions[pane]?.view === $0 } ?? (pane == focused)657            sessions[pane]?.setFocused(pane == focused && isFirstResponder)658        }659    }660661    // MARK: Broadcast input662663    func requestBroadcastToggle(in window: WindowState) {664        guard let tab = window.selectedTab else { return }665        if window.broadcastTabs.contains(tab.id) {666            window.broadcastTabs.remove(tab.id)667            lineTrackers[tab.id] = nil668        } else if tab.panes.count > 1 {669            window.sheet = .broadcastConfirm(tab.id)670        } else {671            window.banner = Banner(style: .info, text: "Broadcast input needs at least two panes in the tab.")672        }673    }674675    func enableBroadcast(tab: TabID, in window: WindowState) {676        guard window.tabs.contains(where: { $0.id == tab }) else { return }677        window.broadcastTabs.insert(tab)678        lineTrackers[tab] = BroadcastGuard.LineTracker()679    }680681    func broadcastTargets(for pane: PaneID, in window: WindowState) -> [PaneID] {682        guard let index = window.tabIndex(containing: pane), window.broadcastTabs.contains(window.tabs[index].id) else { return [] }683        return window.tabs[index].layout.panes.filter { $0 != pane && sessions[$0]?.status.isRunning == true }684    }685686    private func handleUserInput(from pane: PaneID, bytes: ArraySlice<UInt8>) {687        guard let window = window(containing: pane), let index = window.tabIndex(containing: pane) else { return }688        let tab = window.tabs[index].id689        guard window.broadcastTabs.contains(tab) else { return }690        let targets = broadcastTargets(for: pane, in: window)691        guard !targets.isEmpty else { return }692        var tracker = lineTrackers[tab] ?? BroadcastGuard.LineTracker()693        let event = tracker.consume(bytes)694        lineTrackers[tab] = tracker695        if case .line(let line) = event, !line.trimmingCharacters(in: .whitespaces).isEmpty {696            let proposal = ProposedCommand(text: line, isMultiHost: true, analyzer: analyzer)697            let single = analyzer.assess(line)698            if single.level == .destructive || single.reasons.contains(.privilegeEscalation) {699                // Hold the Return key for the other panes until the user confirms this line.700                let withoutReturn = bytes.filter { $0 != 0x0d && $0 != 0x0a }701                for target in targets { sessions[target]?.send(bytes: withoutReturn) }702                let confirmation = CommandConfirmation(703                    title: "Send this command to \(targets.count) other session\(targets.count == 1 ? "" : "s")?",704                    proposal: proposal, targetDescription: "\(targets.count) broadcast panes",705                    onApproved: { [weak self] _ in for target in targets { self?.sessions[target]?.send(bytes: [0x0d]) } },706                    onCancelled: { [weak self] in for target in targets { self?.sessions[target]?.send(bytes: [0x15]) } })707                window.sheet = .commandConfirm(confirmation)708                return709            }710        }711        for target in targets { sessions[target]?.send(bytes: bytes) }712    }713714    // MARK: Paste, clipboard, links715716    func shouldPasteImmediately(_ text: String, pane: PaneID, isDrop: Bool) -> Bool {717        let assessment = PasteGuard.assess(text)718        guard PasteGuard.decide(assessment, policy: settings.pasteConfirmation) == .confirm, let window = window(containing: pane) else { return true }719        window.sheet = .pasteConfirmation(PasteRequest(pane: pane, text: text, changeCount: NSPasteboard.general.changeCount, isDrop: isDrop))720        return false721    }722723    /// Sends already-approved text as a paste, honouring bracketed paste mode.724    func sendPasteText(_ text: String, to pane: PaneID) {725        guard let session = sessions[pane] else { return }726        let clean = PasteGuard.sanitize(text, stripTrailingNewline: false)727        let bracketed = session.view.terminalStateSnapshot().bracketedPasteMode728        let payload = bracketed ? "\u{1b}[200~" + clean + "\u{1b}[201~" : clean.replacingOccurrences(of: "\n", with: "\r")729        session.view.typeText(payload)730    }731732    private func clipboardWriteRequested(_ text: String, pane: PaneID) {733        switch settings.clipboardWrite {734        case .deny: return735        case .allow:736            NSPasteboard.general.clearContents()737            NSPasteboard.general.setString(text, forType: .string)738        case .ask:739            let source = sessions[pane]?.foregroundProcessName ?? "A program"740            window(containing: pane)?.sheet = .clipboardWrite(text: text, source: source)741        }742    }743744    /// Opens a link coming from terminal output. Web and mail links open directly; local files745    /// are revealed (never launched); anything else asks first.746    func openLink(_ link: String) {747        guard let url = URL(string: link.trimmingCharacters(in: .whitespacesAndNewlines)), let scheme = url.scheme?.lowercased() else { return }748        switch LinkPolicy.decision(forScheme: scheme) {749        case .open: NSWorkspace.shared.open(url)750        case .reveal: NSWorkspace.shared.activateFileViewerSelecting([url])751        case .ask:752            if environment.confirm("Open this link?", "A program in the terminal provided a link that opens another application:\n\n\(link.prefix(300))", "Open") {753                NSWorkspace.shared.open(url)754            }755        case .block: break756        }757    }758759    // MARK: Commands from snippets / assistant760761    /// Puts a command at the prompt of a pane without running it (the user presses Return).762    func insert(command: String, into pane: PaneID) {763        guard let session = sessions[pane] else { return }764        session.insertCommand(command, execute: false)765        if let window = window(containing: pane) { focus(pane, in: window) }766    }767768    /// Asks for confirmation, then runs a command in a pane. This is the only path by which769    /// SP Term itself presses Return on the user's behalf.770    func requestRun(command: String, in pane: PaneID, source: String, title: String) {771        guard let window = window(containing: pane), let session = sessions[pane] else { return }772        let host = remoteHost(of: pane)773        let proposal = ProposedCommand(text: command, workingDirectory: session.workingDirectory, host: host, analyzer: analyzer)774        window.sheet = .commandConfirm(CommandConfirmation(title: title, proposal: proposal, targetDescription: paneTitle(pane),775                                                           onApproved: { [weak self] approved in776            guard let self else { return }777            self.sessions[pane]?.insertCommand(approved.text, execute: true)778            self.stores.history.append(HistoryEntry(command: approved.text, directory: approved.workingDirectory, host: approved.host, source: source),779                                       enabled: self.settings.recordHistory, privateMode: self.settings.privateMode,780                                       redact: { SecretRedactor().redact($0).text })781        }))782    }783784    func remoteHost(of pane: PaneID) -> String? {785        if case .ssh(let alias) = descriptor(for: pane)?.kind { return alias }786        return sessions[pane]?.reportedRemoteHost787    }788789    func paneTitle(_ pane: PaneID) -> String {790        guard let descriptor = descriptor(for: pane) else { return "Session" }791        if let custom = descriptor.customTitle, !custom.isEmpty { return custom }792        let session = sessions[pane]793        if let title = session?.reportedTitle, !title.isEmpty { return title }794        switch descriptor.kind {795        case .ssh(let alias): return alias796        case .command(let line): return line797        case .localShell:798            if let directory = session?.workingDirectory { return Formatters.abbreviate(path: directory) }799            return session?.foregroundProcessName ?? "Shell"800        }801    }802803    func tabTitle(_ tab: TabModel) -> String {804        if let custom = tab.customTitle, !custom.isEmpty { return custom }805        guard let pane = tab.focusedPane ?? tab.layout.panes.first else { return "Tab" }806        return paneTitle(pane)807    }808809    // MARK: Workspaces810811    /// Current arrangement of every window (the quick terminal is not part of workspaces).812    func currentSnapshot(name: String = "Last Session") -> WorkspaceSnapshot {813        let all = screens()814        let models: [WindowModel] = windows.map { window in815            // Remember where each session is so it reopens in the same directory.816            for index in window.tabs.indices {817                for pane in window.tabs[index].layout.panes {818                    guard let session = sessions[pane], session.reportedRemoteHost == nil, let directory = session.workingDirectory else { continue }819                    window.tabs[index].update(pane) { $0.workingDirectory = directory }820                }821            }822            let nsWindow = window.controller?.window823            let isFullScreen = nsWindow?.styleMask.contains(.fullScreen) ?? false824            let frame = isFullScreen ? window.controller?.frameBeforeFullScreen : nsWindow?.frame825            let screen = frame.flatMap { PlacementEngine.screen(containing: $0, in: all) }?.reference826            return window.snapshot(frame: frame, screen: screen, isFullScreen: isFullScreen)827        }828        return WorkspaceSnapshot(name: name, windows: models)829    }830831    func scheduleAutosave() {832        guard environment.persists, !autosaveScheduled else { return }833        autosaveScheduled = true834        DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in835            self?.autosaveScheduled = false836            self?.saveLastSession()837        }838    }839840    func saveLastSession() {841        guard environment.persists, !settings.privateMode, !windows.isEmpty else { return }842        save { try stores.lastSession.save(currentSnapshot()) }843    }844845    /// Opens the windows of a workspace on the displays available now. Processes are always new:846    /// only the arrangement, titles, session kinds and directories come from the snapshot.847    @discardableResult848    func open(workspace: WorkspaceSnapshot, keepIDs: Bool = false) -> [WindowState] {849        let snapshot = keepIDs ? workspace : workspace.instantiated()850        let placements = PlacementEngine.arrange(snapshot.windows, in: screens())851        return snapshot.windows.map { model in852            openWindow(tabs: model.tabs, selectedTab: model.selectedTab, placement: placements[model.id], id: model.id, fullScreen: model.isFullScreen)853        }854    }855856    func saveCurrentWorkspace(named name: String) {857        var snapshot = currentSnapshot(name: name)858        snapshot.id = savedWorkspaces.first { $0.name == name }?.id ?? UUID()859        savedWorkspaces.removeAll { $0.name == name }860        savedWorkspaces.append(snapshot)861        save { try stores.workspaces.save(savedWorkspaces) }862    }863864    func deleteWorkspace(_ id: UUID) {865        savedWorkspaces.removeAll { $0.id == id }866        save { try stores.workspaces.save(savedWorkspaces) }867    }868869    func open(preset: WorkspacePreset, hosts: [String] = [], agentCommands: [String] = [], replacing window: WindowState? = nil) {870        let all = screens()871        let target = preferredScreen() ?? PlacementEngine.fallbackScreen(in: all)872        let capacity = target.map { PaneCapacity.recommendedMaximum(for: $0.visibleFrame.size, cellSize: cellSize()) } ?? 4873        let directory = window?.focusedPane.flatMap { sessions[$0]?.workingDirectory } ?? keyWindowState?.focusedPane.flatMap { sessions[$0]?.workingDirectory }874        let options = PresetOptions(workingDirectory: directory, hosts: hosts, agentCommands: agentCommands, screenCount: all.count,875                                    maxPanesPerWindow: max(capacity, preset == .sshFleet ? capacity : preset.nominalPaneCount))876        let built = PresetBuilder.build(preset, options: options)877        if built.paneCount > capacity * built.windows.count, let state = window ?? keyWindowState {878            state.banner = Banner(style: .info, text: "This display comfortably fits about \(capacity) panes; \(preset.title) uses more, so panes will be small.")879        }880        open(workspace: built, keepIDs: true)881    }882883    func cellSize() -> CGSize {884        let font = TerminalSession.font(named: settings.fontName, size: CGFloat(settings.fontSize))885        let width = ("W" as NSString).size(withAttributes: [.font: font]).width886        return CGSize(width: max(width, 4), height: max(font.ascender - font.descender + font.leading, 8))887    }888889    // MARK: Display changes890891    /// Reacts to monitors being plugged, unplugged or reconfigured: every window that is no892    /// longer reachable is brought back onto an existing display. Returns the moved windows.893    @discardableResult894    func handleScreenChange(previous: [ScreenDescriptor]? = nil, current: [ScreenDescriptor]? = nil) -> [WindowID: Placement] {895        let before = previous ?? lastKnownScreens896        let after = current ?? screens()897        lastKnownScreens = after898        var frames: [WindowID: CGRect] = [:]899        for window in windows { if let frame = window.controller?.window?.frame { frames[window.id] = frame } }900        let rescued = PlacementEngine.rescue(windows: frames, previousScreens: before, currentScreens: after)901        for (id, placement) in rescued {902            windows.first { $0.id == id }?.controller?.window?.setFrame(placement.frame, display: true)903        }904        let change = ScreenChange.between(before, after)905        if !change.isEmpty {906            if !rescued.isEmpty, let window = keyWindowState {907                window.banner = Banner(style: .info, text: "\(rescued.count) window\(rescued.count == 1 ? "" : "s") moved back on screen after a display change.")908            }909            quickTerminal?.screensChanged()910            scheduleAutosave()911        }912        return rescued913    }914915    // MARK: Hosts, snippets, providers916917    func saveHosts() { save { try hostStore.save(manualHosts) } }918    func saveSnippets() { save { try stores.snippets.save(snippets) } }919    func saveProviders() { save { try providerStore.save(providers) } }920921    func openSSH(_ profile: SSHHostProfile, in window: WindowState, asSplit: Bool = false) {922        let kind = SessionKind.ssh(hostAlias: profile.host)923        if asSplit { split(axis: .horizontal, in: window, kind: kind) } else { newTab(in: window, kind: kind) }924        if let pane = window.focusedPane { rename(pane: pane, to: profile.label) }925    }926927    // MARK: Termination928929    var busySessions: [TerminalSession] { sessions.values.filter(\.isBusy) }930931    func terminateAllSessions() {932        isTerminating = true933        timer?.invalidate()934        for session in sessions.values { session.terminate() }935    }936937    // MARK: Context menu938939    func contextMenu(for pane: PaneID) -> NSMenu? {940        guard let window = window(containing: pane) else { return nil }941        focus(pane, in: window)942        return (NSApp.delegate as? AppDelegate)?.makeContextMenu(pane: pane, window: window)943    }944}945946/// A foreground command that has just ended in a pane.947struct CommandCompletion: Equatable, Identifiable {948    /// Shorter commands (`ls`, `cd`…) are not worth a signal.949    static let minimumDuration: TimeInterval = 2950    let id = UUID()951    var name: String952    var duration: TimeInterval953}954955/// What to do with a link found in terminal output, by URL scheme.956enum LinkPolicy {957    enum Decision { case open, reveal, ask, block }958959    static func decision(forScheme scheme: String) -> Decision {960        switch scheme.lowercased() {961        case "http", "https", "mailto": return .open962        case "file": return .reveal963        case "javascript", "data", "vbscript": return .block964        default: return .ask965        }966    }967}968969enum Formatters {970    static func abbreviate(path: String) -> String {971        let home = NSHomeDirectory()972        if path == home { return "~" }973        if path.hasPrefix(home + "/") { return "~" + path.dropFirst(home.count) }974        return path975    }976977    static func duration(_ seconds: TimeInterval) -> String {978        let total = Int(seconds)979        if total < 60 { return "\(total)s" }980        if total < 3600 { return "\(total / 60)m \(total % 60)s" }981        return "\(total / 3600)h \((total % 3600) / 60)m"982    }983984    static func bytes(_ count: UInt64) -> String {985        ByteCountFormatter.string(fromByteCount: Int64(count), countStyle: .memory)986    }987}988989/// Encoding of a pane being dragged by its header.990enum PaneDrag {991    static let prefix = "spterm-pane:"992    static func token(for pane: PaneID) -> String { prefix + pane.raw.uuidString }993    static func pane(from text: String) -> PaneID? {994        guard text.hasPrefix(prefix), let uuid = UUID(uuidString: String(text.dropFirst(prefix.count))) else { return nil }995        return PaneID(uuid)996    }997    /// Nearest edge of the target for a normalized drop point (origin top-left).998    static func edge(for point: CGPoint) -> DropEdge {999        let distances: [(DropEdge, CGFloat)] = [(.left, point.x), (.right, 1 - point.x), (.top, point.y), (.bottom, 1 - point.y)]1000        return distances.min { $0.1 < $1.1 }!.01001    }1002}1003
Files main
Menu

Theme