SPB Git

Repository Public

AssistantPanel.swift 17.1 KB 349 lines swift

1import AIAssistant2import Observation3import SwiftUI4import WorkspaceKit56/// What terminal content the user chose to attach to a question. Nothing is attached by default.7enum ContextSource: String, CaseIterable, Identifiable {8    case none = "Nothing"9    case selection = "Selected text"10    case screen = "Last 60 lines"11    var id: String { rawValue }12}1314/// State of the assistant panel of one window.15@MainActor16@Observable17final class AssistantModel {18    var mode: AIMode = .explain19    var source: ContextSource = .none20    var question = ""21    var preview: ContextPreview?22    var response: AIResponse?23    var proposals: [ProposedCommand] = []24    var error: String?25    var isSending = false26    /// Pane the pending preview/answer refers to.27    var pane: PaneID?28    /// Counts requests actually handed to the network layer (asserted by tests).29    private(set) var requestsSent = 030    @ObservationIgnored var transport: (any HTTPTransport)?3132    func reset() {33        preview = nil34        response = nil35        proposals = []36        error = nil37    }3839    /// Builds the exact payload that would leave the machine. No network access happens here.40    func makePreview(model: AppModel, window: WindowState) {41        reset()42        guard let provider = model.activeProvider else {43            error = "Add a provider in Settings › Intelligence first."44            return45        }46        let pane = window.focusedPane47        self.pane = pane48        let session = pane.flatMap { model.session(for: $0) }49        var attached: String?50        switch source {51        case .none: attached = nil52        case .selection:53            attached = session?.selectedText54            if attached == nil { error = "Nothing is selected in the focused session."; return }55        case .screen:56            attached = session.map { $0.bufferText().split(separator: "\n", omittingEmptySubsequences: false).suffix(60).joined(separator: "\n") }57        }58        let context = AIContext(question: question, selectedText: attached, workingDirectory: session?.workingDirectory,59                                host: pane.flatMap { model.remoteHost(of: $0) }, shell: session?.foregroundProcessName)60        do {61            // Secrets are always masked before the preview is built; the preview shows the result.62            preview = try ContextPreview.make(mode: mode, context: context, provider: provider,63                                              policy: NetworkPolicy(localOnly: model.settings.assistantLocalOnly))64        } catch let policy as NetworkPolicyError {65            error = AssistantModel.describe(policy, localOnly: model.settings.assistantLocalOnly)66        } catch {67            self.error = "Could not prepare the request: \(error)"68        }69    }7071    /// Sends the previewed payload. This is the only place a request is made, and it can only72    /// be reached from an explicit click on "Send" under the preview.73    func send(model: AppModel) async {74        guard let preview, !isSending else { return }75        let approved = model.gate.approve(preview)76        let client = AIClient(transport: transport ?? URLSessionTransport(), secrets: model.environment.secrets,77                              policy: NetworkPolicy(localOnly: model.settings.assistantLocalOnly))78        isSending = true79        error = nil80        requestsSent += 181        defer { isSending = false }82        do {83            let answer = try await client.send(approved)84            response = answer85            let session = pane.flatMap { model.session(for: $0) }86            proposals = answer.proposedCommands(workingDirectory: session?.workingDirectory, host: pane.flatMap { model.remoteHost(of: $0) })87            self.preview = nil88        } catch let failure as AIClientError {89            error = AssistantModel.describe(failure)90        } catch {91            self.error = "Request failed: \(error.localizedDescription)"92        }93    }9495    static func describe(_ error: NetworkPolicyError, localOnly: Bool) -> String {96        switch error {97        case .remoteDestinationRefused(let host): return "Local-only mode is on: “\(host)” is not this machine, so nothing was sent."98        case .insecureTransport(let host): return "Refusing to send over unencrypted HTTP to “\(host)”."99        case .unsupportedScheme(let scheme): return "Unsupported URL scheme “\(scheme)”."100        case .invalidURL: return "The provider URL is not valid."101        }102    }103104    static func describe(_ error: AIClientError) -> String {105        switch error {106        case .missingAPIKey: return "No API key is stored in the Keychain for this provider. Add it in Settings › Intelligence."107        case .policyViolation(let policy): return describe(policy, localOnly: true)108        case .api(let api): return "The provider answered \(api.status): \(api.message)"109        case .refused: return "The model declined to answer."110        case .transport(let message): return "Network error: \(message)"111        case .invalidEndpoint: return "The provider URL is not valid."112        case .secretStore(let message): return "Keychain error: \(message)"113        case .decoding(let message): return "Unexpected answer from the provider: \(message)"114        }115    }116}117118extension AppModel {119    var activeProvider: AIProviderConfig? {120        providers.first { $0.id == settings.assistantActiveProviderID } ?? providers.first121    }122123    func assistant(for window: WindowState) -> AssistantModel {124        if let existing = assistants[window.id] { return existing }125        let created = AssistantModel()126        assistants[window.id] = created127        return created128    }129}130131struct AssistantPanelView: View {132    @Bindable var state: WindowState133    let model: AppModel134135    var body: some View {136        let palette = model.palette137        let assistant = model.assistant(for: state)138        VStack(alignment: .leading, spacing: 0) {139            PanelHeader(title: "SP Intelligence", subtitle: "Optional. Bring your own key. Nothing is sent without a preview.", palette: palette)140            if !model.settings.assistantEnabled {141                VStack(alignment: .leading, spacing: 10) {142                    Text("SP Intelligence is off.").font(.system(size: 13, weight: .medium))143                    Text("When enabled, you can ask a model to explain output, suggest or draft commands, or review a diff. You choose what text is attached, you see the exact payload before it is sent, secrets are masked, and no command ever runs without your confirmation. The terminal works fully without it.")144                        .font(.system(size: 12)).foregroundStyle(palette.secondary).fixedSize(horizontal: false, vertical: true)145                    Button("Enable SP Intelligence") { model.settings.assistantEnabled = true }146                    AgentLauncherView(state: state, model: model)147                }148                .padding(12)149                Spacer()150            } else {151                AssistantBody(assistant: assistant, state: state, model: model)152            }153        }154        .background(palette.chrome)155    }156}157158private struct AssistantBody: View {159    @Bindable var assistant: AssistantModel160    @Bindable var state: WindowState161    let model: AppModel162163    var body: some View {164        let palette = model.palette165        ScrollView {166            VStack(alignment: .leading, spacing: 10) {167                HStack {168                    Picker("Mode", selection: $assistant.mode) {169                        Text("Explain").tag(AIMode.explain)170                        Text("Suggest").tag(AIMode.suggest)171                        Text("Draft command").tag(AIMode.draftCommand)172                        Text("Review diff").tag(AIMode.reviewDiff)173                        Text("Agent workspace").tag(AIMode.agentWorkspace)174                    }175                    .labelsHidden()176                    Spacer()177                    if model.settings.assistantLocalOnly {178                        Label("Local only", systemImage: "lock.shield").font(.system(size: 10, weight: .medium)).foregroundStyle(palette.success)179                    }180                }181                if let provider = model.activeProvider {182                    Text("\(provider.label) · \(provider.model.isEmpty ? "no model set" : provider.model) · \(provider.baseURL.host() ?? "")")183                        .font(.system(size: 10)).foregroundStyle(palette.secondary).lineLimit(1)184                } else {185                    Text("No provider configured. Add one in Settings › Intelligence.").font(.system(size: 11)).foregroundStyle(palette.warning)186                }187                Picker("Attach", selection: $assistant.source) {188                    ForEach(ContextSource.allCases) { Text($0.rawValue).tag($0) }189                }190                .pickerStyle(.segmented).controlSize(.small)191                .help("Terminal text is only attached when you choose it here")192                TextField(placeholder(assistant.mode), text: $assistant.question, axis: .vertical)193                    .lineLimit(3...8).textFieldStyle(.roundedBorder)194                    .accessibilityLabel("Question")195                HStack {196                    Button("Preview Request…") { assistant.makePreview(model: model, window: state) }197                        .disabled(assistant.question.trimmingCharacters(in: .whitespaces).isEmpty && assistant.source == .none)198                    if assistant.isSending { ProgressView().controlSize(.small) }199                    Spacer()200                    if assistant.response != nil || assistant.preview != nil { Button("Clear") { assistant.reset() }.controlSize(.small) }201                }202                if let error = assistant.error {203                    Text(error).font(.system(size: 12)).foregroundStyle(palette.danger).textSelection(.enabled)204                }205                if let preview = assistant.preview { previewView(preview) }206                if let response = assistant.response { responseView(response) }207                if assistant.mode == .agentWorkspace { AgentLauncherView(state: state, model: model) }208            }209            .padding(12)210            .frame(maxWidth: .infinity, alignment: .leading)211        }212    }213214    private func placeholder(_ mode: AIMode) -> String {215        switch mode {216        case .explain: return "What should be explained?"217        case .suggest: return "What are you trying to do?"218        case .draftCommand: return "Describe the command you need"219        case .reviewDiff: return "What should the review focus on?"220        case .agentWorkspace: return "Describe the task to plan across agents"221        }222    }223224    private func previewView(_ preview: ContextPreview) -> some View {225        let palette = model.palette226        return VStack(alignment: .leading, spacing: 6) {227            Text("THIS WILL BE SENT").font(.system(size: 10, weight: .bold)).foregroundStyle(palette.warning)228            Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 2) {229                GridRow { Text("To").foregroundStyle(palette.secondary); Text("\(preview.destinationHost)\(preview.isLocalDestination ? " (this Mac)" : "")") }230                GridRow { Text("Provider").foregroundStyle(palette.secondary); Text(preview.providerLabel) }231                GridRow { Text("Model").foregroundStyle(palette.secondary); Text(preview.model.isEmpty ? "—" : preview.model) }232                GridRow { Text("Size").foregroundStyle(palette.secondary); Text("\(preview.byteCount) bytes") }233                GridRow {234                    Text("Masked").foregroundStyle(palette.secondary)235                    Text(preview.findings.isEmpty ? "no secret detected" : preview.findings.map { "\($0.count)× \($0.kind.rawValue)" }.joined(separator: ", "))236                }237            }238            .font(.system(size: 11))239            ScrollView {240                Text(preview.payloadText).font(.system(size: 11, design: .monospaced)).textSelection(.enabled)241                    .frame(maxWidth: .infinity, alignment: .leading).padding(6)242            }243            .frame(maxHeight: 200)244            .background(RoundedRectangle(cornerRadius: 6).fill(palette.background))245            .accessibilityLabel("Exact text that will be sent")246            HStack {247                Button("Cancel") { assistant.preview = nil }248                Spacer()249                Button("Send") { Task { await assistant.send(model: model) } }250                    .keyboardShortcut(.defaultAction)251                    .disabled(assistant.isSending || preview.model.isEmpty)252            }253        }254        .padding(8)255        .background(RoundedRectangle(cornerRadius: 8).strokeBorder(palette.warning.opacity(0.7)))256    }257258    private func responseView(_ response: AIResponse) -> some View {259        let palette = model.palette260        return VStack(alignment: .leading, spacing: 8) {261            Text(response.text).font(.system(size: 12)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)262            if response.isTruncated { Text("The answer was cut off by the output limit.").font(.system(size: 10)).foregroundStyle(palette.warning) }263            if !assistant.proposals.isEmpty {264                Text("SUGGESTED COMMANDS — never run automatically").font(.system(size: 10, weight: .bold)).foregroundStyle(palette.secondary)265                ForEach(assistant.proposals) { proposal in266                    VStack(alignment: .leading, spacing: 4) {267                        Text(proposal.text).font(.system(size: 11, design: .monospaced)).textSelection(.enabled)268                        HStack(spacing: 6) {269                            Text(riskText(proposal.risk.level)).font(.system(size: 9, weight: .bold))270                                .padding(.horizontal, 5).padding(.vertical, 1)271                                .background(Capsule().fill(riskColor(proposal.risk.level).opacity(0.2)))272                                .foregroundStyle(riskColor(proposal.risk.level))273                            Spacer()274                            Button("Insert") {275                                if let pane = assistant.pane ?? state.focusedPane { model.insert(command: proposal.text, into: pane) }276                            }277                            .controlSize(.small).help("Place at the prompt without running")278                            Button("Review & Run…") {279                                if let pane = assistant.pane ?? state.focusedPane {280                                    model.requestRun(command: proposal.text, in: pane, source: "assistant", title: "Run this suggested command?")281                                }282                            }283                            .controlSize(.small)284                        }285                    }286                    .padding(6)287                    .background(RoundedRectangle(cornerRadius: 6).fill(palette.background))288                }289            }290            if let usage = response.usage.inputTokens, let output = response.usage.outputTokens {291                Text("\(usage) tokens in · \(output) out").font(.system(size: 9)).foregroundStyle(palette.secondary)292            }293        }294    }295296    private func riskText(_ level: RiskLevel) -> String {297        switch level {298        case .safe: return "NO KNOWN RISK"299        case .caution: return "CAUTION"300        case .destructive: return "DESTRUCTIVE"301        }302    }303304    private func riskColor(_ level: RiskLevel) -> Color {305        switch level {306        case .safe: return model.palette.success307        case .caution: return model.palette.warning308        case .destructive: return model.palette.danger309        }310    }311}312313/// Starts installed agent CLIs (Claude Code, Codex…) as ordinary programs in their own panes.314/// Their own authentication is used as-is; SP Term reads no credential and reports no fake progress:315/// the pane header shows the real process state.316struct AgentLauncherView: View {317    @Bindable var state: WindowState318    let model: AppModel319    @State private var agents: [DetectedAgentCLI] = []320321    var body: some View {322        let palette = model.palette323        VStack(alignment: .leading, spacing: 6) {324            Text("AGENT CLIS INSTALLED ON THIS MAC").font(.system(size: 10, weight: .bold)).foregroundStyle(palette.secondary)325            if agents.isEmpty {326                Text("None found (looked for claude, codex, gemini, aider, opencode…).").font(.system(size: 11)).foregroundStyle(palette.secondary)327            }328            ForEach(agents) { agent in329                HStack {330                    VStack(alignment: .leading, spacing: 0) {331                        Text(agent.cli.displayName).font(.system(size: 12, weight: .medium))332                        Text(agent.executablePath).font(.system(size: 9)).foregroundStyle(palette.secondary).lineLimit(1).truncationMode(.head)333                    }334                    Spacer()335                    Button("Open in Pane") { model.split(axis: .horizontal, in: state, kind: .command(line: agent.executablePath)) }336                        .controlSize(.small)337                }338            }339            if !agents.isEmpty {340                Button("Agent Command Center (one pane per agent)") {341                    model.open(preset: .agentCommandCenter, agentCommands: agents.prefix(3).map(\.executablePath), replacing: state)342                }343                .controlSize(.small)344            }345        }346        .task { agents = ToolLocator.agents() }347    }348}349
Files main
Menu

Theme