SPB Git

Repository Public

ClaudeService.swift 4.1 KB 93 lines swift

1import Foundation2import Observation3import ClaudeIntegration4import PersistenceCore5import os67/// Owns everything Claude-related in the app: CLI discovery, the opt-in hook receiver and the8/// verified session tracker. Nothing here touches `~/.claude`; hooks are injected per launch via9/// `claude --settings <app-private file>` and vanish when the toggle is turned off.10@MainActor11@Observable12final class ClaudeService {13    nonisolated static let logger = Logger(subsystem: "ai.spboucher.nexterm", category: "claude")1415    private(set) var cli: ClaudeCLI? { didSet { changeHandler?() } }16    private(set) var discovering = false17    /// Invoked on the main actor whenever the CLI or hook settings change (the controller rebuilds its planner).18    var changeHandler: (() -> Void)?19    let tracker = ClaudeSessionTracker()20    private(set) var hooksActive = false21    private(set) var hooksSettingsPath: String?22    private(set) var hookServerURL: String?23    private(set) var lastError: String?24    private var server: HookServer?25    private let hooksDirectory: URL2627    init(dataDirectory: String?) {28        hooksDirectory = PersistenceLocations.applicationSupportDirectory(override: dataDirectory).appendingPathComponent("hooks", isDirectory: true)29        // Never leave a stale settings file around from a previous run.30        HookSettingsWriter.remove(from: hooksDirectory)31    }3233    var isAvailable: Bool { cli != nil }3435    /// Setup guidance shown when the CLI is missing. NEXTERM never installs it.36    static let installGuidance = "Claude Code was not found on this Mac. Install it with the official instructions (https://docs.claude.com/en/docs/claude-code) — for example `brew install --cask claude-code` or `npm install -g @anthropic-ai/claude-code` — then choose Claude ▸ Re-detect CLI."3738    func refreshCLI() {39        guard !discovering else { return }40        discovering = true41        Task.detached(priority: .userInitiated) { [weak self] in42            let found = ClaudeCLIDiscovery.discover()43            await MainActor.run {44                self?.cli = found45                self?.discovering = false46                if let found { Self.logger.info("claude CLI \(found.version ?? "?", privacy: .public) at \(found.path, privacy: .public)") }47            }48        }49    }5051    /// Starts/stops the local HTTP receiver and (re)writes the app-private settings file.52    func setHooksEnabled(_ enabled: Bool) async {53        if enabled {54            guard server == nil else { return }55            do {56                let token = HookSettingsWriter.makeToken()57                let server = try HookServer(token: token) { [weak self] event in58                    Self.logger.info("hook event \(event.name, privacy: .public) session \(event.sessionID, privacy: .public): \(event.headline, privacy: .public)")59                    Task { @MainActor in self?.tracker.handle(event) }60                }61                try await server.start()62                guard let url = server.url else { throw NSError(domain: "nexterm.hooks", code: 1, userInfo: [NSLocalizedDescriptionKey: "no port"]) }63                let path = try HookSettingsWriter.write(to: hooksDirectory, url: url, token: token)64                self.server = server65                hookServerURL = url66                hooksSettingsPath = path67                hooksActive = true68                lastError = nil69                changeHandler?()70                Self.logger.info("hooks receiver listening at \(url, privacy: .public)")71            } catch {72                lastError = "Could not start the hook receiver: \(error.localizedDescription)"73                Self.logger.error("hook receiver failed: \(String(describing: error), privacy: .public)")74                hooksActive = false75            }76        } else {77            server?.stop()78            server = nil79            HookSettingsWriter.remove(from: hooksDirectory)80            hooksSettingsPath = nil81            hookServerURL = nil82            hooksActive = false83            changeHandler?()84        }85    }8687    func shutdown() {88        server?.stop()89        server = nil90        HookSettingsWriter.remove(from: hooksDirectory)91    }92}93
Files main
Menu

Theme